Tables¶
Starcel's tables are spreadsheets of Python. A table can have 2, 3 or more dimensions, and every cell can hold a value, a formula or code.
Your first table¶
from ue_math.nd_table.ndtable import Table
from ue_spawn import spawn_table_actor
from unreal_engine import FVector
t = Table(shape=(3, 4)) # 3 rows, 4 columns
t['A1'] = 'Name'; t['B1'] = 'Size'; t['C1'] = 'Date'; t['D1'] = 'Type'
t['A2'] = 'file.py'; t['B2'] = '10 KB'; t['C2'] = '2024-01'; t['D2'] = '.py'
t[2, 0] = 'readme'; t[2, 1] = '1 KB'; t[2, 2] = '2024-01'; t[2, 3] = '.md'
spawn_table_actor(t, location=FVector(0, 0, 500))
Cells can be addressed by label ('A1') or by index (t[row, column], starting at 0).
Formulas¶
A string that starts with = is a formula. Formulas are Python, and cell labels in them are cell values.
t = Table(shape=(7, 5))
t['A1'], t['B1'], t['C1'], t['D1'] = 'Item', 'Qty', 'Price', 'Total'
items = [('Widget', 5, 12.50), ('Gadget', 3, 27.00), ('Bracket', 10, 4.75),
('Washer', 50, 0.30), ('Bolt', 20, 1.10)]
for i, (name, qty, price) in enumerate(items, start=2):
t[f'A{i}'] = name
t[f'B{i}'] = qty
t[f'C{i}'] = price
t[f'D{i}'] = f'=B{i} * C{i}'
t['A7'] = 'Sum'
t['D7'] = '=sum(D2:D6)'
t['E7'] = '=np.mean(D2:D6)'
t['D2'] # 62.5
- Ranges like
D2:D6are lists of the non-empty values, sosum,max,lenandnp.meanwork like SUM, MAX, COUNT and AVERAGE. mathandnpare available in formulas.- Changing a cell updates the formulas that use it.
- Name a cell:
t.name_cell('D7', 'grand_total'), then usegrand_totalin formulas. - Refer to another table:
=table2.A1.
Editing in the world¶
Click a cell to type in it, Ctrl+Enter to run it. Drag a gridline to resize its row, column or layer. The cell's result is in cell_actor.cell_data.
Options of spawn_table_actor:
| Option | Default | Does |
|---|---|---|
orientation |
'wall_table' |
'wall_table' stands up, 'ground_table' lies flat |
cell_spacing |
100.0 |
Space between cells, in UU (cm) |
render_gridlines |
True |
Draw the grid |
render_text |
True |
Draw the cell text |
enable_resize |
True |
Drag gridlines to resize |
auto_size |
True |
Refit rows and columns after you edit |
editable |
True |
Click cells to type |
spawn_table(t, ...) does the same without a PyActor and returns the renderer.
3D tables¶
Give shape a third number for layers:
t = Table(shape=(3, 3, 3))
for i in range(3):
for j in range(3):
for k in range(3):
t[i, j, k] = f'r{i}c{j}l{k}'
spawn_table_actor(t, location=FVector(0, 0, 500))
Higher dimensions work too; spawn('nd_grid') shows tables from 2D to 7D.
Save and load¶
path = t.save('budget') # Saved/Tables/budget.zarr
t2 = Table.load('budget')
spawn_table_actor('budget') # spawn straight from the file
Entity(model='budget.zarr') and spawn('C:/path/budget.zarr') work too.
NumPy¶
Undo¶
In the tests¶
Copied from the code when this site is built. test_table is the example above with more formulas; the others spawn 3D and higher-dimensional tables.
From the tests: test_table (Content/Scripts/test_spawn.py:737)
def test_table(base_y=0):
"""Spawn two nd_tables: a basic 3×4 file listing and an advanced formula
spreadsheet that exercises in-cell Python, spreadsheet labels (A–C, AA, AB),
named cells, and cross-cell dependencies."""
from ue_spawn import spawn_table
results = {}
# Basic table (unchanged)
renderer = None
t0 = time.monotonic()
try:
from ue_math.nd_table.ndtable import Table
t = Table(shape=(3, 4))
t[(0, 0)] = 'Name'; t[(0, 1)] = 'Size'; t[(0, 2)] = 'Date'; t[(0, 3)] = 'Type'
t[(1, 0)] = 'file.py'; t[(1, 1)] = '10 KB'; t[(1, 2)] = '2024-01'; t[(1, 3)] = '.py'
t[(2, 0)] = 'readme'; t[(2, 1)] = '1 KB'; t[(2, 2)] = '2024-01'; t[(2, 3)] = '.md'
renderer = spawn_table(t, location=FVector(0, base_y, 500))
except Exception as e:
_log_exception('table', e)
n_cells = len(renderer.cell_actors) if renderer and hasattr(renderer, 'cell_actors') else 0
results.update(_result('table', renderer, extra=f'{n_cells} cells',
elapsed=time.monotonic() - t0))
# Advanced formula spreadsheet
# Uses spreadsheet labels A–C and extended AA, AB.
# Row 0: headers
# Rows 1-5: numeric data + formulas referencing other cells
adv_renderer = None
t0 = time.monotonic()
try:
from ue_math.nd_table.ndtable import Table
adv = Table(shape=(8, 28), lazy_eval=True) # 8 rows, 28 cols (A..AB)
# Headers in row 0
adv['A1'] = 'Item'
adv['B1'] = 'Qty'
adv['C1'] = 'Price'
# Column D = total per row (Qty * Price)
adv[(0, 3)] = 'Total'
# Column E = running sum
adv[(0, 4)] = 'RunSum'
# Extended label columns
adv[(0, 26)] = 'AA:Sum' # col 26 = AA
adv[(0, 27)] = 'AB:Avg' # col 27 = AB
# Data rows (A=0, B=1, C=2)
items = [
('Widget', 5, 12.50),
('Gadget', 3, 27.00),
('Bracket', 10, 4.75),
('Washer', 50, 0.30),
('Bolt', 20, 1.10),
]
for i, (name, qty, price) in enumerate(items, start=2):
row = i - 1 # row index (0-based)
adv[(row, 0)] = name
adv[(row, 1)] = qty
adv[(row, 2)] = price
# D = Qty * Price (formula using spreadsheet labels)
adv[(row, 3)] = f'=B{i} * C{i}'
# Running sum in column E (cumulative formula chain)
adv[(1, 4)] = '=D2'
for i in range(3, 7):
adv[(i - 1, 4)] = f'=E{i - 1} + D{i}'
# Named cell for grand total
try:
adv.name_cell('E6', 'grand_total')
except Exception:
pass
# AA column (col 26): sum of all totals via formula
adv[(1, 26)] = '=D2 + D3 + D4 + D5 + D6'
# AB column (col 27): average using Python math in formula
adv[(1, 27)] = '=(D2 + D3 + D4 + D5 + D6) / 5'
# Row 7: summary using math functions (use builtins explicitly)
adv[(6, 0)] = 'sqrt(sum)'
adv[(6, 3)] = '=math.sqrt(D2 + D3 + D4 + D5 + D6)'
adv[(6, 4)] = '=max(D2, D3, D4, D5, D6)'
# Force evaluation to verify formulas work
formula_ok = True
try:
val_d2 = adv['D2'] # should be 5 * 12.50 = 62.50
val_aa = adv[(1, 26)] # sum
val_ab = adv[(1, 27)] # average
_log(f' adv_table formulas: D2={val_d2}, AA2={val_aa}, AB2={val_ab}')
except Exception as e:
_log(f' adv_table formula eval failed: {e}')
formula_ok = False
adv_renderer = spawn_table(
adv, location=FVector(500, base_y + 400, 500))
if formula_ok:
_log(f' adv_table: formulas evaluated successfully')
except Exception as e:
_log_exception('adv_table', e)
n_adv = len(adv_renderer.cell_actors) if adv_renderer and hasattr(adv_renderer, 'cell_actors') else 0
results.update(_result('table_formulas', adv_renderer,
extra=f'{n_adv} cells, labels A-C + AA + AB',
elapsed=time.monotonic() - t0))
return results
From the tests: test_3d_table_resize (Content/Scripts/test_spawn.py:1117)
def test_3d_table_resize(base_y=0):
"""Spawn a 3x3x3 resizable table for trying out row/col/layer drag-resize.
Hover a gridline, then LMB-drag to resize the adjacent row (axis 0),
column (axis 1), or layer (axis 2). The cursor changes to
ResizeUpDown / ResizeLeftRight / CardinalCross to indicate the axis.
"""
from ue_spawn import spawn_table_actor
actor = None
t0 = time.monotonic()
try:
from ue_math.nd_table.ndtable import Table
t = Table(shape=(3, 3, 3))
for i in range(3):
for j in range(3):
for k in range(3):
t[i, j, k] = f'r{i}c{j}l{k}'
actor = spawn_table_actor(
t,
location=FVector(0, base_y, 500),
enable_resize=True,
)
except Exception as e:
_log_exception('3d_table_resize', e)
extra = 'drag gridlines: row/col/layer resize'
try:
if actor is not None:
proxy = actor.get_py_proxy()
if proxy is not None and proxy.renderer is not None:
n_cells = len(proxy.renderer.cell_actors)
n_lines = proxy.renderer.gridline_count
extra = f'{n_cells} cells, {n_lines} gridlines (drag to resize row/col/layer)'
except Exception:
pass
return _result('3d_table_resize', actor, extra=extra, elapsed=time.monotonic() - t0)
From the tests: test_3d_table_5x5x5 (Content/Scripts/test_spawn.py:1154)
def test_3d_table_5x5x5(base_y=0):
"""Spawn a 5x5x5 resizable table with every row/col/layer forced to
400 UU so the grid is a true cube (restored from the old
test_text3d_click prototype). LMB-drag gridlines to resize.
"""
from ue_spawn import spawn_table_actor
CELL_SIZE = 400.0
GRID_N = 5
actor = None
t0 = time.monotonic()
try:
from ue_math.nd_table.ndtable import Table
t = Table(shape=(GRID_N, GRID_N, GRID_N))
for i in range(GRID_N):
for j in range(GRID_N):
for k in range(GRID_N):
t[(i, j, k)] = f'r{i}c{j}l{k}'
t[(0, 0, 0)] = 'Col A'; t[(0, 1, 0)] = 'Col B'; t[(0, 2, 0)] = 'Col C'
t[(1, 0, 0)] = 'Hello'; t[(1, 1, 0)] = 'World'; t[(1, 2, 0)] = '123'
t[(2, 0, 0)] = 'Click'; t[(2, 1, 0)] = 'Me'; t[(2, 2, 0)] = '!'
actor = spawn_table_actor(
t,
location=FVector(0, base_y, 500),
enable_resize=True,
)
except Exception as e:
_log_exception('3d_table_5x5x5', e)
extra = f'{GRID_N}x{GRID_N}x{GRID_N} @ {CELL_SIZE:.0f} UU'
try:
if actor is not None:
proxy = actor.get_py_proxy()
if proxy is not None and proxy.renderer is not None:
for axis in (0, 1, 2):
for idx in range(GRID_N):
proxy.renderer.set_user_size(axis, idx, CELL_SIZE)
proxy.renderer.recompute_layout()
extra = (f'{len(proxy.renderer.cell_actors)} cells, '
f'{GRID_N}x{GRID_N}x{GRID_N} @ {CELL_SIZE:.0f} UU')
except Exception as e:
_log_exception('3d_table_5x5x5 sizing', e)
return _result('3d_table_5x5x5', actor, extra=extra, elapsed=time.monotonic() - t0)
From the tests: test_nd_table (Content/Scripts/test_spawn.py:1022)
def test_nd_table(base_y=0):
"""Spawn the comprehensive nD table grid (2D through 6D, including
negative indices, tabs/newlines and callable cells)."""
from ue_spawn import spawn_nd_table
renderers = []
t0 = time.monotonic()
try:
renderers = spawn_nd_table(location=FVector(0, base_y, 700),
cube_cells=True)
except Exception as e:
_log_exception('nd_table', e)
ok = bool(renderers) and all(r.cell_actors and r.gridline_actors
for r in renderers)
overlaps = 0
boxes = [r.get_bounds() for r in renderers] if ok else []
for i, (lo, hi) in enumerate(boxes):
for lo2, hi2 in boxes[:i]:
overlaps += (lo.x < hi2.x and lo2.x < hi.x and
lo.y < hi2.y and lo2.y < hi.y and
lo.z < hi2.z and lo2.z < hi.z)
n_cells = sum(len(r.cell_actors) for r in renderers)
n_lines = sum(r.gridline_count for r in renderers)
errors = [] # cells showing #ERROR
for r in renderers:
for idx in r._last_table.cells:
try:
r._last_table[idx]
except Exception as e:
errors.append(f'{r._last_table.ndim}D cell {idx}: {e}')
return _result('nd_table', renderers if ok and not overlaps and not errors else None,
extra='; '.join(errors + [
f'{len(renderers)} tables, {n_cells} cells, '
f'{n_lines} gridlines, {overlaps} overlaps']),
elapsed=time.monotonic() - t0)
From the tests: test_nd_table_text (Content/Scripts/test_spawn.py:1058)
def test_nd_table_text(base_y=0):
"""Spawn nd_table's text sizing example: tabs, newlines, long text."""
renderers = []
t0 = time.monotonic()
try:
from ue_math.nd_table import example_text_sizing_test
renderers = example_text_sizing_test(FVector(0, base_y + 200, 900))
except Exception as e:
_log_exception('nd_table_text', e)
ok = bool(renderers) and all(r.cell_actors for r in renderers)
n_cells = sum(len(r.cell_actors) for r in renderers)
return _result('nd_table_text', renderers if ok else None,
extra=f'{len(renderers)} tables, {n_cells} cells',
elapsed=time.monotonic() - t0)
From the tests: test_nd_table_spread (Content/Scripts/test_spawn.py:1074)
def test_nd_table_spread(base_y=0):
"""Spawn the spread_engine examples side by side along Y.
Each copy of the table is drawn as its one filled cell. A spread's x, y are
drawn along +Y, +Z and scaled until no two copies overlap.
"""
from ue_spawn import spawn_table
from ue_math.nd_table.spread_engine import spread_examples
results = {}
left = base_y + 300
for name, copies in spread_examples():
renderers, problems = [], []
t0 = time.monotonic()
pts = [(float(p[0]), float(p[1])) for _, p in copies]
nearest = min(math.hypot(a[0] - b[0], a[1] - b[1])
for i, a in enumerate(pts) for b in pts[:i])
scale = 160.0 / nearest # a (cube) cell is about 114 UU
min_x, min_y = (min(p[k] for p in pts) for k in (0, 1))
for (table, _), (x, y) in zip(copies, pts):
try:
r = spawn_table(table, render_gridlines=False, cube_cells=True,
location=FVector(0, left + (x - min_x) * scale,
300 + (y - min_y) * scale))
if not r.cell_actors:
problems.append('a copy spawned no cells')
renderers.append(r)
except Exception as e:
_log_exception(f'nd_spread_{name}', e)
problems.append(repr(e))
left += (max(p[0] for p in pts) - min_x) * scale + 400
results.update(_result(
f'nd_spread_{name}', None if problems else renderers,
extra='; '.join(problems) or f'{len(renderers)} copies',
elapsed=time.monotonic() - t0))
return results
The offline tests show saving and loading (they run without Unreal):
From the tests: TestFormulasAndCode.test_formulas_come_back_and_recalculate (Content/Scripts/ue_math/nd_table/test_zarr.py:113)
def test_formulas_come_back_and_recalculate(self):
t = Table(shape=(3, 3))
t[(0, 0)] = 5
t[(0, 1)] = '=A1*2'
self.assertEqual(t[(0, 1)], 10)
t2 = self.round_trip(t)
self.assertEqual(t2.cells[(0, 1)].formula, 'A1*2')
self.assertEqual(t2.get_code((0, 1)), '=A1*2')
self.assertEqual(t2[(0, 1)], 10)
t2[(0, 0)] = 7
self.assertEqual(t2[(0, 1)], 14)
From the tests: TestFormulasAndCode.test_named_cells (Content/Scripts/ue_math/nd_table/test_zarr.py:135)
def test_named_cells(self):
t = Table(shape=(2, 2))
t[(0, 0)] = 5
t.name_cell((0, 0), 'price')
t[(1, 1)] = '=price+1'
t2 = self.round_trip(t)
self.assertEqual(t2.named_cells, {'price': (0, 0)})
self.assertEqual(t2.cells[(0, 0)].name, 'price')
self.assertEqual(t2['price'], 5)
self.assertEqual(t2[(1, 1)], 6)