--- a/cmd/eqoaadmin/main.go +++ b/cmd/eqoaadmin/main.go @@ -8,6 +8,7 @@ // eqoaadmin -db eqoa.db create NAME PASSWORD [LEVEL] // eqoaadmin -db eqoa.db password NAME NEWPASSWORD // eqoaadmin -db eqoa.db classic [-dry-run] (Ascended rewards back to the game's own: classic.go) +// eqoaadmin -db eqoa.db rising [-dry-run] (EQOA Rising: the added NPCs out, on a stopped server: rising.go) // eqoaadmin -db eqoa.db backup FILE (a consistent copy, VACUUM INTO) package main @@ -36,6 +37,7 @@ create NAME PASSWORD [LEVEL] make an account (default level 0) password NAME NEWPASSWORD set an account's password classic [-dry-run] the game's own raid loot and epic rewards in place of Ascended gear + rising [-dry-run] EQOA Rising: the NPCs other servers added, out (server stopped) backup FILE write a consistent copy of the database`) } flag.Parse() @@ -156,6 +158,21 @@ fmt.Printf("classic rewards restored: %s\n", r) } + case "rising": + dry := len(args) > 1 && (args[1] == "-dry-run" || args[1] == "--dry-run") + r, err := risingCleanup(raw, dry) + if err != nil { + fail("rising: %v", err) + } + switch { + case r.total() == 0: + fmt.Println("EQOA Rising cleanup: nothing to take out (already done)") + case dry: + fmt.Printf("EQOA Rising cleanup (dry run, nothing written): %s\n", r) + default: + fmt.Printf("EQOA Rising cleanup: took out %s\n", r) + } + case "backup": need(args, 2, "backup FILE") out, err := filepath.Abs(args[1]) --- a/cmd/eqoaadmin/rising.go +++ b/cmd/eqoaadmin/rising.go @@ -0,0 +1,92 @@ +package main + +// rising.go — "eqoaadmin rising": EQOA Rising's classic cleanup. The NPCs and +// boards other servers added to the open database, which the original game +// never had, out of table npcs: GM helpers and testing extras, the gear and +// mercenary vendors, event, PvP, dungeon and housing boards, the Bug Finder +// Leaderboard and the Christmas event. By name, as they share no other mark. +// Kept on purpose: everything of the game's own (spiritmasters, waysenders and +// coachmen, merchants, guards, quest NPCs, the towns' announcement boards) and +// the extras EQOA Rising keeps (Equipment Dyers, Pet Groomers, the +// Rehabilitators, the Hardcore Leaderboard, the Memorial of the Fallen and the +// training dummies). The server reads its NPCs as it starts, so it runs on a +// stopped server. A second run finds nothing to do. + +import ( + "database/sql" + "fmt" + "strings" +) + +// risingNPCs are the names taken out (exactly, case and all). +var risingNPCs = []string{ + // GM helpers and testing extras + "Buffer", "Bruce Buffer", "Spell Archivist", + "Testing Heroes Vendor", "Teleporter", "Razeal Raid Teleporter", + // the other servers' gear + "Heirloom Outfitter", "Weapon Enchanter", + // the mercenaries (not in the game): their recruiters and Dabrish, the liaison + "Mercenary Recruitment", "Mercenary Liaison", "Dabrish", + // events, PvP, instanced dungeons, homes + "PvP Events", "Heroic Dungeons", "Dungeon Warden", "Real Estate Listings", + "Wage Cage", "Wage Cage bars", "Mr. Moogie", "Moogie's Servant", + // leaderboards + "Bug Finder Leaderboard", + // the Christmas event + "Christmas Tree", "Holiday Elf", "Toymaker Tinsel", "Santa Claus", "Santa's Sleigh", "Santa", + "Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen", + "The Grinch", "Servant of Grinch", +} + +// risingReport is what a run found: each name's rows, in risingNPCs' order. +type risingReport struct { + Names []string + Rows []int +} + +func (r risingReport) total() int { + n := 0 + for _, c := range r.Rows { + n += c + } + return n +} + +func (r risingReport) String() string { + parts := make([]string, len(r.Names)) + for i, name := range r.Names { + parts[i] = fmt.Sprintf("%s %d", name, r.Rows[i]) + } + return fmt.Sprintf("%d NPC rows (%s)", r.total(), strings.Join(parts, ", ")) +} + +// risingCleanup takes risingNPCs out of npcs in one transaction (with dry, +// only counts them). +func risingCleanup(db *sql.DB, dry bool) (risingReport, error) { + var r risingReport + tx, err := db.Begin() + if err != nil { + return r, err + } + defer tx.Rollback() + for _, name := range risingNPCs { + var n int + if err := tx.QueryRow(`SELECT COUNT(*) FROM npcs WHERE npc_name = ?`, name).Scan(&n); err != nil { + return risingReport{}, fmt.Errorf("count %q: %w", name, err) + } + if n == 0 { + continue + } + r.Names, r.Rows = append(r.Names, name), append(r.Rows, n) + if dry { + continue + } + if _, err := tx.Exec(`DELETE FROM npcs WHERE npc_name = ?`, name); err != nil { + return risingReport{}, fmt.Errorf("delete %q: %w", name, err) + } + } + if dry { + return r, nil + } + return r, tx.Commit() +} --- a/cmd/eqoaadmin/rising_test.go +++ b/cmd/eqoaadmin/rising_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "database/sql" + "path/filepath" + "testing" + + _ "modernc.org/sqlite" +) + +// EQOA Rising: "rising" takes the added NPCs out by their exact names (a dry +// run only counts them), keeps every other (the extras EQOA Rising keeps, and +// a name that matches only in another case), and a second run finds nothing. +func TestRisingCleanup(t *testing.T) { + db, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "t.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec(`CREATE TABLE npcs (id INTEGER PRIMARY KEY, npc_name TEXT)`); err != nil { + t.Fatal(err) + } + names := []string{"Buffer", "Buffer", "Mercenary Liaison", "Santa's Sleigh", "Dabrish", + "Equipment Dyer", "Pet Groomer", "Rehabilitator", "Hardcore Leaderboard", "Memorial of the Fallen", "a training dummy", "buffer", "Santa Claus Jr"} + for _, n := range names { + if _, err := db.Exec(`INSERT INTO npcs (npc_name) VALUES (?)`, n); err != nil { + t.Fatal(err) + } + } + left := func() int { + var n int + if err := db.QueryRow(`SELECT COUNT(*) FROM npcs`).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + + dry, err := risingCleanup(db, true) + if err != nil { + t.Fatal(err) + } + if dry.total() != 5 || left() != len(names) { + t.Fatalf("the dry run: %s, %d rows left (want 5 found, all %d left)", dry, left(), len(names)) + } + + r, err := risingCleanup(db, false) + if err != nil { + t.Fatal(err) + } + want := "5 NPC rows (Buffer 2, Mercenary Liaison 1, Dabrish 1, Santa's Sleigh 1)" + if r.String() != want || left() != len(names)-5 { + t.Fatalf("the run: %s, %d rows left; want %s, %d left", r, left(), want, len(names)-5) + } + var kept int + if err := db.QueryRow(`SELECT COUNT(*) FROM npcs WHERE npc_name IN ('Equipment Dyer', 'Pet Groomer', 'Rehabilitator', 'Hardcore Leaderboard', 'Memorial of the Fallen', 'a training dummy', 'buffer', 'Santa Claus Jr')`).Scan(&kept); err != nil { + t.Fatal(err) + } + if kept != 8 { + t.Fatalf("the control: %d of the 8 kept NPCs left", kept) + } + + again, err := risingCleanup(db, false) + if err != nil { + t.Fatal(err) + } + if again.total() != 0 { + t.Fatalf("a second run found %s", again) + } +} --- a/cmd/gameserver/main.go +++ b/cmd/gameserver/main.go @@ -746,6 +746,20 @@ handlers.SetRockOfFreeport(cfg.World.RockOfFreeport) // /testinvis, every player's safe mode (handlers/safemode.go) handlers.SetTestInvis(cfg.World.TestInvis) + // the rehabilitators' prices (world.rehab_prices, handlers/rehab.go) + { + rp := cfg.World.RehabPrices + price := func(v *int, unset int) int { + if v == nil { + return unset + } + return *v + } + handlers.SetRehabPrices(price(rp.TrainingPerLevel2, 100), price(rp.Masteries, 500000), price(rp.PathPerLevel2, 100)) + // the dyers' and groomers' (world.dye_prices, handlers/dyeprice.go) + dp := cfg.World.DyePrices + handlers.SetDyePrices(price(dp.Dyer, 500), price(dp.Groomer, 500)) + } // /noclip's GMs (handlers/noclip.go) handlers.SetNoclipAccounts(cfg.World.NoclipAccounts) // whose NPC row edits are written to the other shard's database too (handlers/npcmirror.go) --- a/config.yaml.example +++ b/config.yaml.example @@ -493,6 +493,25 @@ # enchanter_token: "Holly Token" # enchanter_token_id: 0 + # The rehabilitators' prices in tunar (handlers/rehab.go, EQOA Rising). A + # stat points reset costs training_per_level2 times the character's level + # squared, the Combat Masteries' reset the masteries price, both the two + # added, a path chosen again path_per_level2 times the level squared, and + # a saved build used the reset of what it changes. Unset: the values + # below; 0 makes that one free. + # rehab_prices: + # training_per_level2: 100 + # masteries: 500000 + # path_per_level2: 100 + + # The Equipment Dyers' and the Pet Groomers' prices in tunar + # (handlers/dyeprice.go, EQOA Rising): each piece of armour, robe, cape, + # shield or weapon dyed, and each part of a pet, the same at every level. + # Taking a dye off is free. Unset: the values below; 0 makes it free. + # dye_prices: + # dyer: 500 + # groomer: 500 + # --- Optional extras (each off unless set; most need their NPC or items # placed by the tool named) --- --- a/internal/config/config.go +++ b/internal/config/config.go @@ -624,6 +624,22 @@ EnchanterToken string `yaml:"enchanter_token"` EnchanterTokenID int `yaml:"enchanter_token_id"` + // RehabPrices is what a rehabilitator (handlers/rehab.go) takes in tunar + // (EQOA Rising): a stat points reset TrainingPerLevel2 times the + // character's level squared, the Combat Masteries' reset Masteries, both + // the two added, a path chosen again PathPerLevel2 times the level + // squared, and a saved build used as the reset of what it changes. + // Unset: 100, 500000 and 100 (a level 60's stat points 360,000 tunar); + // 0 makes that one free. + RehabPrices RehabPrices `yaml:"rehab_prices"` + + // DyePrices is what an Equipment Dyer and a Pet Groomer take in tunar + // (handlers/dyeprice.go, EQOA Rising): Dyer for each piece of armour, + // robe, cape, shield or weapon dyed, Groomer for each part of a pet, the + // same at every level. Taking a dye off is free. Unset: 500 and 500; 0 + // makes that one free. + DyePrices DyePrices `yaml:"dye_prices"` + // Mercs turns on the mercenaries (handlers/merc.go, entity/merc.go): a // Mercenary Liaison (tools/place_merc_liaisons.py stands one beside each // city's announcements board and Dabrish) hires one for nothing, a player @@ -1166,3 +1182,16 @@ } return max(0, *w.StartTunar) } + +// DyePrices is world.dye_prices (World.DyePrices), in tunar a piece or a part. +type DyePrices struct { + Dyer *int `yaml:"dyer"` + Groomer *int `yaml:"groomer"` +} + +// RehabPrices is world.rehab_prices (World.RehabPrices), in tunar. +type RehabPrices struct { + TrainingPerLevel2 *int `yaml:"training_per_level2"` + Masteries *int `yaml:"masteries"` + PathPerLevel2 *int `yaml:"path_per_level2"` +} --- a/internal/entity/deadplayer_test.go +++ b/internal/entity/deadplayer_test.go @@ -0,0 +1,98 @@ +package entity + +import ( + "testing" + "time" + + "github.com/eqoa/server/internal/session" +) + +// EQOA Rising: a dead player lies dead in another's view (byte 58, CLIENT's +// dying state, as a corpse's), still targetable (byte 26 as alive, for a +// rez), and walks again once it is up. The control: alive, the locomotion +// its own client reported. +func TestADeadPlayerLiesDeadInOthersView(t *testing.T) { + aw := newAssistWorld(t) + rec := func() []byte { return aw.w.serializeEntityForChannel(aw.asker, aw.b.ServerID, aLeader) } + aw.b.HP, aw.b.Animation = 100, 1 // alive, walking + alive := rec() + if alive[58] != 1 { + t.Fatalf("the control, alive and walking: byte 58 = %d, want 1", alive[58]) + } + live26 := alive[26] + aw.b.HP, aw.b.DiedAt = 0, time.Now() + dead := rec() + if dead[58] != pvpDyingState { + t.Fatalf("dead: byte 58 = %d, want %d (the dying state)", dead[58], pvpDyingState) + } + if dead[26] != live26 { + t.Fatalf("dead: byte 26 = %d, want %d as alive (targetable for a rez)", dead[26], live26) + } + aw.b.HP, aw.b.DiedAt = 1, time.Time{} + if up := rec(); up[58] != 1 { + t.Fatalf("up again: byte 58 = %d, want its walk's 1", up[58]) + } +} + +// gone reports that no slot of the sessions holds the player any more. +func gone(t *testing.T, id EntityID, ss ...*session.Session) { + t.Helper() + for _, s := range ss { + for i, e := range GetOrCreateVisibility(s).ChannelEntity { + if e == id { + t.Errorf("slot %d still holds it after its return", i) + } + } + } +} + +// EQOA Rising: a player with no PvP flag back from a death, at its respawn, +// is made anew on every client that had it on a slot (pvpRiseLocked), as a +// flagged one is: CLIENT never stands a sprite it laid down. +func TestADeadPlayerRespawnsStanding(t *testing.T) { + d := newPvP(t) + d.w.mu.Lock() + defer d.w.mu.Unlock() + now := d.at(time.Second) + d.b.HP, d.b.DiedAt = 0, now + if b := d.w.serializeEntityForChannel(d.sa, d.b.ServerID, d.aSeesB); b[58] != pvpDyingState { + t.Fatalf("dead with no flag: byte 58 %d", b[58]) + } + if due := d.w.playerRespawnSystem(now.Add(PlayerRespawnDelay)); len(due) != 1 || d.b.HP != d.b.MaxHP { + t.Fatalf("respawn: %d due, HP %d", len(due), d.b.HP) + } + gone(t, d.b.ServerID, d.sa, d.sc) + if GetOrCreateVisibility(d.sa).ChannelEntity[1] != d.c.ServerID { + t.Error("the control: another player on a slot left it too") + } +} + +// EQOA Rising: a player brought back by a rez taken (TakeRezReturn) is made +// anew on every client that had it on a slot, as at a respawn. The control: +// a No leaves it lying, on its slots. +func TestARezzedPlayerStandsUp(t *testing.T) { + d := newPvP(t) + now := d.at(time.Second) + d.w.mu.Lock() + d.b.HP, d.b.DiedAt = 0, now + d.b.RezReturn = RezReturn{World: 0, X: 100, Y: 0, Z: 100, Until: now.Add(time.Minute)} + d.w.mu.Unlock() + if _, _, _, _, ok := d.w.TakeRezReturn(d.sb, false, now); ok { + t.Fatal("a No went back") + } + if GetOrCreateVisibility(d.sa).ChannelEntity[0] != d.b.ServerID { + t.Fatal("the control: a No left its slots") + } + d.w.mu.Lock() + d.b.RezReturn = RezReturn{World: 0, X: 100, Y: 0, Z: 100, Until: now.Add(time.Minute)} + d.w.mu.Unlock() + if _, _, _, _, ok := d.w.TakeRezReturn(d.sb, true, now); !ok { + t.Fatal("a Yes did not go back") + } + d.w.mu.Lock() + defer d.w.mu.Unlock() + if d.b.respawnPending() || d.b.HP != d.b.MaxHP { + t.Fatalf("not up: died at %v, HP %d", d.b.DiedAt, d.b.HP) + } + gone(t, d.b.ServerID, d.sa, d.sc) +} --- a/internal/entity/pvp.go +++ b/internal/entity/pvp.go @@ -547,13 +547,15 @@ } } -// pvpRiseLocked is a flagged player back from a death: every client that has it on a slot makes it +// pvpRiseLocked is a player back from a death (EQOA Rising: every player, whose death everyone sees +// now, visibility.go; a flagged one's before; at a respawn and at a rez taken, resurrect.go): +// every client that has it on a slot makes it // anew under a new id at the next visibility pass. CLIENT never stands a sprite it laid down // (VICSprite::m_dead clears only in Clear, a new sprite) and vanilla keeps a body by its entity's id, // so one that watched it fall, and whose view it comes back into before its slot goes, would draw it // lying there for as long as it stayed in view. Must be called with the lock held. func (w *World) pvpRiseLocked(p *Player) { - if !p.pvpLive() || w.SessionManager == nil { + if w.SessionManager == nil { return } w.SessionManager.ForEach(func(s *session.Session) bool { --- a/internal/entity/pvp_test.go +++ b/internal/entity/pvp_test.go @@ -714,8 +714,8 @@ } // A flagged player killed falls for everyone (byte 58 CLIENT's dying state, seen only while it lies -// dead), and at its return every client that had it on a slot makes it anew under a new id; an -// unflagged player's death is as it was. +// dead), and at its return every client that had it on a slot makes it anew under a new id. EQOA +// Rising: an unflagged player's death is seen so too (deadplayer_test.go). func TestPvPDeathIsSeen(t *testing.T) { d := newPvP(t) d.flag(t, d.sa, 0) @@ -742,10 +742,10 @@ t.Errorf("dead: bytes 58, 142 %d, %d", b[58], b[142]) } } - // the control: a player with no flag, dead, is as any dead player was + // EQOA Rising: a player with no flag, dead, falls for everyone too d.c.HP, d.c.DiedAt = 0, now - if b := view(d.sa, d.c, aSeesC); b[58] == pvpDyingState { - t.Errorf("an unflagged player's death changed byte 58: %d", b[58]) + if b := view(d.sa, d.c, aSeesC); b[58] != pvpDyingState { + t.Errorf("an unflagged player's death not seen: byte 58 %d", b[58]) } d.c.HP, d.c.DiedAt = 100, time.Time{} --- a/internal/entity/resurrect.go +++ b/internal/entity/resurrect.go @@ -434,6 +434,7 @@ return 0, 0, 0, 0, false } if p.respawnPending() { + w.pvpRiseLocked(p) // EQOA Rising: each client that saw it fall makes it anew (pvp.go) p.DiedAt = time.Time{} p.HP, p.Power = p.MaxHP, p.MaxPower p.Breath = BreathFull --- a/internal/entity/resurrect_test.go +++ b/internal/entity/resurrect_test.go @@ -87,7 +87,29 @@ func (r *rezRig) respawn(d time.Duration) { r.w.mu.Lock() defer r.w.mu.Unlock() + // EQOA Rising: a player back from a death leaves every slot it was on (pvp.go's pvpRiseLocked, + // so that CLIENT makes it anew, standing), and the visibility pass after it puts it back on the + // slots of those near it: under a new id on a server, under the rig's own here, which its casts name. + type slot struct { + e EntityID + o uint32 + } + before := map[*session.Session][]slot{} + for _, s := range []*session.Session{r.sa, r.sb, r.sc} { + vs := GetOrCreateVisibility(s) + for i := range vs.ChannelEntity { + before[s] = append(before[s], slot{vs.ChannelEntity[i], vs.ChannelObjectID[i]}) + } + } r.w.playerRespawnSystem(r.at(d)) + for s, slots := range before { + vs := GetOrCreateVisibility(s) + for i, sl := range slots { + if vs.ChannelEntity[i] == 0 && sl.e != 0 { + vs.ChannelEntity[i], vs.ChannelObjectID[i] = sl.e, sl.o + } + } + } } // land runs the casts whose landing has come by d. --- a/internal/entity/visibility.go +++ b/internal/entity/visibility.go @@ -482,6 +482,16 @@ // which is what the serializer already does, so there is nothing for // the visibility path to add. buf := putPlayerUpdate(to, objectID, p) + // EQOA Rising: every dead player lies dead in the others' view, as a + // flagged one does (pvp.go's pvpViewLocked: byte 58 CLIENT's dying + // state, as a creature's corpse above), until it is up again; at its + // return each client that had it makes it anew (pvpRiseLocked). Its + // own client's reports carry only its locomotion (clientupdate.go's + // locoStates), so the others saw it standing until it went home. Byte + // 26 stays a live player's: it can still be targeted, for a rez. + if p.respawnPending() { + buf[58] = pvpDyingState + } w.duelViewLocked(sess, p.ServerID, buf) // a duel opponent as a creature (duel.go) w.pvpViewLocked(sess, p, buf) // a foe, to be swung at (pvp.go) w.ctfViewLocked(sess, p, buf) // the arena's teams by their names' colours (ctf.go) --- a/internal/handlers/cmdsearch.go +++ b/internal/handlers/cmdsearch.go @@ -37,9 +37,9 @@ // either way, any case), or one line saying there is none. func commandsBeginning(word string, gm bool) []string { prefix := strings.ToLower(strings.TrimLeft(word, "/#")) - lines := playerHelpLines + lines := playerHelpNow() if gm { - lines = append(append([]string(nil), playerHelpLines...), gmHelpLines...) + lines = append(append([]string(nil), lines...), gmHelpLines...) } var out []string for _, l := range lines { --- a/internal/handlers/dyeprice.go +++ b/internal/handlers/dyeprice.go @@ -0,0 +1,111 @@ +package handlers + +// dyeprice.go — EQOA Rising: what the Equipment Dyers (dyer.go) and the Pet +// Groomers (petgroomer.go) take for a dye (the owner, 2026-11-21: "Equipment +// Dyer (for a reasonable cost)", "Pet Groomer (for a reasonable cost)"). +// world.dye_prices: so much tunar for each piece of armour, robe, cape, +// shield or weapon dyed, and for each part of a pet, the same at every level +// (the owner, 2026-11-22: "per level is a bad decision good for respecing +// yes but it needs to be a fixed price"; unset: 500 each; 0 free). Taking a +// dye off is free. Paid as the Rehabilitators' resets are (rehab.go's pay): +// out of the purse at once, kept and sent to the client; a purse too short is +// told the price and what it holds, and nothing is dyed. + +import ( + "fmt" + "log" + + "github.com/eqoa/server/internal/entity" + "github.com/eqoa/server/internal/protocol" + "github.com/eqoa/server/internal/session" +) + +// dyePrices is world.dye_prices (SetDyePrices): tunar a piece or a part. +var dyePrices struct { + dyer, groomer int +} + +// SetDyePrices sets what a dyer takes for each piece and a groomer for each +// part they dye, at any level (world.dye_prices); 0, or below, free. +func SetDyePrices(dyer, groomer int) { + dyePrices.dyer = max(dyer, 0) + dyePrices.groomer = max(groomer, 0) +} + +// dyerPrice is a piece's dye. +func dyerPrice() int { return dyePrices.dyer } + +// groomerPrice is a pet's part's dye. +func groomerPrice() int { return dyePrices.groomer } + +// dyeCost is a dye's price: each of n pieces or parts at each; taking a dye +// off (rgba 0) is free. +func dyeCost(each, n int, rgba uint32) int { + if rgba == 0 || each <= 0 || n <= 0 { + return 0 + } + return each * n +} + +// pricePhrase is a dyer's or a groomer's price in its greeting: "free of +// charge", or "for 250 tunar a piece" (unit "a piece", "a part"). +func pricePhrase(each int, unit string) string { + if each <= 0 { + return "free of charge" + } + return fmt.Sprintf("for %s %s", tunarText(each), unit) +} + +// paidSaid is what a dye done says: done, and what it took. +func paidSaid(done string, price int) string { + if price <= 0 { + return done + } + return fmt.Sprintf("%s That was %s.", done, tunarText(price)) +} + +// dyePurseStore keeps a character's purse (database.InventoryStore's). +type dyePurseStore interface { + SetPurse(serverID uint32, tunar int) error +} + +// payForDye takes price tunar from p's purse, kept in store and sent; a purse +// too short is told so through say, and nothing is taken: false. +func payForDye(gw *entity.World, store dyePurseStore, sess *session.Session, p *entity.Player, price int, say func(string)) bool { + if price <= 0 { + return true + } + if gw == nil || p == nil { + return false + } + purse, ok := gw.TakeTunar(p.CharServerID, price) + if !ok { + have, _ := gw.TakeTunar(p.CharServerID, 0) + say(fmt.Sprintf(rehabShort, tunarText(price), tunarText(have))) + return false + } + dyePurseChanged(store, sess, p, purse) + return true +} + +// refundDye gives back n tunar paid for a dye that went wrong. +func refundDye(gw *entity.World, store dyePurseStore, sess *session.Session, p *entity.Player, n int) { + if n <= 0 || gw == nil || p == nil { + return + } + if purse, ok := gw.TakeTunar(p.CharServerID, -n); ok { + dyePurseChanged(store, sess, p, purse) + } +} + +// dyePurseChanged keeps p's purse and tells its client (rehab.go's purseChanged). +func dyePurseChanged(store dyePurseStore, sess *session.Session, p *entity.Player, purse int) { + if store != nil { + if err := store.SetPurse(p.CharServerID, purse); err != nil { + log.Printf("Dye: saving %s's purse %d: %v", p.Name, purse, err) + } + } + if sess != nil { + queueReliable(sess, protocol.OpcodePlayerTunar, tunarPayload(purse)) + } +} --- a/internal/handlers/dyeprice_test.go +++ b/internal/handlers/dyeprice_test.go @@ -0,0 +1,165 @@ +package handlers + +import ( + "fmt" + "strings" + "testing" + + "github.com/eqoa/server/internal/database" + "github.com/eqoa/server/internal/entity" +) + +// keptPurses records what a dye's price left in a purse (database.InventoryStore's SetPurse). +type keptPurses map[uint32]int + +func (k keptPurses) SetPurse(serverID uint32, tunar int) error { + k[serverID] = tunar + return nil +} + +// EQOA Rising: the dyers' and groomers' prices, fixed, for each piece or +// part dyed, a dye off free, the words of the greeting, and nothing below +// zero. +func TestDyePrices(t *testing.T) { + SetDyePrices(250, 400) + t.Cleanup(func() { SetDyePrices(0, 0) }) + if dyerPrice() != 250 || groomerPrice() != 400 { + t.Fatalf("prices: %d %d", dyerPrice(), groomerPrice()) + } + if dyeCost(250, 7, 0xD10000FF) != 1750 || dyeCost(250, 7, 0) != 0 { + t.Fatal("all armor is seven pieces' price, and a dye off is free") + } + if pricePhrase(250, "a piece") != "for 250 tunar a piece" || pricePhrase(0, "a piece") != "free of charge" { + t.Fatalf("the words: %q, %q", pricePhrase(250, "a piece"), pricePhrase(0, "a piece")) + } + SetDyePrices(-5, -5) + if dyerPrice() != 0 || groomerPrice() != 0 { + t.Fatal("a negative price is not free") + } +} + +// EQOA Rising: with prices set, the Equipment Dyer says its price a piece, +// the same at level 60 as at any (fixed), takes it for a dye (the purse +// kept and the dye done), tells a purse too short for all the armour and +// dyes nothing, and takes every dye off for nothing. The control: +// TestTheArmorDyer, prices unset, dyes for nothing. +func TestTheDyerCharges(t *testing.T) { + SetDyePrices(250, 250) + t.Cleanup(func() { SetDyePrices(0, 0) }) + tw := newTalkWorld(t, 100, 100) + db, err := database.NewSQLite(t.TempDir() + "/dyer.db") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + rec := &database.CharacterRecord{CharName: "Talker", AccountID: 1, Level: 10} + if err := database.NewSQLiteCharacterStore(db).Create(rec); err != nil { + t.Fatal(err) + } + tw.p.CharServerID, tw.p.Level, tw.p.Tunar = rec.ServerID, 60, 1000 + d := NewDyer(tw.w, db) + kept := keptPurses{} + d.purses = kept + dyer := &entity.NPC{ServerID: 3101, Name: EquipmentDyerName, NPCType: 0x80} + questMsgs(tw.s) + talk := func() []string { + t.Helper() + if !d.Talk(tw.s, tw.p, dyer) { + t.Fatal("the dyer did not answer") + } + return questMsgs(tw.s) + } + pick := func(msgs []string, n byte) []string { + t.Helper() + if !d.Answer(tw.s, tw.p, boxID(msgs), n) { + t.Fatalf("no dyer's question in %q", msgs) + } + return questMsgs(tw.s) + } + dyes := func() [database.DyeSlots]uint32 { + t.Helper() + c, err := db.CharDyes(rec.ServerID) + if err != nil { + t.Fatal(err) + } + return c + } + + got := talk() + if !hasMsg(got, "box:Equipment Dyer: I dye armor, robes, shields and weapons any color you like, for 250 tunar a piece.*") { + t.Fatalf("the greeting: %q", got) + } + got = pick(pick(pick(pick(got, 1), 0), 1), 0) // One armor piece; Chest; Reds and pinks; Red + if !hasMsg(got, "box:Equipment Dyer: There: red. That was 250 tunar.") || dyes()[database.DyeChest] != 0xD10000FF { + t.Fatalf("the chest dyed for 250: %q, %08X", got, dyes()[database.DyeChest]) + } + if tw.p.Tunar != 750 || kept[rec.ServerID] != 750 { + t.Fatalf("the purse: %d, kept %d (want 750)", tw.p.Tunar, kept[rec.ServerID]) + } + + got = pick(pick(pick(talk(), 0), 4), 5) // All armor; Blues and teals; Navy: seven pieces, 1,750 + if !hasMsg(got, "box:Equipment Dyer: "+fmt.Sprintf(rehabShort, "1,750 tunar", "750 tunar")) { + t.Fatalf("a purse too short not told: %q", got) + } + if c := dyes(); c[database.DyeChest] != 0xD10000FF || c[database.DyeLegs] != 0 || tw.p.Tunar != 750 { + t.Fatalf("a purse too short dyed (chest %08X, legs %08X) or paid (%d)", c[database.DyeChest], c[database.DyeLegs], tw.p.Tunar) + } + + got = pick(talk(), 5) // Remove all dyes + if dyes() != ([database.DyeSlots]uint32{}) || tw.p.Tunar != 750 || !hasMsg(got, "box:Equipment Dyer: Every dye is off.") { + t.Fatalf("every dye off for nothing: %08X, purse %d, %q", dyes(), tw.p.Tunar, got) + } +} + +// EQOA Rising: with prices set, a Pet Groomer takes its price a part for a +// dye (kept), tells a purse too short for both parts and dyes nothing, and +// takes every dye off for nothing; its greeting says the price, the same at +// level 20 as at any (fixed). The control: TestThePetGroomer, prices unset, +// dyes for nothing. +func TestTheGroomerCharges(t *testing.T) { + SetDyePrices(500, 500) + t.Cleanup(func() { SetDyePrices(0, 0) }) + f := newGenieFixture(t) + f.p.Level, f.p.Tunar = 20, 600 + const look = 0x8A416241 + g := NewGroomer(f.w, f.db) + kept := keptPurses{} + g.purses = kept + questMsgs(f.sess) + if !g.Talk(f.sess, f.p, &entity.NPC{ServerID: 3102, Name: "Pet Groomer", NPCType: 0x80}) { + t.Fatal("the groomer did not answer") + } + if got := questMsgs(f.sess); !hasMsg(got, "box:Pet Groomer: I groom and dye pets, for 500 tunar a part.*") { + t.Fatalf("the greeting: %q", got) + } + a := groomAsk{speaker: "Pet Groomer", look: look, pet: "Fire Elemental"} + petDyes := func() [database.PetDyeAreas]uint32 { + t.Helper() + d, err := f.db.PetDyesOf(f.p.CharServerID) + if err != nil { + t.Fatal(err) + } + return d[look] + } + + g.dye(f.sess, f.p, a, []int{1}, 0xD10000FF, "There: red.") + if got := questMsgs(f.sess); !hasMsg(got, "box:Pet Groomer: There: red. That was 500 tunar.") { + t.Fatalf("said: %q", got) + } + if petDyes() != [2]uint32{0, 0xD10000FF} || f.p.Tunar != 100 || kept[f.p.CharServerID] != 100 { + t.Fatalf("the body red for 500: %08X, purse %d, kept %d", petDyes(), f.p.Tunar, kept[f.p.CharServerID]) + } + + g.dye(f.sess, f.p, a, []int{0, 1}, 0x8A2BE2FF, "There: violet.") + if got := questMsgs(f.sess); !strings.Contains(strings.Join(got, "\n"), fmt.Sprintf(rehabShort, "1,000 tunar", "100 tunar")) { + t.Fatalf("a purse too short not told: %q", got) + } + if petDyes() != [2]uint32{0, 0xD10000FF} || f.p.Tunar != 100 { + t.Fatalf("a purse too short dyed (%08X) or paid (%d)", petDyes(), f.p.Tunar) + } + + g.dye(f.sess, f.p, a, []int{0, 1}, 0, "Every dye is off.") + if petDyes() != [2]uint32{} || f.p.Tunar != 100 { + t.Fatalf("every dye off for nothing: %08X, purse %d", petDyes(), f.p.Tunar) + } +} --- a/internal/handlers/dyer.go +++ b/internal/handlers/dyer.go @@ -176,11 +176,13 @@ // Dyer keeps each character's question in hand. type Dyer struct { - gw *entity.World - dyes dyeStore - mu sync.Mutex - seq uint32 - asked map[uint32]dyerAsk + gw *entity.World + dyes dyeStore + // purses keeps a purse a dye was paid from (EQOA Rising, dyeprice.go) + purses dyePurseStore + mu sync.Mutex + seq uint32 + asked map[uint32]dyerAsk } // dyerAsk is a question asked: its box, which question (askWhat...), what @@ -246,9 +248,11 @@ d.say(sess, speaker, "My vats are dry today.") return } - greeting := "I dye armor, robes, shields and weapons any color you like, free of charge. Only those who see the live game's colors see a dye." + // EQOA Rising: its price a piece (dyeprice.go) + price := pricePhrase(dyerPrice(), "a piece") + greeting := fmt.Sprintf("I dye armor, robes, shields and weapons any color you like, %s. Only those who see the live game's colors see a dye.", price) if entity.CapesOn() { - greeting = "I dye armor, robes, capes, shields and weapons any color you like, free of charge. Only those who see the live game's colors see a dye." + greeting = fmt.Sprintf("I dye armor, robes, capes, shields and weapons any color you like, %s. Only those who see the live game's colors see a dye.", price) } d.say(sess, speaker, greeting) room := dialogRoom(sess) @@ -380,6 +384,11 @@ d.say(sess, speaker, "Something went wrong with my vats. Try again.") return } + // EQOA Rising: paid first, a price a piece; a dye off is free (dyeprice.go) + price := dyeCost(dyerPrice(), len(slots), rgba) + if !payForDye(d.gw, d.purses, sess, p, price, func(line string) { d.say(sess, speaker, line) }) { + return + } who := database.GMEdit{AccountID: sess.AccountID(), Via: "game"} if addr := sess.RemoteAddr(); addr != nil { who.IP = addr.IP.String() @@ -387,6 +396,7 @@ for _, s := range slots { if _, _, err := d.dyes.SetCharDye(p.CharServerID, s, rgba, who, "the Armor Dyer"); err != nil { log.Printf("Dyer: %s's %s: %v", p.Name, database.DyeSlotNames[s], err) + refundDye(d.gw, d.purses, sess, p, price) d.say(sess, speaker, "Something went wrong with my vats. Try again.") return } @@ -395,7 +405,7 @@ if d.gw != nil { d.gw.SetDyes(p.CharServerID, entity.Dyes(cur)) } - d.say(sess, speaker, done) + d.say(sess, speaker, paidSaid(done, price)) names := make([]string, len(slots)) for i, s := range slots { names[i] = database.DyeSlotNames[s] --- a/internal/handlers/hidemercs.go +++ b/internal/handlers/hidemercs.go @@ -103,6 +103,11 @@ // mercenaries hidden, once a login, that they are (OnPlayerEntered). func tellMercsHidden(w *entity.World) func(sess *session.Session, p *entity.Player) { return func(sess *session.Session, p *entity.Player) { + // EQOA Rising: with mercenaries off (world.mercs) there are none to + // hide, and the line only spoke of a feature this server has not + if !MercsOn() { + return + } if on, ok := w.MercsHidden(sess); ok && on { SendColoredChat(sess, mercsHiddenLoginLine, 255, 255, 0) } --- a/internal/handlers/hidemercs_test.go +++ b/internal/handlers/hidemercs_test.go @@ -1,6 +1,7 @@ package handlers import ( + "strings" "testing" "github.com/eqoa/server/internal/database" @@ -62,6 +63,8 @@ // on by default) and is told so once in the world; one that chose /show mercs // keeps them shown and is told nothing; one that chose /hide mercs hides them. func TestHideMercsOutlivesALogin(t *testing.T) { + SetMercs(true) // EQOA Rising: the line is said only where there are mercenaries + t.Cleanup(func() { SetMercs(false) }) db, chars := newSafeDB(t) c := newChatWorld(t) h := &CharacterHandler{store: chars, gameWorld: c.gw} @@ -95,4 +98,38 @@ if got := heard(t, plain); len(got) != 0 { t.Fatalf("a login showing the mercs told %q", texts(got)) } + // EQOA Rising: with mercenaries off, a login with them hidden is told + // nothing (the control: the same login above, with them on, was told) + SetMercs(false) + flushQueue(s) // heard peeks: the line above is still queued + tell(s, p) + if got := heard(t, s); len(got) != 0 { + t.Fatalf("mercenaries off: the login told %q", texts(got)) + } +} + +// EQOA Rising: /help names /hide mercs only where there are mercenaries +// (world.mercs); every other line is there either way. +func TestHelpNamesHideMercsOnlyWithMercs(t *testing.T) { + has := func(lines []string) bool { + for _, l := range lines { + if strings.Contains(l, "/hide mercs") { + return true + } + } + return false + } + SetMercs(false) + off := playerHelpNow() + if has(off) || len(off) != len(playerHelpLines)-1 { + t.Fatalf("mercenaries off: %d lines, /hide mercs %v", len(off), has(off)) + } + if got := commandsBeginning("/hide", false); has(got) { + t.Fatalf("mercenaries off: /hide ? found %q", got) + } + SetMercs(true) + t.Cleanup(func() { SetMercs(false) }) + if on := playerHelpNow(); !has(on) || len(on) != len(playerHelpLines) { + t.Fatalf("the control, mercenaries on: %d lines, /hide mercs %v", len(on), has(on)) + } } --- a/internal/handlers/petgroomer.go +++ b/internal/handlers/petgroomer.go @@ -91,11 +91,13 @@ // Groomer keeps each character's question in hand. type Groomer struct { - gw *entity.World - dyes petDyeStore - mu sync.Mutex - seq uint32 - asked map[uint32]groomAsk + gw *entity.World + dyes petDyeStore + // purses keeps a purse a dye was paid from (EQOA Rising, dyeprice.go) + purses dyePurseStore + mu sync.Mutex + seq uint32 + asked map[uint32]groomAsk } // groomAsk is a question asked: its box, which question (groomWhat...), the @@ -162,16 +164,18 @@ g.say(sess, speaker, "My brushes are packed away today.") return } + // EQOA Rising: its price a part (dyeprice.go) + price := pricePhrase(groomerPrice(), "a part") pet, ok := g.gw.PetLookOf(sess) if !ok { - g.say(sess, speaker, "I groom and dye pets, free of charge. Call yours to your side and I will color its coat. Only those who see the live game's colors see a dye.") + g.say(sess, speaker, fmt.Sprintf("I groom and dye pets, %s. Call yours to your side and I will color its coat. Only those who see the live game's colors see a dye.", price)) return } - line := fmt.Sprintf("What a fine %s! I dye pets any color you like, free of charge, and it keeps its colors for this form. Only those who see the live game's colors see a dye.", pet.Name) + line := fmt.Sprintf("What a fine %s! I dye pets any color you like, %s, and it keeps its colors for this form. Only those who see the live game's colors see a dye.", pet.Name, price) if pet.Rule { - line = fmt.Sprintf("What a fine %s! I dye a pet's clothing one color and its body another, as the dyers two-tone armor, free of charge, and it keeps its colors for this form. Only those who see the live game's colors see a dye.", pet.Name) + line = fmt.Sprintf("What a fine %s! I dye a pet's clothing one color and its body another, as the dyers two-tone armor, %s, and it keeps its colors for this form. Only those who see the live game's colors see a dye.", pet.Name, price) if !pet.Clothed { - line = fmt.Sprintf("What a fine %s! It wears no clothing, so I dye its whole body, any color you like, free of charge, and it keeps its colors for this form. Only those who see the live game's colors see a dye.", pet.Name) + line = fmt.Sprintf("What a fine %s! It wears no clothing, so I dye its whole body, any color you like, %s, and it keeps its colors for this form. Only those who see the live game's colors see a dye.", pet.Name, price) } } g.say(sess, speaker, line) @@ -256,6 +260,11 @@ // dye writes the areas' colour on the asked body and puts the character's pet // dyes on it where it stands. func (g *Groomer) dye(sess *session.Session, p *entity.Player, a groomAsk, areas []int, rgba uint32, done string) { + // EQOA Rising: paid first, a price a part; a dye off is free (dyeprice.go) + price := dyeCost(groomerPrice(), len(areas), rgba) + if !payForDye(g.gw, g.purses, sess, p, price, func(line string) { g.say(sess, a.speaker, line) }) { + return + } who := database.GMEdit{AccountID: sess.AccountID(), Via: "game"} if addr := sess.RemoteAddr(); addr != nil { who.IP = addr.IP.String() @@ -263,12 +272,13 @@ for _, area := range areas { if _, _, err := g.dyes.SetPetDye(p.CharServerID, a.look, area, rgba, who, "the Pet Groomer"); err != nil { log.Printf("Groomer: %s's pet 0x%08X area %d: %v", p.Name, a.look, area+1, err) + refundDye(g.gw, g.purses, sess, p, price) g.say(sess, a.speaker, "Something went wrong with my dyes. Try again.") return } } g.reload(p.CharServerID) - g.say(sess, a.speaker, done) + g.say(sess, a.speaker, paidSaid(done, price)) log.Printf("Groomer: %s's %s (0x%08X) areas %v: %s", p.Name, a.pet, a.look, areas, database.FormatDye(rgba)) } --- a/internal/handlers/raidcmds.go +++ b/internal/handlers/raidcmds.go @@ -418,9 +418,24 @@ " /hide mercs, /show mercs - other players' mercenaries out of your view, or back", } -// playerHelp is /help: playerHelpLines, and to a GM where its own commands are. -func (h *ChatHandler) playerHelp(sess *session.Session) { +// playerHelpNow is /help's lines as this server has them. EQOA Rising: with +// mercenaries off (world.mercs) no /hide mercs line, there being none to hide. +func playerHelpNow() []string { + if MercsOn() { + return playerHelpLines + } + out := make([]string, 0, len(playerHelpLines)) for _, l := range playerHelpLines { + if !strings.Contains(l, "/hide mercs") { + out = append(out, l) + } + } + return out +} + +// playerHelp is /help: playerHelpNow, and to a GM where its own commands are. +func (h *ChatHandler) playerHelp(sess *session.Session) { + for _, l := range playerHelpNow() { SendClientMessage(sess, l) } if h.isGM(sess) { --- a/internal/handlers/raidcmds_test.go +++ b/internal/handlers/raidcmds_test.go @@ -68,7 +68,7 @@ flushQueue(alice) c.say(alice, l) got := texts(heard(t, alice)) - if len(got) < len(playerHelpLines) || got[0] != playerHelpLines[0] { + if len(got) < len(playerHelpNow()) || got[0] != playerHelpLines[0] { t.Fatalf("%s: %q", l, got) } } --- a/internal/handlers/registry.go +++ b/internal/handlers/registry.go @@ -692,10 +692,16 @@ chatHandler.SetDyeStore(charStore.DB()) // the Armor Dyers (dyer.go) dye as #dye does interactHandler.dyer = NewDyer(gameWorld, charStore.DB()) + if invStore != nil { + interactHandler.dyer.purses = invStore // EQOA Rising: a dye's price kept (dyeprice.go) + } // the Weapon Enchanters (enchanter.go): a held copy's own auras interactHandler.enchanter = NewEnchanter(gameWorld, charStore.DB()) // the Pet Groomers (petgroomer.go) dye a pet's two areas as the dyers dye armour interactHandler.groomer = NewGroomer(gameWorld, charStore.DB()) + if invStore != nil { + interactHandler.groomer.purses = invStore // EQOA Rising: a dye's price kept (dyeprice.go) + } // the lamps' genies (genie.go): the bank, an outfitter's wares, the forge genie := NewGenie(gameWorld, charStore.DB(), npcWindowHandler) interactHandler.genie, equipHandler.genie = genie, genie --- a/internal/handlers/rehab.go +++ b/internal/handlers/rehab.go @@ -89,6 +89,44 @@ rehabAskChange = "Shall I make the change?" ) +// EQOA Rising: what a rehabilitator says of its price (world.rehab_prices). +const ( + rehabCosts = "It will cost you %s." + rehabShort = "That costs %s, and you carry %s. Come back when you can pay." +) + +// rehabPrices is what the rehabilitators take in tunar (world.rehab_prices, +// SetRehabPrices): a stat points reset trainingPerLevel2 times the level +// squared, the masteries' reset masteries, a path pathPerLevel2 times the +// level squared. Zero (as before main sets them, and in tests) is free. +var rehabPrices struct { + trainingPerLevel2, masteries, pathPerLevel2 int +} + +// SetRehabPrices sets the rehabilitators' prices (world.rehab_prices). +func SetRehabPrices(trainingPerLevel2, masteries, pathPerLevel2 int) { + rehabPrices.trainingPerLevel2 = max(trainingPerLevel2, 0) + rehabPrices.masteries = max(masteries, 0) + rehabPrices.pathPerLevel2 = max(pathPerLevel2, 0) +} + +// resetPrice is what a reset on terms t costs a character of level lv. +func resetPrice(lv int, t rehabTerms) int { + n := 0 + if t.training { + n += rehabPrices.trainingPerLevel2 * lv * lv + } + if t.mastery { + n += rehabPrices.masteries + } + return n +} + +// pathPrice is what a path chosen again costs a character of level lv. +func pathPrice(lv int) int { + return rehabPrices.pathPerLevel2 * lv * lv +} + // The menus' answers, and what a confirmation does. const ( rehabMastery = iota + 1 @@ -368,6 +406,9 @@ } } r.say(sess, speaker, is) + if !r.quote(sess, p, speaker, resetPrice(p.Level, t)) { + return + } r.ask(sess, p, &rehabBox{speaker: speaker, stage: rehabStageConfirm, what: what, terms: t}, rehabAskBegin, []string{rehabYes, rehabNotNow}) } @@ -384,6 +425,11 @@ r.askReset(sess, p, b.speaker, b.what) // the parts moved: asked again return } + price := resetPrice(p.Level, t) + if !r.pay(sess, p, price) { + r.say(sess, b.speaker, fmt.Sprintf(rehabShort, tunarText(price), tunarText(r.purse(p)))) + return + } var lines []string didM, didT, trouble := false, false, false if t.mastery { @@ -414,20 +460,26 @@ } } if !didM && !didT { + r.refund(sess, p, price) r.say(sess, b.speaker, rehabNothing) return } + // a part asked and not done is given back + if owed := resetPrice(p.Level, rehabTerms{mastery: didM, training: didT}); owed < price { + r.refund(sess, p, price-owed) + price = owed + } if didM { - r.count(p, database.ResetMastery) + r.count(p, database.ResetMastery, resetPrice(p.Level, rehabTerms{mastery: true})) } if didT { - r.count(p, database.ResetTraining) + r.count(p, database.ResetTraining, resetPrice(p.Level, rehabTerms{training: true})) } if trouble { lines = append(lines, "Something went wrong keeping it: tell a GM.") } r.say(sess, b.speaker, rehabDone+" "+strings.Join(lines, " ")) - log.Printf("Rehab: %s reset (masteries %v, stat points %v), free", p.Name, didM, didT) + log.Printf("Rehab: %s reset (masteries %v, stat points %v), %d tunar", p.Name, didM, didT, price) } // --- paths --- @@ -839,6 +891,9 @@ return } r.say(sess, speaker, r.swapLines(u)...) + if !r.quote(sess, p, speaker, pathPrice(p.Level)) { + return + } r.ask(sess, p, &rehabBox{speaker: speaker, stage: rehabStageConfirm, what: rehabPath, swap: u}, rehabAskChange, []string{rehabChangeYes, rehabNotNow}) } @@ -869,6 +924,11 @@ r.askSwap(sess, p, b.speaker, u.pick, u.to) // the pick moved: asked again return } + price := pathPrice(p.Level) + if !r.pay(sess, p, price) { + r.say(sess, b.speaker, fmt.Sprintf(rehabShort, tunarText(price), tunarText(r.purse(p)))) + return + } var gone []string if r.cm != nil && len(u.out) > 0 { gone = r.cm.takeAbilitiesFrom(sess, p.CharServerID, u.out) @@ -897,7 +957,7 @@ } } r.quests().setPick(p.CharServerID, u.pick.pq.quest.ID, u.pick.step, u.to) - r.count(p, database.ResetPath) + r.count(p, database.ResetPath, price) opts := u.pick.options() var what []string @@ -914,21 +974,83 @@ if len(what) > 0 { r.say(sess, "", strings.Join(what, " ")) } - log.Printf("Rehab: %s changed %q step %d from %q to %q (out %v, in %v, back %v, given %v, missing %v, inferred %v), free", + log.Printf("Rehab: %s changed %q step %d from %q to %q (out %v, in %v, back %v, given %v, missing %v, inferred %v), %d tunar", p.Name, u.pick.pq.quest.Name, u.pick.step, opts[u.pick.option].Answer, opts[u.to].Answer, gone, spellNames(u.in), - back, given, u.missing, u.pick.inferred) + back, given, u.missing, u.pick.inferred, price) } // --- the counts and the items --- -// count counts a reset the character had: every one is free (counted as -// used), and the paid column keeps what was paid before they were. -func (r *Rehab) count(p *entity.Player, kind string) { - if err := r.rows.CountReset(p.CharServerID, kind, true, r.now()); err != nil { +// count counts a reset the character had, free when it paid nothing (EQOA +// Rising: world.rehab_prices). +func (r *Rehab) count(p *entity.Player, kind string, paid int) { + if err := r.rows.CountReset(p.CharServerID, kind, paid <= 0, r.now()); err != nil { log.Printf("Rehab: %s's %s reset not counted: %v", p.Name, kind, err) } } +// quote says what something costs (price), or that the purse is short and +// it cannot be had: false then. Nothing to pay says nothing. +func (r *Rehab) quote(sess *session.Session, p *entity.Player, speaker string, price int) bool { + if price <= 0 { + return true + } + if purse := r.purse(p); purse < price { + r.say(sess, speaker, fmt.Sprintf(rehabShort, tunarText(price), tunarText(purse))) + return false + } + r.say(sess, speaker, fmt.Sprintf(rehabCosts, tunarText(price))) + return true +} + +// purse is the character's purse now (0 when it is not in the world). +func (r *Rehab) purse(p *entity.Player) int { + if r.gw == nil { + return 0 + } + n, _ := r.gw.TakeTunar(p.CharServerID, 0) + return n +} + +// pay takes price tunar from the character's purse, kept and sent; false, +// nothing taken, when the purse is short. Nothing to pay is paid at once. +func (r *Rehab) pay(sess *session.Session, p *entity.Player, price int) bool { + if price <= 0 { + return true + } + if r.gw == nil { + return false + } + purse, ok := r.gw.TakeTunar(p.CharServerID, price) + if !ok { + return false + } + r.purseChanged(sess, p, purse) + return true +} + +// refund gives n tunar back: what was paid for and not done. +func (r *Rehab) refund(sess *session.Session, p *entity.Player, n int) { + if n <= 0 || r.gw == nil { + return + } + if purse, ok := r.gw.TakeTunar(p.CharServerID, -n); ok { + r.purseChanged(sess, p, purse) + } +} + +// purseChanged keeps the character's purse and tells its client. +func (r *Rehab) purseChanged(sess *session.Session, p *entity.Player, purse int) { + if r.inv != nil { + if err := r.inv.SetPurse(p.CharServerID, purse); err != nil { + log.Printf("Rehab: saving %s's purse %d: %v", p.Name, purse, err) + } + } + if sess != nil { + queueReliable(sess, protocol.OpcodePlayerTunar, tunarPayload(purse)) + } +} + // takeItems takes n of an item from where the character holds it, a record // at a time: unworn in its pack first (0x003C), then its bank (0x1250, under // bankMu), kept. It returns how many it took. --- a/internal/handlers/rehabprice_test.go +++ b/internal/handlers/rehabprice_test.go @@ -0,0 +1,82 @@ +package handlers + +import ( + "fmt" + "testing" + + "github.com/eqoa/server/internal/database" + "github.com/eqoa/server/internal/protocol" +) + +// EQOA Rising: with prices set (world.rehab_prices) a stat points reset says +// its price when asked, takes it when done (the purse kept and sent) and is +// counted paid; a purse short of it is told so and asked nothing. The +// control: TestRehabStatPointsResetAlwaysFree, prices unset, keeps the purse. +func TestRehabStatPointsResetPaid(t *testing.T) { + SetRehabPrices(100, 500000, 100) + t.Cleanup(func() { SetRehabPrices(0, 0, 0) }) + f := newRehabFixture(t) + price := 100 * 60 * 60 // a level 60's stat points + + f.purse(price - 1) + f.spendTraining(5, 3) + f.resets() + m := f.pick(1) + if q, _ := asked(m); q != "" { + t.Fatalf("a short purse was asked %q (%q)", q, m) + } + if !rehabSays(m, fmt.Sprintf(rehabShort, tunarText(price), tunarText(price-1))) { + t.Errorf("a short purse not told: %q", m) + } + if f.purseNow() != price-1 { + t.Errorf("a short purse changed: %d", f.purseNow()) + } + + f.purse(800_000) + f.resets() + m = f.pick(1) + if q, _ := asked(m); q != rehabAskBegin { + t.Fatalf("the question: %q (%q)", q, m) + } + if !rehabSays(m, fmt.Sprintf(rehabCosts, tunarText(price))) { + t.Errorf("the price not said: %q", m) + } + m = f.pick(0) + if !rehabSays(m, "8 training points are yours to spend again.") { + t.Errorf("the reset's lines: %q", m) + } + if u, p := f.counts(database.ResetTraining); u != 0 || p != 1 || f.purseNow() != 800_000-price { + t.Errorf("used %d paid %d, purse %d (want %d)", u, p, f.purseNow(), 800_000-price) + } + if !hasMsg(m, fmt.Sprintf("op:%04X", uint16(protocol.OpcodePlayerTunar))) { + t.Errorf("the client not told of its purse: %q", m) + } +} + +// EQOA Rising: the prices by level and part, and nothing below zero. +func TestRehabPrices(t *testing.T) { + SetRehabPrices(100, 500000, 100) + t.Cleanup(func() { SetRehabPrices(0, 0, 0) }) + for _, c := range []struct { + lv int + t rehabTerms + want int + }{ + {10, rehabTerms{training: true}, 10_000}, + {60, rehabTerms{training: true}, 360_000}, + {60, rehabTerms{mastery: true}, 500_000}, + {60, rehabTerms{mastery: true, training: true}, 860_000}, + {60, rehabTerms{}, 0}, + } { + if got := resetPrice(c.lv, c.t); got != c.want { + t.Errorf("level %d %+v: %d, want %d", c.lv, c.t, got, c.want) + } + } + if got := pathPrice(30); got != 90_000 { + t.Errorf("a level 30's path: %d", got) + } + SetRehabPrices(-5, -5, -5) + if resetPrice(60, rehabTerms{mastery: true, training: true}) != 0 || pathPrice(60) != 0 { + t.Error("a negative price is not free") + } +} --- a/internal/handlers/rehabtemplates.go +++ b/internal/handlers/rehabtemplates.go @@ -538,6 +538,9 @@ return } r.say(sess, speaker, r.useLines(pl, t, speaker)...) + if !r.quote(sess, p, speaker, resetPrice(p.Level, templateTerms(pl))) { + return + } r.ask(sess, p, &rehabBox{speaker: speaker, stage: rehabStageConfirm, what: rehabTplUse, slot: slot, tpl: useTerms(pl, t)}, rehabAskBegin, []string{rehabYes, rehabNotNow}) } @@ -570,8 +573,14 @@ r.say(sess, b.speaker, fmt.Sprintf(rehabAlreadySpent, b.slot)) return } + price := resetPrice(p.Level, templateTerms(pl)) + if !r.pay(sess, p, price) { + r.say(sess, b.speaker, fmt.Sprintf(rehabShort, tunarText(price), tunarText(r.purse(p)))) + return + } pl, st, ok := r.gw.ApplyRespec(sess, from, t.TP, templateRanks(t), k) if !ok { + r.refund(sess, p, price) return } trouble := false @@ -592,7 +601,7 @@ SendTrainingPointsSpent(sess, int32(pl.TPBefore-pl.TPAfter)) } sendStatsOf(r.gw, sess) - r.count(p, database.ResetTemplate) + r.count(p, database.ResetTemplate, price) lines := []string{fmt.Sprintf("%s You have spent %s.", rehabDone, r.spendText(planSpent(pl).TP, planSpent(pl).CMs)), leftText(pl, "are yours to spend")} @@ -657,3 +666,13 @@ } queueReliable(who, protocol.OpcodeClassMasteryServer, cmPoints(pl.After)) } + +// templateTerms is what using a saved build resets, for its price (EQOA +// Rising: world.rehab_prices): the training points when they move, the +// masteries when a rank or the points do. +func templateTerms(pl entity.RespecPlan) rehabTerms { + return rehabTerms{ + training: pl.TPFrom != pl.TPTo || pl.TPBefore != pl.TPAfter, + mastery: len(pl.Removed) > 0 || len(pl.Added) > 0 || pl.Before.Points != pl.After.Points || pl.Before.Spent != pl.After.Spent, + } +}