Workbench panels
A plugin can add tabs to the Workbench, for tools that belong next to Wraith’s own, like the Unity plugin’s Unity tab with its Scene.
They’re advanced because of where they run. The Workbench is a window of its own, with a thread of its own, so a panel draws on a third thread: not the render thread or the game thread. Read that page first.
Adding one
Section titled “Adding one”ui.addWorkbenchPanel(options, draw) takes WorkbenchPanel.Options and a draw function, and gives back the panel. Each panel is a tab of its own, a docked window like Wraith’s. Draw with the same ImGui calls as overlay windows. Don’t start a window of your own, since the panel’s already one.
import { Wraith } from "wraith";
const imgui = Wraith.imgui();let party: string[] = [];
Wraith.threads().onTick(() => { party = readParty();});
const panel = Wraith.ui().addWorkbenchPanel({ title: "Party" }, () => { for (const name of party) imgui.TextUnformatted(name);});local Wraith = require("wraith").Wraith
local imgui = Wraith.imgui()local party = {}
Wraith.threads():onTick(function() party = read_party()end)
local panel = Wraith.ui():addWorkbenchPanel({ title = "Party" }, function() for _, name in ipairs(party) do imgui:TextUnformatted(name) endend)The panel’s on another thread, so keep what it shows in a volatile field and swap in a new one each tick. More on that below.
volatile string[] party = [];
// in Startvar imgui = ImGui.Instance;
Threads.Instance.OnTick(() => party = ReadParty());
panel = Ui.Instance.AddWorkbenchPanel(new WorkbenchPanel.Options { Title = "Party" }, () =>{ foreach (var name in party) imgui.TextUnformatted(name);});The panel’s on another thread, so swap in what it shows whole each tick, under a lock that’s only held to swap. More on that below.
#include <memory>#include <mutex>#include <string>#include <vector>
using Party = std::vector<std::string>;static std::mutex lock;static std::shared_ptr<const Party> party = std::make_shared<Party>();
Party read_party();
static std::shared_ptr<const Party> latest() { std::lock_guard held(lock); return party;}
// in startwraith::api().threads().onTick(sal::keep<Wraith::Threads::Tick>([] { auto next = std::make_shared<const Party>(read_party()); std::lock_guard held(lock); party = next;}));auto panel = wraith::api().ui().addWorkbenchPanel({.title = sal::String::of("Party")}, sal::keep<Wraith::WorkbenchPanel::Draw>([] { for (const auto& name : *latest()) wraith::api().imgui().TextUnformatted(name.c_str());}));The panel’s on another thread, so swap in what it shows whole each tick, under a lock that’s only held to swap. More on that below.
use std::sync::{Arc, Mutex};
use salamander::Str;use wraith::{ThreadsTick, WorkbenchPanelDraw, WorkbenchPanelOptions};
static PARTY: Mutex<Option<Arc<Vec<String>>>> = Mutex::new(None);
fn read_party() -> Vec<String> { Vec::new()}
fn add_panel() -> Option<()> { let api = wraith::api(); api.threads() .on_tick(ThreadsTick::keep(|| { let next = Arc::new(read_party()); *PARTY.lock().unwrap() = Some(next); })) .ok()?; let panel = api.ui().add_workbench_panel( WorkbenchPanelOptions { title: Str::new("Party"), ..Default::default() }, WorkbenchPanelDraw::keep(|| { let party = PARTY.lock().unwrap().clone(); let imgui = wraith::api().imgui(); for name in party.iter().flat_map(|p| p.iter()) { let text = name.as_bytes().as_ptr_range(); imgui.text_unformatted_ex(text.start, text.end); } }), ); Some(())}ctx.wraith.ui().addWorkbenchPanel works as in other languages. The SDK’s sdk.workbench.addPanel is a Zig helper that takes your context and a method.
self.panel = try sdk.workbench.addPanel(self, drawPanel, .{ .title = "Party" });
fn drawPanel(self: *Plugin) void { // The Workbench's thread const party = self.party.read() orelse return sdk.ui.textDisabled("Waiting for the game", .{}); defer party.end(); for (party.value.names) |name| sdk.ui.text("{s}", .{name});}The panel’s on another thread, so keep what it shows in a copy you swap in whole each tick, under a lock that’s only held to swap, like an SRW lock on Windows. More on that below.
static void draw_panel(uintptr_t self) { (void)self; /* Take the lock, copy or take the newest party, let go, then draw it */ Wraith_ImGui_TextUnformatted(Wraith_Api_imgui(w), "Party");}
static const Wraith_WorkbenchPanel_Draw_table panel_table = { SAL_TABLE(Wraith_WorkbenchPanel_Draw), .call = draw_panel };
/* in start */Wraith_WorkbenchPanel_Options options = { .title = SAL_STR("Party") };Wraith_WorkbenchPanel panel = Wraith_Ui_addWorkbenchPanel(Wraith_Api_ui(w), options, (Wraith_WorkbenchPanel_Draw){ 0, &panel_table });Options says where it goes and what it is:
title: its tab’s label.kind: what it is, likesheets, andid: which one, for several of a kind at once, like an address. Together they’re how Wraith remembers where it was moved, so keep them the same each time. An emptykinduses the title.place:top, with the documents,bottom, with Addresses, orleft, with Search. Only the first time it shows; after that it’s wherever it was left. It can be closed, and comes back from View, or when youfocus()it.order: lower comes first among tabs in the same place. Wraith’s own are 100 apart from 100, and 0 is after them.parent: inside another tab instead, as one of its tabs, below.
It opens itself behind what you’re looking at.
Tabs inside tabs
Section titled “Tabs inside tabs”A tab with parent goes inside the tab it names, as one of its tabs, like Scene and Classes in the Unreal tab. Name one of your own by its kind, like unreal, another plugin’s as plugin/kind, or Wraith’s Debug and Diagnostics as wraith/debug and wraith/diagnostics. It’s still a panel of its own: isOpen() says whether it’s the one in front, and focus() brings the tab it’s in to the front, on it.
The tab holding them is a WorkbenchTab, below, whose describe says parts. It draws nothing of its own, only the tabs that name it, in their order. In Zig, sdk.workbench.Holder is one:
holder: sdk.workbench.Holder = .{ .options = .{ .title = "Unreal", .kind = "unreal" } },
_ = try sdk.workbench.addHolder(&self.holder);self.scene = try sdk.workbench.addPanel(self, drawScene, .{ .title = "Scene", .kind = "scene", .parent = "unreal" });isOpen() says whether its tab’s showing, so you can skip work for a panel nobody’s looking at. focus() brings it to the front. remove() takes it out, and it goes anyway when your plugin does.
ui.showClass("Game.Player") opens a C# class in Classes, from anywhere.
Tabs with more to say, and many at once
Section titled “Tabs with more to say, and many at once”ui.addWorkbenchTab(tab) takes an object implementing WorkbenchTab instead of a draw function, for a tab that says more about itself, or a kind of tab with several open at once, like Wraith’s memory views. Its methods run on the Workbench’s thread:
describe()is asked once: itstitle,kind,place,orderandparentas above,multifor many at once, andpartsto hold the tabs that name it as theirparent.draw(id)draws one.idis empty unless it’smulti.status(id)gives its label and a dot for something not saved, each frame it shows.create()is View → New’s, formulti: a new one’s id, or empty for none.keepOpen(id)is its close button’s: true keeps it open, like to ask about saving first.
Only describe and draw are needed. Without the rest it keeps its label, has no New, and closes when asked. It gives back a Contribution, whose open(id) opens one of a multi tab, or brings it to the front, and close(id) closes one without asking. A multi tab’s ids are yours, like a file’s path or an address, and each one’s place is remembered by its kind and id.
import { Wraith } from "wraith";
let made = 0;const notes = Wraith.ui().addWorkbenchTab({ describe() { return { title: "Notes", kind: "notes", place: "bottom", order: 0, multi: true }; }, draw(id) { /* ImGui calls */ }, status(id) { return { title: `Note ${id}`, unsaved: false }; }, create() { return String(++made); }, keepOpen(id) { return false; },});notes.open("1");local Wraith = require("wraith").Wraithlocal made = 0local Notes = {}function Notes:describe() return { title = "Notes", kind = "notes", place = "bottom", order = 0, multi = true } endfunction Notes:draw(id) --[[ ImGui calls ]] endfunction Notes:status(id) return { title = "Note " .. id, unsaved = false } endfunction Notes:create() made = made + 1 return tostring(made) endfunction Notes:keepOpen(id) return false endlocal notes = Wraith.ui():addWorkbenchTab(Notes)notes:open("1")Implement IWorkbenchTab, whose methods all have defaults:
sealed class Notes : IWorkbenchTab{ uint made; public WorkbenchTab.Info Describe() => new() { Title = "Notes", Kind = "notes", Place = WorkbenchPanel.Place.Bottom, Multi = true }; public void Draw(string id) { /* ImGui calls */ } public WorkbenchTab.State Status(string id) => new() { Title = $"Note {id}" }; public string Create() => (++made).ToString(); public bool KeepOpen(string id) => false;}
// Kept in a field, since Wraith holds it till the plugin goesvar notes = Ui.Instance.AddWorkbenchTab(WorkbenchTab.From(this.notes));notes?.Open("1");Any type with the methods it has, which has to outlive it:
struct Notes { uint32_t made = 0; char id[12] = {}; Wraith::WorkbenchTab::Info describe() const { return {.title = sal::String::of("Notes"), .kind = sal::String::of("notes"), .place = Wraith::WorkbenchPanel_Place::bottom, .multi = true}; } void draw(std::string_view id) { /* ImGui calls */ } std::string_view create() { auto n = std::to_chars(id, id + sizeof(id), ++made).ptr - id; return std::string_view(id, n); }};
static Notes notes;auto tab = wraith::api().ui().addWorkbenchTab(Wraith::WorkbenchTab::of(notes));if (tab.ok()) tab.value().open("1");Implement WorkbenchTabImpl, whose methods all have defaults:
struct Notes { made: AtomicU32,}
impl wraith::WorkbenchTabImpl for Notes { fn describe(&self) -> wraith::WorkbenchTabInfo { wraith::WorkbenchTabInfo { title: Str::new("Notes"), kind: Str::new("notes"), place: wraith::WorkbenchPanelPlace::BOTTOM, multi: true, ..unsafe { std::mem::zeroed() } } } fn draw(&self, id: &str) { /* ImGui calls */ }}
static NOTES: Notes = Notes { made: AtomicU32::new(0) };let notes = wraith::api().ui().add_workbench_tab(wraith::WorkbenchTab::from_static(&NOTES)).ok()?;notes.open("1");sdk.workbench.addTab takes a type’s functions, and fills in what it doesn’t have:
const Notes = struct { made: u32 = 0, id: [12]u8 = undefined,
pub fn describe(_: *Notes) W.WorkbenchTab.Info { return .{ .title = "Notes", .kind = "notes", .place = .bottom, .multi = true }; } pub fn draw(_: *Notes, id: []const u8) void { _ = id; // sdk.ui calls } pub fn create(self: *Notes) []const u8 { self.made += 1; return std.fmt.bufPrint(&self.id, "{d}", .{self.made}) catch ""; }};
const tab = try sdk.workbench.addTab(&self.notes, Notes);tab.open("1");A table with the methods it has. The rest stay null:
static Wraith_WorkbenchTab_Info describe(uintptr_t self) { Wraith_WorkbenchTab_Info info = { .title = SAL_STR_INIT("Notes"), .kind = SAL_STR_INIT("notes"), .place = Wraith_WorkbenchPanel_Place_bottom, .multi = true }; return info;}static void draw(uintptr_t self, sal_string id) { /* ImGui calls */ }
static const Wraith_WorkbenchTab_table notes_table = { SAL_TABLE(Wraith_WorkbenchTab), .describe = describe, .draw = draw };
Wraith_Contribution notes;Wraith_WorkbenchTab tab = { 0, ¬es_table };if (Wraith_Ui_addWorkbenchTab(Wraith_Api_ui(w), tab, ¬es) == SAL_OK) Wraith_Contribution_open(notes, SAL_STR("1"));Never touch the game from a panel
Section titled “Never touch the game from a panel”The game doesn’t know about the Workbench’s thread. Calling into it from there, like an engine’s functions or a C# method, can crash it, and reading something the game’s changing can give you half of one value and half of another.
So split it in two:
- Your game-thread code, like an
onTick, reads what the panel shows and keeps it. - The panel draws what was kept, and queues anything it wants changed.
- The game-thread code makes the changes on its next tick.
In scripts
Section titled “In scripts”A JavaScript or Lua plugin only runs one thing at a time, so its panel and its onTick never run together. Keep what the panel shows in plain variables, like party above, and let the panel change variables your onTick acts on.
The Workbench waits its turn for your script, so a long onTick makes the panel slow, never the game.
In Zig
Section titled “In Zig”Your plugin’s code really does run on several threads at once, so sdk.workbench has two helpers that make it safe without ever holding up the game.
Latest(T) hands the newest value from one thread to another. The game-thread side builds each value in next()’s allocator, which can hold slices, then publishes it. Publishing never waits: if the panel’s reading the last one right then, it gives false, and you try again next tick. The panel reads the newest and ends when it’s done.
Queue(A) goes the other way. The panel pushes, and the game-thread side drains, which never waits either.
party: sdk.workbench.Latest(Party) = .{},edits: sdk.workbench.Queue(Edit) = .{},pending: ?Party = null,
fn tick(self: *Plugin) void { for (self.edits.drain()) |edit| apply(edit); if (!self.panel.isOpen()) return; if (self.pending) |p| { if (self.party.publish(p)) self.pending = null; return; } const p = readParty(self.party.next()) catch return; if (!self.party.publish(p)) self.pending = p;}
fn drawPanel(self: *Plugin) void { const party = self.party.read() orelse return; defer party.end(); for (party.value.members) |m| if (sdk.ui.button(m.name)) self.edits.push(.{ .heal = m.id });}The Unity plugin’s Scene panel works exactly like this, if you want a bigger example.
C# runs on several threads at once too, but there’s no Latest or Queue. Plain .NET does the same job. Build a new value on the game thread and swap it into a volatile field, and never change one after the panel could see it. Edits go the other way through a ConcurrentQueue, which never waits either.
volatile Party? party;readonly ConcurrentQueue<Edit> edits = new();
void Tick(){ while (edits.TryDequeue(out var edit)) Apply(edit); if (panel.IsOpen()) party = ReadParty();}
void DrawPanel(){ if (party is not { } p) return; foreach (var m in p.Members) if (imgui.Button(m.Name)) edits.Enqueue(new Edit(Heal: m.Id));}In C++, Rust and C
Section titled “In C++, Rust and C”Swap in a new value whole, under a lock that’s only held for the swap. The game thread builds the next one before taking the lock, and the panel takes its copy and lets go before drawing, so neither waits on the other for more than a moment. Never change a value after the panel could see it. Edits go the other way through a list of your own, under the same lock, which the game thread takes and empties each tick.
A std::shared_ptr to a const value is the swap. The panel keeps the one it took alive while it draws, even if a newer one comes in.
#include <memory>#include <mutex>#include <string>#include <vector>
struct Member { uint32_t id; std::string name;};using Party = std::vector<Member>;struct Edit { uint32_t heal;};
static std::mutex lock;static std::shared_ptr<const Party> party;static std::vector<Edit> edits;static Wraith::WorkbenchPanel panel;
Party read_party();void apply(Edit edit);
// On the game thread, each tickstatic void tick() { std::vector<Edit> todo; { std::lock_guard held(lock); todo.swap(edits); } for (auto edit : todo) apply(edit); if (!panel.isOpen()) return; auto next = std::make_shared<const Party>(read_party()); std::lock_guard held(lock); party = next;}
// On the Workbench's threadstatic void draw_panel() { std::shared_ptr<const Party> shown; { std::lock_guard held(lock); shown = party; } if (!shown) return; for (const auto& m : *shown) { if (!wraith::api().imgui().Button(m.name.c_str())) continue; std::lock_guard held(lock); edits.push_back({.heal = m.id}); }}An Arc is the swap. The panel’s clone keeps the one it took alive while it draws, even if a newer one comes in.
use std::sync::{Arc, Mutex};
use wraith::WorkbenchPanel;
struct Member { id: u32, name: String,}
struct Edit { heal: u32,}
static PARTY: Mutex<Option<Arc<Vec<Member>>>> = Mutex::new(None);static EDITS: Mutex<Vec<Edit>> = Mutex::new(Vec::new());
fn read_party() -> Vec<Member> { Vec::new() // read it from the game}
fn apply(edit: Edit) { // heal edit.heal, if they're still there}
// On the game thread, each tickfn tick(panel: WorkbenchPanel) { let todo = std::mem::take(&mut *EDITS.lock().unwrap()); for edit in todo { apply(edit); } if !panel.is_open() { return; } let next = Arc::new(read_party()); *PARTY.lock().unwrap() = Some(next);}
// On the Workbench's threadfn draw_panel() { let Some(party) = PARTY.lock().unwrap().clone() else { return }; let imgui = wraith::api().imgui(); for m in party.iter() { let label = format!("{}\0", m.name); if imgui.button(label.as_ptr().cast()) { EDITS.lock().unwrap().push(Edit { heal: m.id }); } }}With no shared pointers, keep the value small enough to copy, and copy it in and out under the lock. An SRW lock lets the panel read while nothing’s writing.
#include <windows.h>
typedef struct { uint32_t count; uint32_t ids[8]; char names[8][32];} Party;
static SRWLOCK lock = SRWLOCK_INIT;static Party party;static uint32_t heals[16];static uint32_t heal_count;static Wraith_WorkbenchPanel panel;
void read_party(Party *out);void heal(uint32_t id);
/* On the game thread, each tick */static void tick(uintptr_t self) { (void)self; uint32_t todo[16]; AcquireSRWLockExclusive(&lock); uint32_t n = heal_count; memcpy(todo, heals, n * sizeof todo[0]); heal_count = 0; ReleaseSRWLockExclusive(&lock); for (uint32_t i = 0; i < n; i++) heal(todo[i]);
if (!Wraith_WorkbenchPanel_isOpen(panel)) return; Party next; read_party(&next); AcquireSRWLockExclusive(&lock); party = next; ReleaseSRWLockExclusive(&lock);}
/* On the Workbench's thread */static void draw_panel(uintptr_t self) { (void)self; Party shown; AcquireSRWLockShared(&lock); shown = party; ReleaseSRWLockShared(&lock); for (uint32_t i = 0; i < shown.count; i++) { if (!Wraith_ImGui_Button(Wraith_Api_imgui(w), shown.names[i])) continue; AcquireSRWLockExclusive(&lock); if (heal_count < 16) heals[heal_count++] = shown.ids[i]; ReleaseSRWLockExclusive(&lock); }}Keep in mind
Section titled “Keep in mind”Whatever the language:
- Copy what you need into the value the panel gets. A pointer into the game can be stale by the time the panel draws.
- Check anything in an edit again before you use it, since the object it’s about may be gone by then.
- A panel’s
remove()waits for a draw under way, so it’s safe to free what the panel uses after it. Call it before tearing things down instop. Don’t hold a lock your draw needs while you call it, or the two will wait on each other.
wraith.io · Mods on the Hub · Get Wraith
Made with ♥ by Asgard
