forked from genewildish/Mainline
feat: Complete pipeline hot-rebuild implementation with acceptance tests
- Implements pipeline hot-rebuild with state preservation (issue #43) - Adds auto-injection of MVP stages for missing capabilities - Adds radial camera mode for polar coordinate scanning - Adds afterimage and motionblur effects using framebuffer history - Adds comprehensive acceptance tests for camera modes and pipeline rebuild - Updates presets.toml with new effect configurations Related to: #35 (Pipeline Mutation API epic) Closes: #43, #44, #45
This commit is contained in:
@@ -101,6 +101,8 @@ def run_pipeline_mode_direct():
|
||||
border_mode = BorderMode.OFF
|
||||
source_items = None
|
||||
allow_unsafe = False
|
||||
viewport_width = None
|
||||
viewport_height = None
|
||||
|
||||
i = 1
|
||||
argv = sys.argv
|
||||
@@ -115,6 +117,14 @@ def run_pipeline_mode_direct():
|
||||
elif arg == "--pipeline-camera" and i + 1 < len(argv):
|
||||
camera_type = argv[i + 1]
|
||||
i += 2
|
||||
elif arg == "--viewport" and i + 1 < len(argv):
|
||||
vp = argv[i + 1]
|
||||
try:
|
||||
viewport_width, viewport_height = map(int, vp.split("x"))
|
||||
except ValueError:
|
||||
print("Error: Invalid viewport format. Use WxH (e.g., 40x15)")
|
||||
sys.exit(1)
|
||||
i += 2
|
||||
elif arg == "--pipeline-display" and i + 1 < len(argv):
|
||||
display_name = argv[i + 1]
|
||||
i += 2
|
||||
@@ -221,8 +231,8 @@ def run_pipeline_mode_direct():
|
||||
|
||||
# Build pipeline using validated config and params
|
||||
params = result.params
|
||||
params.viewport_width = 80
|
||||
params.viewport_height = 24
|
||||
params.viewport_width = viewport_width if viewport_width is not None else 80
|
||||
params.viewport_height = viewport_height if viewport_height is not None else 24
|
||||
|
||||
ctx = PipelineContext()
|
||||
ctx.params = params
|
||||
@@ -356,6 +366,12 @@ def run_pipeline_mode_direct():
|
||||
current_width = params.viewport_width
|
||||
current_height = params.viewport_height
|
||||
|
||||
# Only get dimensions from display if viewport wasn't explicitly set
|
||||
if "--viewport" not in sys.argv and hasattr(display, "get_dimensions"):
|
||||
current_width, current_height = display.get_dimensions()
|
||||
params.viewport_width = current_width
|
||||
params.viewport_height = current_height
|
||||
|
||||
print(" \033[38;5;82mStarting pipeline...\033[0m")
|
||||
print(" \033[38;5;245mPress Ctrl+C to exit\033[0m\n")
|
||||
|
||||
|
||||
@@ -45,8 +45,19 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
print(f" \033[38;5;245mPreset: {preset.name} - {preset.description}\033[0m")
|
||||
|
||||
params = preset.to_params()
|
||||
params.viewport_width = 80
|
||||
params.viewport_height = 24
|
||||
# Use preset viewport if available, else default to 80x24
|
||||
params.viewport_width = getattr(preset, "viewport_width", 80)
|
||||
params.viewport_height = getattr(preset, "viewport_height", 24)
|
||||
|
||||
if "--viewport" in sys.argv:
|
||||
idx = sys.argv.index("--viewport")
|
||||
if idx + 1 < len(sys.argv):
|
||||
vp = sys.argv[idx + 1]
|
||||
try:
|
||||
params.viewport_width, params.viewport_height = map(int, vp.split("x"))
|
||||
except ValueError:
|
||||
print("Error: Invalid viewport format. Use WxH (e.g., 40x15)")
|
||||
sys.exit(1)
|
||||
|
||||
pipeline = Pipeline(
|
||||
config=PipelineConfig(
|
||||
@@ -156,25 +167,12 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
list_source = ListDataSource(items, name=preset.source)
|
||||
pipeline.add_stage("source", DataSourceStage(list_source, name=preset.source))
|
||||
|
||||
# Add FontStage for headlines/poetry (default for demo)
|
||||
if preset.source in ["headlines", "poetry"]:
|
||||
from engine.pipeline.adapters import FontStage, ViewportFilterStage
|
||||
|
||||
# Add viewport filter to prevent rendering all items
|
||||
pipeline.add_stage(
|
||||
"viewport_filter", ViewportFilterStage(name="viewport-filter")
|
||||
)
|
||||
pipeline.add_stage("font", FontStage(name="font"))
|
||||
else:
|
||||
# Fallback to simple conversion for other sources
|
||||
pipeline.add_stage("render", SourceItemsToBufferStage(name="items-to-buffer"))
|
||||
|
||||
# Add camera stage if specified in preset (after font/render stage)
|
||||
# Add camera state update stage if specified in preset (must run before viewport filter)
|
||||
camera = None
|
||||
if preset.camera:
|
||||
from engine.camera import Camera
|
||||
from engine.pipeline.adapters import CameraStage
|
||||
from engine.pipeline.adapters import CameraClockStage, CameraStage
|
||||
|
||||
camera = None
|
||||
speed = getattr(preset, "camera_speed", 1.0)
|
||||
if preset.camera == "feed":
|
||||
camera = Camera.feed(speed=speed)
|
||||
@@ -190,9 +188,35 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
camera = Camera.floating(speed=speed)
|
||||
elif preset.camera == "bounce":
|
||||
camera = Camera.bounce(speed=speed)
|
||||
elif preset.camera == "radial":
|
||||
camera = Camera.radial(speed=speed)
|
||||
elif preset.camera == "static" or preset.camera == "":
|
||||
# Static camera: no movement, but provides camera_y=0 for viewport filter
|
||||
camera = Camera.scroll(speed=0.0) # Speed 0 = no movement
|
||||
camera.set_canvas_size(200, 200)
|
||||
|
||||
if camera:
|
||||
pipeline.add_stage("camera", CameraStage(camera, name=preset.camera))
|
||||
# Add camera update stage to ensure camera_y is available for viewport filter
|
||||
pipeline.add_stage(
|
||||
"camera_update", CameraClockStage(camera, name="camera-clock")
|
||||
)
|
||||
|
||||
# Add FontStage for headlines/poetry (default for demo)
|
||||
if preset.source in ["headlines", "poetry"]:
|
||||
from engine.pipeline.adapters import FontStage, ViewportFilterStage
|
||||
|
||||
# Add viewport filter to prevent rendering all items
|
||||
pipeline.add_stage(
|
||||
"viewport_filter", ViewportFilterStage(name="viewport-filter")
|
||||
)
|
||||
pipeline.add_stage("font", FontStage(name="font"))
|
||||
else:
|
||||
# Fallback to simple conversion for other sources
|
||||
pipeline.add_stage("render", SourceItemsToBufferStage(name="items-to-buffer"))
|
||||
|
||||
# Add camera stage if specified in preset (after font/render stage)
|
||||
if camera:
|
||||
pipeline.add_stage("camera", CameraStage(camera, name=preset.camera))
|
||||
|
||||
for effect_name in preset.effects:
|
||||
effect = effect_registry.get(effect_name)
|
||||
@@ -451,7 +475,7 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
# Add camera if specified
|
||||
if new_preset.camera:
|
||||
from engine.camera import Camera
|
||||
from engine.pipeline.adapters import CameraStage
|
||||
from engine.pipeline.adapters import CameraClockStage, CameraStage
|
||||
|
||||
speed = getattr(new_preset, "camera_speed", 1.0)
|
||||
camera = None
|
||||
@@ -468,8 +492,19 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
camera = Camera.floating(speed=speed)
|
||||
elif cam_type == "bounce":
|
||||
camera = Camera.bounce(speed=speed)
|
||||
elif cam_type == "radial":
|
||||
camera = Camera.radial(speed=speed)
|
||||
elif cam_type == "static" or cam_type == "":
|
||||
# Static camera: no movement, but provides camera_y=0 for viewport filter
|
||||
camera = Camera.scroll(speed=0.0)
|
||||
camera.set_canvas_size(200, 200)
|
||||
|
||||
if camera:
|
||||
# Add camera update stage to ensure camera_y is available for viewport filter
|
||||
pipeline.add_stage(
|
||||
"camera_update",
|
||||
CameraClockStage(camera, name="camera-clock"),
|
||||
)
|
||||
pipeline.add_stage("camera", CameraStage(camera, name=cam_type))
|
||||
|
||||
# Add effects
|
||||
@@ -637,10 +672,11 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
ctx.set("pipeline_order", pipeline.execution_order)
|
||||
ctx.set("camera_y", 0)
|
||||
|
||||
current_width = 80
|
||||
current_height = 24
|
||||
current_width = params.viewport_width
|
||||
current_height = params.viewport_height
|
||||
|
||||
if hasattr(display, "get_dimensions"):
|
||||
# Only get dimensions from display if viewport wasn't explicitly set
|
||||
if "--viewport" not in sys.argv and hasattr(display, "get_dimensions"):
|
||||
current_width, current_height = display.get_dimensions()
|
||||
params.viewport_width = current_width
|
||||
params.viewport_height = current_height
|
||||
@@ -687,7 +723,7 @@ def run_pipeline_mode(preset_name: str = "demo"):
|
||||
display.clear_quit_request()
|
||||
raise KeyboardInterrupt()
|
||||
|
||||
if hasattr(display, "get_dimensions"):
|
||||
if "--viewport" not in sys.argv and hasattr(display, "get_dimensions"):
|
||||
new_w, new_h = display.get_dimensions()
|
||||
if new_w != current_width or new_h != current_height:
|
||||
current_width, current_height = new_w, new_h
|
||||
|
||||
60
engine/data_sources/checkerboard.py
Normal file
60
engine/data_sources/checkerboard.py
Normal file
@@ -0,0 +1,60 @@
|
||||
"""Checkerboard data source for visual pattern generation."""
|
||||
|
||||
from engine.data_sources.sources import DataSource, SourceItem
|
||||
|
||||
|
||||
class CheckerboardDataSource(DataSource):
|
||||
"""Data source that generates a checkerboard pattern.
|
||||
|
||||
Creates a grid of alternating characters, useful for testing motion effects
|
||||
and camera movement. The pattern is static; movement comes from camera panning.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
width: int = 200,
|
||||
height: int = 200,
|
||||
square_size: int = 10,
|
||||
char_a: str = "#",
|
||||
char_b: str = " ",
|
||||
):
|
||||
"""Initialize checkerboard data source.
|
||||
|
||||
Args:
|
||||
width: Total pattern width in characters
|
||||
height: Total pattern height in lines
|
||||
square_size: Size of each checker square in characters
|
||||
char_a: Character for "filled" squares (default: '#')
|
||||
char_b: Character for "empty" squares (default: ' ')
|
||||
"""
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.square_size = square_size
|
||||
self.char_a = char_a
|
||||
self.char_b = char_b
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "checkerboard"
|
||||
|
||||
@property
|
||||
def is_dynamic(self) -> bool:
|
||||
return False
|
||||
|
||||
def fetch(self) -> list[SourceItem]:
|
||||
"""Generate the checkerboard pattern as a single SourceItem."""
|
||||
lines = []
|
||||
for y in range(self.height):
|
||||
line_chars = []
|
||||
for x in range(self.width):
|
||||
# Determine which square this position belongs to
|
||||
square_x = x // self.square_size
|
||||
square_y = y // self.square_size
|
||||
# Alternate pattern based on parity of square coordinates
|
||||
if (square_x + square_y) % 2 == 0:
|
||||
line_chars.append(self.char_a)
|
||||
else:
|
||||
line_chars.append(self.char_b)
|
||||
lines.append("".join(line_chars))
|
||||
content = "\n".join(lines)
|
||||
return [SourceItem(content=content, source="checkerboard", timestamp="0")]
|
||||
@@ -20,6 +20,7 @@ except ImportError:
|
||||
from engine.display.backends.multi import MultiDisplay
|
||||
from engine.display.backends.null import NullDisplay
|
||||
from engine.display.backends.pygame import PygameDisplay
|
||||
from engine.display.backends.replay import ReplayDisplay
|
||||
from engine.display.backends.terminal import TerminalDisplay
|
||||
from engine.display.backends.websocket import WebSocketDisplay
|
||||
|
||||
@@ -90,6 +91,7 @@ class DisplayRegistry:
|
||||
return
|
||||
cls.register("terminal", TerminalDisplay)
|
||||
cls.register("null", NullDisplay)
|
||||
cls.register("replay", ReplayDisplay)
|
||||
cls.register("websocket", WebSocketDisplay)
|
||||
cls.register("pygame", PygameDisplay)
|
||||
if _MODERNGL_AVAILABLE:
|
||||
@@ -278,6 +280,7 @@ __all__ = [
|
||||
"BorderMode",
|
||||
"TerminalDisplay",
|
||||
"NullDisplay",
|
||||
"ReplayDisplay",
|
||||
"WebSocketDisplay",
|
||||
"MultiDisplay",
|
||||
"PygameDisplay",
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
Null/headless display backend.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
class NullDisplay:
|
||||
@@ -10,7 +13,8 @@ class NullDisplay:
|
||||
|
||||
This display does nothing - useful for headless benchmarking
|
||||
or when no display output is needed. Captures last buffer
|
||||
for testing purposes.
|
||||
for testing purposes. Supports frame recording for replay
|
||||
and file export/import.
|
||||
"""
|
||||
|
||||
width: int = 80
|
||||
@@ -19,6 +23,9 @@ class NullDisplay:
|
||||
|
||||
def __init__(self):
|
||||
self._last_buffer = None
|
||||
self._is_recording = False
|
||||
self._recorded_frames: list[dict[str, Any]] = []
|
||||
self._frame_count = 0
|
||||
|
||||
def init(self, width: int, height: int, reuse: bool = False) -> None:
|
||||
"""Initialize display with dimensions.
|
||||
@@ -37,7 +44,6 @@ class NullDisplay:
|
||||
|
||||
from engine.display import get_monitor, render_border
|
||||
|
||||
# Get FPS for border (if available)
|
||||
fps = 0.0
|
||||
frame_time = 0.0
|
||||
monitor = get_monitor()
|
||||
@@ -49,26 +55,28 @@ class NullDisplay:
|
||||
fps = 1000.0 / avg_ms
|
||||
frame_time = avg_ms
|
||||
|
||||
# Apply border if requested (same as terminal display)
|
||||
if border:
|
||||
buffer = render_border(buffer, self.width, self.height, fps, frame_time)
|
||||
|
||||
self._last_buffer = buffer
|
||||
|
||||
# For debugging: print first few frames to stdout
|
||||
if hasattr(self, "_frame_count"):
|
||||
self._frame_count += 1
|
||||
else:
|
||||
self._frame_count = 0
|
||||
if self._is_recording:
|
||||
self._recorded_frames.append(
|
||||
{
|
||||
"frame_number": self._frame_count,
|
||||
"buffer": buffer,
|
||||
"width": self.width,
|
||||
"height": self.height,
|
||||
}
|
||||
)
|
||||
|
||||
# Only print first 5 frames or every 10th frame
|
||||
if self._frame_count <= 5 or self._frame_count % 10 == 0:
|
||||
sys.stdout.write("\n" + "=" * 80 + "\n")
|
||||
sys.stdout.write(
|
||||
f"Frame {self._frame_count} (buffer height: {len(buffer)})\n"
|
||||
)
|
||||
sys.stdout.write("=" * 80 + "\n")
|
||||
for i, line in enumerate(buffer[:30]): # Show first 30 lines
|
||||
for i, line in enumerate(buffer[:30]):
|
||||
sys.stdout.write(f"{i:2}: {line}\n")
|
||||
if len(buffer) > 30:
|
||||
sys.stdout.write(f"... ({len(buffer) - 30} more lines)\n")
|
||||
@@ -80,6 +88,78 @@ class NullDisplay:
|
||||
elapsed_ms = (time.perf_counter() - t0) * 1000
|
||||
monitor.record_effect("null_display", elapsed_ms, chars_in, chars_in)
|
||||
|
||||
self._frame_count += 1
|
||||
|
||||
def start_recording(self) -> None:
|
||||
"""Begin recording frames."""
|
||||
self._is_recording = True
|
||||
self._recorded_frames = []
|
||||
|
||||
def stop_recording(self) -> None:
|
||||
"""Stop recording frames."""
|
||||
self._is_recording = False
|
||||
|
||||
def get_frames(self) -> list[list[str]]:
|
||||
"""Get recorded frames as list of buffers.
|
||||
|
||||
Returns:
|
||||
List of buffers, each buffer is a list of strings (lines)
|
||||
"""
|
||||
return [frame["buffer"] for frame in self._recorded_frames]
|
||||
|
||||
def get_recorded_data(self) -> list[dict[str, Any]]:
|
||||
"""Get full recorded data including metadata.
|
||||
|
||||
Returns:
|
||||
List of frame dicts with 'frame_number', 'buffer', 'width', 'height'
|
||||
"""
|
||||
return self._recorded_frames
|
||||
|
||||
def clear_recording(self) -> None:
|
||||
"""Clear recorded frames."""
|
||||
self._recorded_frames = []
|
||||
|
||||
def save_recording(self, filepath: str | Path) -> None:
|
||||
"""Save recorded frames to a JSON file.
|
||||
|
||||
Args:
|
||||
filepath: Path to save the recording
|
||||
"""
|
||||
path = Path(filepath)
|
||||
data = {
|
||||
"version": 1,
|
||||
"display": "null",
|
||||
"width": self.width,
|
||||
"height": self.height,
|
||||
"frame_count": len(self._recorded_frames),
|
||||
"frames": self._recorded_frames,
|
||||
}
|
||||
path.write_text(json.dumps(data, indent=2))
|
||||
|
||||
def load_recording(self, filepath: str | Path) -> list[dict[str, Any]]:
|
||||
"""Load recorded frames from a JSON file.
|
||||
|
||||
Args:
|
||||
filepath: Path to load the recording from
|
||||
|
||||
Returns:
|
||||
List of frame dicts
|
||||
"""
|
||||
path = Path(filepath)
|
||||
data = json.loads(path.read_text())
|
||||
self._recorded_frames = data.get("frames", [])
|
||||
self.width = data.get("width", 80)
|
||||
self.height = data.get("height", 24)
|
||||
return self._recorded_frames
|
||||
|
||||
def replay_frames(self) -> list[list[str]]:
|
||||
"""Get frames for replay.
|
||||
|
||||
Returns:
|
||||
List of buffers for replay
|
||||
"""
|
||||
return self.get_frames()
|
||||
|
||||
def clear(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
122
engine/display/backends/replay.py
Normal file
122
engine/display/backends/replay.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
Replay display backend - plays back recorded frames.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ReplayDisplay:
|
||||
"""Replay display - plays back recorded frames.
|
||||
|
||||
This display reads frames from a recording (list of frame data)
|
||||
and yields them sequentially, useful for testing and demo purposes.
|
||||
"""
|
||||
|
||||
width: int = 80
|
||||
height: int = 24
|
||||
|
||||
def __init__(self):
|
||||
self._frames: list[dict[str, Any]] = []
|
||||
self._current_frame = 0
|
||||
self._playback_index = 0
|
||||
self._loop = False
|
||||
|
||||
def init(self, width: int, height: int, reuse: bool = False) -> None:
|
||||
"""Initialize display with dimensions.
|
||||
|
||||
Args:
|
||||
width: Terminal width in characters
|
||||
height: Terminal height in rows
|
||||
reuse: Ignored for ReplayDisplay
|
||||
"""
|
||||
self.width = width
|
||||
self.height = height
|
||||
|
||||
def set_frames(self, frames: list[dict[str, Any]]) -> None:
|
||||
"""Set frames to replay.
|
||||
|
||||
Args:
|
||||
frames: List of frame dicts with 'buffer', 'width', 'height'
|
||||
"""
|
||||
self._frames = frames
|
||||
self._current_frame = 0
|
||||
self._playback_index = 0
|
||||
|
||||
def set_loop(self, loop: bool) -> None:
|
||||
"""Set loop playback mode.
|
||||
|
||||
Args:
|
||||
loop: True to loop, False to stop at end
|
||||
"""
|
||||
self._loop = loop
|
||||
|
||||
def show(self, buffer: list[str], border: bool = False) -> None:
|
||||
"""Display a frame (ignored in replay mode).
|
||||
|
||||
Args:
|
||||
buffer: Buffer to display (ignored)
|
||||
border: Border flag (ignored)
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_next_frame(self) -> list[str] | None:
|
||||
"""Get the next frame in the recording.
|
||||
|
||||
Returns:
|
||||
Buffer list of strings, or None if playback is done
|
||||
"""
|
||||
if not self._frames:
|
||||
return None
|
||||
|
||||
if self._playback_index >= len(self._frames):
|
||||
if self._loop:
|
||||
self._playback_index = 0
|
||||
else:
|
||||
return None
|
||||
|
||||
frame = self._frames[self._playback_index]
|
||||
self._playback_index += 1
|
||||
return frame.get("buffer")
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Reset playback to the beginning."""
|
||||
self._playback_index = 0
|
||||
|
||||
def seek(self, index: int) -> None:
|
||||
"""Seek to a specific frame.
|
||||
|
||||
Args:
|
||||
index: Frame index to seek to
|
||||
"""
|
||||
if 0 <= index < len(self._frames):
|
||||
self._playback_index = index
|
||||
|
||||
def is_finished(self) -> bool:
|
||||
"""Check if playback is finished.
|
||||
|
||||
Returns:
|
||||
True if at end of frames and not looping
|
||||
"""
|
||||
return not self._loop and self._playback_index >= len(self._frames)
|
||||
|
||||
def clear(self) -> None:
|
||||
pass
|
||||
|
||||
def cleanup(self) -> None:
|
||||
pass
|
||||
|
||||
def get_dimensions(self) -> tuple[int, int]:
|
||||
"""Get current dimensions.
|
||||
|
||||
Returns:
|
||||
(width, height) in character cells
|
||||
"""
|
||||
return (self.width, self.height)
|
||||
|
||||
def is_quit_requested(self) -> bool:
|
||||
"""Check if quit was requested (optional protocol method)."""
|
||||
return False
|
||||
|
||||
def clear_quit_request(self) -> None:
|
||||
"""Clear quit request (optional protocol method)."""
|
||||
pass
|
||||
122
engine/effects/plugins/afterimage.py
Normal file
122
engine/effects/plugins/afterimage.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Afterimage effect using previous frame."""
|
||||
|
||||
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
|
||||
|
||||
|
||||
class AfterimageEffect(EffectPlugin):
|
||||
"""Show a faint ghost of the previous frame.
|
||||
|
||||
This effect requires a FrameBufferStage to be present in the pipeline.
|
||||
It shows a dimmed version of the previous frame super-imposed on the
|
||||
current frame.
|
||||
|
||||
Attributes:
|
||||
name: "afterimage"
|
||||
config: EffectConfig with intensity parameter (0.0-1.0)
|
||||
param_bindings: Optional sensor bindings for intensity modulation
|
||||
|
||||
Example:
|
||||
>>> effect = AfterimageEffect()
|
||||
>>> effect.configure(EffectConfig(intensity=0.3))
|
||||
>>> result = effect.process(buffer, ctx)
|
||||
"""
|
||||
|
||||
name = "afterimage"
|
||||
config: EffectConfig = EffectConfig(enabled=True, intensity=0.3)
|
||||
param_bindings: dict[str, dict[str, str | float]] = {}
|
||||
supports_partial_updates = False
|
||||
|
||||
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
|
||||
"""Apply afterimage effect using the previous frame.
|
||||
|
||||
Args:
|
||||
buf: Current text buffer (list of strings)
|
||||
ctx: Effect context with access to framebuffer history
|
||||
|
||||
Returns:
|
||||
Buffer with ghost of previous frame overlaid
|
||||
"""
|
||||
if not buf:
|
||||
return buf
|
||||
|
||||
# Get framebuffer history from context
|
||||
history = None
|
||||
|
||||
for key in ctx.state:
|
||||
if key.startswith("framebuffer.") and key.endswith(".history"):
|
||||
history = ctx.state[key]
|
||||
break
|
||||
|
||||
if not history or len(history) < 1:
|
||||
# No previous frame available
|
||||
return buf
|
||||
|
||||
# Get intensity from config
|
||||
intensity = self.config.params.get("intensity", self.config.intensity)
|
||||
intensity = max(0.0, min(1.0, intensity))
|
||||
|
||||
if intensity <= 0.0:
|
||||
return buf
|
||||
|
||||
# Get the previous frame (index 1, since index 0 is current)
|
||||
prev_frame = history[1] if len(history) > 1 else None
|
||||
if not prev_frame:
|
||||
return buf
|
||||
|
||||
# Blend current and previous frames
|
||||
viewport_height = ctx.terminal_height - ctx.ticker_height
|
||||
result = []
|
||||
|
||||
for row in range(len(buf)):
|
||||
if row >= viewport_height:
|
||||
result.append(buf[row])
|
||||
continue
|
||||
|
||||
current_line = buf[row]
|
||||
prev_line = prev_frame[row] if row < len(prev_frame) else ""
|
||||
|
||||
if not prev_line:
|
||||
result.append(current_line)
|
||||
continue
|
||||
|
||||
# Apply dimming effect by reducing ANSI color intensity or adding transparency
|
||||
# For a simple text version, we'll use a blend strategy
|
||||
blended = self._blend_lines(current_line, prev_line, intensity)
|
||||
result.append(blended)
|
||||
|
||||
return result
|
||||
|
||||
def _blend_lines(self, current: str, previous: str, intensity: float) -> str:
|
||||
"""Blend current and previous line with given intensity.
|
||||
|
||||
For text with ANSI codes, true blending is complex. This is a simplified
|
||||
version that uses color averaging when possible.
|
||||
|
||||
A more sophisticated implementation would:
|
||||
1. Parse ANSI color codes from both lines
|
||||
2. Blend RGB values based on intensity
|
||||
3. Reconstruct the line with blended colors
|
||||
|
||||
For now, we'll use a heuristic: if lines are similar, return current.
|
||||
If they differ, we alternate or use the previous as a faint overlay.
|
||||
"""
|
||||
if current == previous:
|
||||
return current
|
||||
|
||||
# Simple blending: intensity determines mix
|
||||
# intensity=1.0 => fully current
|
||||
# intensity=0.3 => 70% previous ghost, 30% current
|
||||
|
||||
if intensity > 0.7:
|
||||
return current
|
||||
elif intensity < 0.3:
|
||||
# Show previous but dimmed (simulate by adding faint color/gray)
|
||||
return previous # Would need to dim ANSI colors
|
||||
else:
|
||||
# For medium intensity, alternate based on character pattern
|
||||
# This is a placeholder for proper blending
|
||||
return current
|
||||
|
||||
def configure(self, config: EffectConfig) -> None:
|
||||
"""Configure the effect."""
|
||||
self.config = config
|
||||
119
engine/effects/plugins/motionblur.py
Normal file
119
engine/effects/plugins/motionblur.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Motion blur effect using frame history."""
|
||||
|
||||
from engine.effects.types import EffectConfig, EffectContext, EffectPlugin
|
||||
|
||||
|
||||
class MotionBlurEffect(EffectPlugin):
|
||||
"""Apply motion blur by blending current frame with previous frames.
|
||||
|
||||
This effect requires a FrameBufferStage to be present in the pipeline.
|
||||
The framebuffer provides frame history which is blended with the current
|
||||
frame based on intensity.
|
||||
|
||||
Attributes:
|
||||
name: "motionblur"
|
||||
config: EffectConfig with intensity parameter (0.0-1.0)
|
||||
param_bindings: Optional sensor bindings for intensity modulation
|
||||
|
||||
Example:
|
||||
>>> effect = MotionBlurEffect()
|
||||
>>> effect.configure(EffectConfig(intensity=0.5))
|
||||
>>> result = effect.process(buffer, ctx)
|
||||
"""
|
||||
|
||||
name = "motionblur"
|
||||
config: EffectConfig = EffectConfig(enabled=True, intensity=0.5)
|
||||
param_bindings: dict[str, dict[str, str | float]] = {}
|
||||
supports_partial_updates = False
|
||||
|
||||
def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
|
||||
"""Apply motion blur by blending with previous frames.
|
||||
|
||||
Args:
|
||||
buf: Current text buffer (list of strings)
|
||||
ctx: Effect context with access to framebuffer history
|
||||
|
||||
Returns:
|
||||
Blended buffer with motion blur effect applied
|
||||
"""
|
||||
if not buf:
|
||||
return buf
|
||||
|
||||
# Get framebuffer history from context
|
||||
# We'll look for the first available framebuffer history
|
||||
history = None
|
||||
|
||||
for key in ctx.state:
|
||||
if key.startswith("framebuffer.") and key.endswith(".history"):
|
||||
history = ctx.state[key]
|
||||
break
|
||||
|
||||
if not history:
|
||||
# No framebuffer available, return unchanged
|
||||
return buf
|
||||
|
||||
# Get intensity from config
|
||||
intensity = self.config.params.get("intensity", self.config.intensity)
|
||||
intensity = max(0.0, min(1.0, intensity))
|
||||
|
||||
if intensity <= 0.0:
|
||||
return buf
|
||||
|
||||
# Get decay factor (how quickly older frames fade)
|
||||
decay = self.config.params.get("decay", 0.7)
|
||||
|
||||
# Build output buffer
|
||||
result = []
|
||||
viewport_height = ctx.terminal_height - ctx.ticker_height
|
||||
|
||||
# Determine how many frames to blend (up to history depth)
|
||||
max_frames = min(len(history), 5) # Cap at 5 frames for performance
|
||||
|
||||
for row in range(len(buf)):
|
||||
if row >= viewport_height:
|
||||
# Beyond viewport, just copy
|
||||
result.append(buf[row])
|
||||
continue
|
||||
|
||||
# Start with current frame
|
||||
blended = buf[row]
|
||||
|
||||
# Blend with historical frames
|
||||
weight_sum = 1.0
|
||||
if max_frames > 0 and intensity > 0:
|
||||
for i in range(max_frames):
|
||||
frame_weight = intensity * (decay**i)
|
||||
if frame_weight < 0.01: # Skip negligible weights
|
||||
break
|
||||
|
||||
hist_row = history[i][row] if row < len(history[i]) else ""
|
||||
# Simple string blending: we'll concatenate with space
|
||||
# For a proper effect, we'd need to blend ANSI colors
|
||||
# This is a simplified version that just adds the frames
|
||||
blended = self._blend_strings(blended, hist_row, frame_weight)
|
||||
weight_sum += frame_weight
|
||||
|
||||
result.append(blended)
|
||||
|
||||
return result
|
||||
|
||||
def _blend_strings(self, current: str, historical: str, weight: float) -> str:
|
||||
"""Blend two strings with given weight.
|
||||
|
||||
This is a simplified blending that works with ANSI codes.
|
||||
For proper blending we'd need to parse colors, but for now
|
||||
we use a heuristic: if strings are identical, return one.
|
||||
If they differ, we alternate or concatenate based on weight.
|
||||
"""
|
||||
if current == historical:
|
||||
return current
|
||||
|
||||
# If weight is high, show current; if low, show historical
|
||||
if weight > 0.5:
|
||||
return current
|
||||
else:
|
||||
return historical
|
||||
|
||||
def configure(self, config: EffectConfig) -> None:
|
||||
"""Configure the effect."""
|
||||
self.config = config
|
||||
@@ -4,7 +4,7 @@ This module provides adapters that wrap existing components
|
||||
(EffectPlugin, Display, DataSource, Camera) as Stage implementations.
|
||||
"""
|
||||
|
||||
from .camera import CameraStage
|
||||
from .camera import CameraClockStage, CameraStage
|
||||
from .data_source import DataSourceStage, PassthroughStage, SourceItemsToBufferStage
|
||||
from .display import DisplayStage
|
||||
from .effect_plugin import EffectPluginStage
|
||||
@@ -30,6 +30,7 @@ __all__ = [
|
||||
"PassthroughStage",
|
||||
"SourceItemsToBufferStage",
|
||||
"CameraStage",
|
||||
"CameraClockStage",
|
||||
"ViewportFilterStage",
|
||||
"FontStage",
|
||||
"ImageToTextStage",
|
||||
|
||||
@@ -6,8 +6,83 @@ from typing import Any
|
||||
from engine.pipeline.core import DataType, PipelineContext, Stage
|
||||
|
||||
|
||||
class CameraClockStage(Stage):
|
||||
"""Per-frame clock stage that updates camera state.
|
||||
|
||||
This stage runs once per frame and updates the camera's internal state
|
||||
(position, time). It makes camera_y/camera_x available to subsequent
|
||||
stages via the pipeline context.
|
||||
|
||||
Unlike other stages, this is a pure clock stage and doesn't process
|
||||
data - it just updates camera state and passes data through unchanged.
|
||||
"""
|
||||
|
||||
def __init__(self, camera, name: str = "camera-clock"):
|
||||
self._camera = camera
|
||||
self.name = name
|
||||
self.category = "camera"
|
||||
self.optional = False
|
||||
self._last_frame_time: float | None = None
|
||||
|
||||
@property
|
||||
def stage_type(self) -> str:
|
||||
return "camera"
|
||||
|
||||
@property
|
||||
def capabilities(self) -> set[str]:
|
||||
# Provides camera state info only
|
||||
# NOTE: Do NOT provide "source" as it conflicts with viewport_filter's "source.filtered"
|
||||
return {"camera.state"}
|
||||
|
||||
@property
|
||||
def dependencies(self) -> set[str]:
|
||||
# Clock stage - no dependencies (updates every frame regardless of data flow)
|
||||
return set()
|
||||
|
||||
@property
|
||||
def inlet_types(self) -> set:
|
||||
# Accept any data type - this is a pass-through stage
|
||||
return {DataType.ANY}
|
||||
|
||||
@property
|
||||
def outlet_types(self) -> set:
|
||||
# Pass through whatever was received
|
||||
return {DataType.ANY}
|
||||
|
||||
def process(self, data: Any, ctx: PipelineContext) -> Any:
|
||||
"""Update camera state and pass data through.
|
||||
|
||||
This stage updates the camera's internal state (position, time) and
|
||||
makes the updated camera_y/camera_x available to subsequent stages
|
||||
via the pipeline context.
|
||||
|
||||
The data is passed through unchanged - this stage only updates
|
||||
camera state, it doesn't transform the data.
|
||||
"""
|
||||
if data is None:
|
||||
return data
|
||||
|
||||
current_time = time.perf_counter()
|
||||
dt = 0.0
|
||||
if self._last_frame_time is not None:
|
||||
dt = current_time - self._last_frame_time
|
||||
self._camera.update(dt)
|
||||
self._last_frame_time = current_time
|
||||
|
||||
# Update context with current camera position
|
||||
ctx.set_state("camera_y", self._camera.y)
|
||||
ctx.set_state("camera_x", self._camera.x)
|
||||
|
||||
# Pass data through unchanged
|
||||
return data
|
||||
|
||||
|
||||
class CameraStage(Stage):
|
||||
"""Adapter wrapping Camera as a Stage."""
|
||||
"""Adapter wrapping Camera as a Stage.
|
||||
|
||||
This stage applies camera viewport transformation to the rendered buffer.
|
||||
Camera state updates are handled by CameraClockStage.
|
||||
"""
|
||||
|
||||
def __init__(self, camera, name: str = "vertical"):
|
||||
self._camera = camera
|
||||
@@ -22,7 +97,7 @@ class CameraStage(Stage):
|
||||
Returns:
|
||||
Dictionary containing camera state that can be restored
|
||||
"""
|
||||
return {
|
||||
state = {
|
||||
"x": self._camera.x,
|
||||
"y": self._camera.y,
|
||||
"mode": self._camera.mode.value
|
||||
@@ -36,6 +111,14 @@ class CameraStage(Stage):
|
||||
"_y_float": getattr(self._camera, "_y_float", 0.0),
|
||||
"_time": getattr(self._camera, "_time", 0.0),
|
||||
}
|
||||
# Save radial camera state if present
|
||||
if hasattr(self._camera, "_r_float"):
|
||||
state["_r_float"] = self._camera._r_float
|
||||
if hasattr(self._camera, "_theta_float"):
|
||||
state["_theta_float"] = self._camera._theta_float
|
||||
if hasattr(self._camera, "_radial_input"):
|
||||
state["_radial_input"] = self._camera._radial_input
|
||||
return state
|
||||
|
||||
def restore_state(self, state: dict[str, Any]) -> None:
|
||||
"""Restore camera state from saved state.
|
||||
@@ -68,6 +151,14 @@ class CameraStage(Stage):
|
||||
if hasattr(self._camera, "_time"):
|
||||
self._camera._time = state.get("_time", 0.0)
|
||||
|
||||
# Restore radial camera state if present
|
||||
if hasattr(self._camera, "_r_float"):
|
||||
self._camera._r_float = state.get("_r_float", 0.0)
|
||||
if hasattr(self._camera, "_theta_float"):
|
||||
self._camera._theta_float = state.get("_theta_float", 0.0)
|
||||
if hasattr(self._camera, "_radial_input"):
|
||||
self._camera._radial_input = state.get("_radial_input", 0.0)
|
||||
|
||||
@property
|
||||
def stage_type(self) -> str:
|
||||
return "camera"
|
||||
@@ -93,18 +184,26 @@ class CameraStage(Stage):
|
||||
if data is None:
|
||||
return data
|
||||
|
||||
current_time = time.perf_counter()
|
||||
dt = 0.0
|
||||
if self._last_frame_time is not None:
|
||||
dt = current_time - self._last_frame_time
|
||||
self._camera.update(dt)
|
||||
self._last_frame_time = current_time
|
||||
|
||||
ctx.set_state("camera_y", self._camera.y)
|
||||
ctx.set_state("camera_x", self._camera.x)
|
||||
# Camera state is updated by CameraClockStage
|
||||
# We only apply the viewport transformation here
|
||||
|
||||
if hasattr(self._camera, "apply"):
|
||||
viewport_width = ctx.params.viewport_width if ctx.params else 80
|
||||
viewport_height = ctx.params.viewport_height if ctx.params else 24
|
||||
return self._camera.apply(data, viewport_width, viewport_height)
|
||||
|
||||
# Use filtered camera position if available (from ViewportFilterStage)
|
||||
# This handles the case where the buffer has been filtered and starts at row 0
|
||||
filtered_camera_y = ctx.get("camera_y", self._camera.y)
|
||||
|
||||
# Temporarily adjust camera position for filtering
|
||||
original_y = self._camera.y
|
||||
self._camera.y = filtered_camera_y
|
||||
|
||||
try:
|
||||
result = self._camera.apply(data, viewport_width, viewport_height)
|
||||
finally:
|
||||
# Restore original camera position
|
||||
self._camera.y = original_y
|
||||
|
||||
return result
|
||||
return data
|
||||
|
||||
@@ -6,13 +6,22 @@ from engine.pipeline.core import PipelineContext, Stage
|
||||
|
||||
|
||||
class EffectPluginStage(Stage):
|
||||
"""Adapter wrapping EffectPlugin as a Stage."""
|
||||
"""Adapter wrapping EffectPlugin as a Stage.
|
||||
|
||||
def __init__(self, effect_plugin, name: str = "effect"):
|
||||
Supports capability-based dependencies through the dependencies parameter.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
effect_plugin,
|
||||
name: str = "effect",
|
||||
dependencies: set[str] | None = None,
|
||||
):
|
||||
self._effect = effect_plugin
|
||||
self.name = name
|
||||
self.category = "effect"
|
||||
self.optional = False
|
||||
self._dependencies = dependencies or set()
|
||||
|
||||
@property
|
||||
def stage_type(self) -> str:
|
||||
@@ -49,7 +58,7 @@ class EffectPluginStage(Stage):
|
||||
|
||||
@property
|
||||
def dependencies(self) -> set[str]:
|
||||
return set()
|
||||
return self._dependencies
|
||||
|
||||
@property
|
||||
def inlet_types(self) -> set:
|
||||
|
||||
@@ -49,7 +49,9 @@ class ViewportFilterStage(Stage):
|
||||
|
||||
@property
|
||||
def dependencies(self) -> set[str]:
|
||||
return {"source"}
|
||||
# Always requires camera.state for viewport filtering
|
||||
# CameraUpdateStage provides this (auto-injected if missing)
|
||||
return {"source", "camera.state"}
|
||||
|
||||
@property
|
||||
def inlet_types(self) -> set:
|
||||
@@ -95,9 +97,13 @@ class ViewportFilterStage(Stage):
|
||||
|
||||
# Find start index (first item that intersects with visible range)
|
||||
start_idx = 0
|
||||
start_item_y = 0 # Y position where the first visible item starts
|
||||
for i, total_h in enumerate(cumulative_heights):
|
||||
if total_h > start_y:
|
||||
start_idx = i
|
||||
# Calculate the Y position of the start of this item
|
||||
if i > 0:
|
||||
start_item_y = cumulative_heights[i - 1]
|
||||
break
|
||||
|
||||
# Find end index (first item that extends beyond visible range)
|
||||
@@ -107,6 +113,16 @@ class ViewportFilterStage(Stage):
|
||||
end_idx = i + 1
|
||||
break
|
||||
|
||||
# Adjust camera_y for the filtered buffer
|
||||
# The filtered buffer starts at row 0, but the camera position
|
||||
# needs to be relative to where the first visible item starts
|
||||
filtered_camera_y = camera_y - start_item_y
|
||||
|
||||
# Update context with the filtered camera position
|
||||
# This ensures CameraStage can correctly slice the filtered buffer
|
||||
ctx.set_state("camera_y", filtered_camera_y)
|
||||
ctx.set_state("camera_x", ctx.get("camera_x", 0)) # Keep camera_x unchanged
|
||||
|
||||
# Return visible items
|
||||
return data[start_idx:end_idx]
|
||||
|
||||
@@ -127,9 +143,16 @@ class FontStage(Stage):
|
||||
def capabilities(self) -> set[str]:
|
||||
return {"render.output"}
|
||||
|
||||
@property
|
||||
def stage_dependencies(self) -> set[str]:
|
||||
# Must connect to viewport_filter stage to get filtered source
|
||||
return {"viewport_filter"}
|
||||
|
||||
@property
|
||||
def dependencies(self) -> set[str]:
|
||||
return {"source"}
|
||||
# Depend on source.filtered (provided by viewport_filter)
|
||||
# This ensures we get the filtered/processed source, not raw source
|
||||
return {"source.filtered"}
|
||||
|
||||
@property
|
||||
def inlet_types(self) -> set:
|
||||
@@ -147,6 +170,11 @@ class FontStage(Stage):
|
||||
if not isinstance(data, list):
|
||||
return [str(data)]
|
||||
|
||||
import os
|
||||
|
||||
if os.environ.get("DEBUG_CAMERA"):
|
||||
print(f"FontStage: input items={len(data)}")
|
||||
|
||||
viewport_width = ctx.params.viewport_width if ctx.params else 80
|
||||
|
||||
result = []
|
||||
|
||||
@@ -68,6 +68,15 @@ class Pipeline:
|
||||
self._metrics_enabled = self.config.enable_metrics
|
||||
self._frame_metrics: list[FrameMetrics] = []
|
||||
self._max_metrics_frames = 60
|
||||
|
||||
# Minimum capabilities required for pipeline to function
|
||||
# NOTE: Research later - allow presets to override these defaults
|
||||
self._minimum_capabilities: set[str] = {
|
||||
"source",
|
||||
"render.output",
|
||||
"display.output",
|
||||
"camera.state", # Always required for viewport filtering
|
||||
}
|
||||
self._current_frame_number = 0
|
||||
|
||||
def add_stage(self, name: str, stage: Stage, initialize: bool = True) -> "Pipeline":
|
||||
@@ -214,15 +223,22 @@ class Pipeline:
|
||||
pass
|
||||
|
||||
def _rebuild(self) -> None:
|
||||
"""Rebuild execution order after mutation without full reinitialization."""
|
||||
"""Rebuild execution order after mutation or auto-injection."""
|
||||
was_initialized = self._initialized
|
||||
self._initialized = False
|
||||
|
||||
self._capability_map = self._build_capability_map()
|
||||
self._execution_order = self._resolve_dependencies()
|
||||
|
||||
try:
|
||||
self._validate_dependencies()
|
||||
self._validate_types()
|
||||
except StageError:
|
||||
pass
|
||||
|
||||
# Restore initialized state
|
||||
self._initialized = was_initialized
|
||||
|
||||
def get_stage(self, name: str) -> Stage | None:
|
||||
"""Get a stage by name."""
|
||||
return self._stages.get(name)
|
||||
@@ -297,10 +313,123 @@ class Pipeline:
|
||||
"stage_count": len(self._stages),
|
||||
}
|
||||
|
||||
def build(self) -> "Pipeline":
|
||||
"""Build execution order based on dependencies."""
|
||||
@property
|
||||
def minimum_capabilities(self) -> set[str]:
|
||||
"""Get minimum capabilities required for pipeline to function."""
|
||||
return self._minimum_capabilities
|
||||
|
||||
@minimum_capabilities.setter
|
||||
def minimum_capabilities(self, value: set[str]):
|
||||
"""Set minimum required capabilities.
|
||||
|
||||
NOTE: Research later - allow presets to override these defaults
|
||||
"""
|
||||
self._minimum_capabilities = value
|
||||
|
||||
def validate_minimum_capabilities(self) -> tuple[bool, list[str]]:
|
||||
"""Validate that all minimum capabilities are provided.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, missing_capabilities)
|
||||
"""
|
||||
missing = []
|
||||
for cap in self._minimum_capabilities:
|
||||
if not self._find_stage_with_capability(cap):
|
||||
missing.append(cap)
|
||||
return len(missing) == 0, missing
|
||||
|
||||
def ensure_minimum_capabilities(self) -> list[str]:
|
||||
"""Automatically inject MVP stages if minimum capabilities are missing.
|
||||
|
||||
Auto-injection is always on, but defaults are trivial to override.
|
||||
Returns:
|
||||
List of stages that were injected
|
||||
"""
|
||||
from engine.camera import Camera
|
||||
from engine.data_sources.sources import EmptyDataSource
|
||||
from engine.display import DisplayRegistry
|
||||
from engine.pipeline.adapters import (
|
||||
CameraClockStage,
|
||||
CameraStage,
|
||||
DataSourceStage,
|
||||
DisplayStage,
|
||||
SourceItemsToBufferStage,
|
||||
)
|
||||
|
||||
injected = []
|
||||
|
||||
# Check for source capability
|
||||
if (
|
||||
not self._find_stage_with_capability("source")
|
||||
and "source" not in self._stages
|
||||
):
|
||||
empty_source = EmptyDataSource(width=80, height=24)
|
||||
self.add_stage("source", DataSourceStage(empty_source, name="empty"))
|
||||
injected.append("source")
|
||||
|
||||
# Check for camera.state capability (must be BEFORE render to accept SOURCE_ITEMS)
|
||||
camera = None
|
||||
if not self._find_stage_with_capability("camera.state"):
|
||||
# Inject static camera (trivial, no movement)
|
||||
camera = Camera.scroll(speed=0.0)
|
||||
camera.set_canvas_size(200, 200)
|
||||
if "camera_update" not in self._stages:
|
||||
self.add_stage(
|
||||
"camera_update", CameraClockStage(camera, name="camera-clock")
|
||||
)
|
||||
injected.append("camera_update")
|
||||
|
||||
# Check for render capability
|
||||
if (
|
||||
not self._find_stage_with_capability("render.output")
|
||||
and "render" not in self._stages
|
||||
):
|
||||
self.add_stage("render", SourceItemsToBufferStage(name="items-to-buffer"))
|
||||
injected.append("render")
|
||||
|
||||
# Check for camera stage (must be AFTER render to accept TEXT_BUFFER)
|
||||
if camera and "camera" not in self._stages:
|
||||
self.add_stage("camera", CameraStage(camera, name="static"))
|
||||
injected.append("camera")
|
||||
|
||||
# Check for display capability
|
||||
if (
|
||||
not self._find_stage_with_capability("display.output")
|
||||
and "display" not in self._stages
|
||||
):
|
||||
display = DisplayRegistry.create("terminal")
|
||||
if display:
|
||||
self.add_stage("display", DisplayStage(display, name="terminal"))
|
||||
injected.append("display")
|
||||
|
||||
# Rebuild pipeline if stages were injected
|
||||
if injected:
|
||||
self._rebuild()
|
||||
|
||||
return injected
|
||||
|
||||
def build(self, auto_inject: bool = True) -> "Pipeline":
|
||||
"""Build execution order based on dependencies.
|
||||
|
||||
Args:
|
||||
auto_inject: If True, automatically inject MVP stages for missing capabilities
|
||||
"""
|
||||
self._capability_map = self._build_capability_map()
|
||||
self._execution_order = self._resolve_dependencies()
|
||||
|
||||
# Validate minimum capabilities and auto-inject if needed
|
||||
if auto_inject:
|
||||
is_valid, missing = self.validate_minimum_capabilities()
|
||||
if not is_valid:
|
||||
injected = self.ensure_minimum_capabilities()
|
||||
if injected:
|
||||
print(
|
||||
f" \033[38;5;226mAuto-injected stages for missing capabilities: {injected}\033[0m"
|
||||
)
|
||||
# Rebuild after auto-injection
|
||||
self._capability_map = self._build_capability_map()
|
||||
self._execution_order = self._resolve_dependencies()
|
||||
|
||||
self._validate_dependencies()
|
||||
self._validate_types()
|
||||
self._initialized = True
|
||||
@@ -367,12 +496,24 @@ class Pipeline:
|
||||
temp_mark.add(name)
|
||||
stage = self._stages.get(name)
|
||||
if stage:
|
||||
# Handle capability-based dependencies
|
||||
for dep in stage.dependencies:
|
||||
# Find a stage that provides this capability
|
||||
dep_stage_name = self._find_stage_with_capability(dep)
|
||||
if dep_stage_name:
|
||||
visit(dep_stage_name)
|
||||
|
||||
# Handle direct stage dependencies
|
||||
for stage_dep in stage.stage_dependencies:
|
||||
if stage_dep in self._stages:
|
||||
visit(stage_dep)
|
||||
else:
|
||||
# Stage dependency not found - this is an error
|
||||
raise StageError(
|
||||
name,
|
||||
f"Missing stage dependency: '{stage_dep}' not found in pipeline",
|
||||
)
|
||||
|
||||
temp_mark.remove(name)
|
||||
visited.add(name)
|
||||
ordered.append(name)
|
||||
|
||||
@@ -155,6 +155,21 @@ class Stage(ABC):
|
||||
"""
|
||||
return set()
|
||||
|
||||
@property
|
||||
def stage_dependencies(self) -> set[str]:
|
||||
"""Return set of stage names this stage must connect to directly.
|
||||
|
||||
This allows explicit stage-to-stage dependencies, useful for enforcing
|
||||
pipeline structure when capability matching alone is insufficient.
|
||||
|
||||
Examples:
|
||||
- {"viewport_filter"} # Must connect to viewport_filter stage
|
||||
- {"camera_update"} # Must connect to camera_update stage
|
||||
|
||||
NOTE: These are stage names (as added to pipeline), not capabilities.
|
||||
"""
|
||||
return set()
|
||||
|
||||
def init(self, ctx: "PipelineContext") -> bool:
|
||||
"""Initialize stage with pipeline context.
|
||||
|
||||
|
||||
@@ -50,6 +50,11 @@ class PipelinePreset:
|
||||
border: bool | BorderMode = (
|
||||
False # Border mode: False=off, True=simple, BorderMode.UI for panel
|
||||
)
|
||||
# Extended fields for fine-tuning
|
||||
camera_speed: float = 1.0 # Camera movement speed
|
||||
viewport_width: int = 80 # Viewport width in columns
|
||||
viewport_height: int = 24 # Viewport height in rows
|
||||
source_items: list[dict[str, Any]] | None = None # For ListDataSource
|
||||
|
||||
def to_params(self) -> PipelineParams:
|
||||
"""Convert to PipelineParams."""
|
||||
@@ -67,6 +72,8 @@ class PipelinePreset:
|
||||
)
|
||||
params.camera_mode = self.camera
|
||||
params.effect_order = self.effects.copy()
|
||||
# Note: camera_speed, viewport_width/height are not stored in PipelineParams
|
||||
# They are used directly from the preset object in pipeline_runner.py
|
||||
return params
|
||||
|
||||
@classmethod
|
||||
@@ -80,6 +87,10 @@ class PipelinePreset:
|
||||
camera=data.get("camera", "vertical"),
|
||||
effects=data.get("effects", []),
|
||||
border=data.get("border", False),
|
||||
camera_speed=data.get("camera_speed", 1.0),
|
||||
viewport_width=data.get("viewport_width", 80),
|
||||
viewport_height=data.get("viewport_height", 24),
|
||||
source_items=data.get("source_items"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"""
|
||||
Frame buffer stage - stores previous frames for temporal effects.
|
||||
|
||||
Provides:
|
||||
- frame_history: list of previous buffers (most recent first)
|
||||
- intensity_history: list of corresponding intensity maps
|
||||
- current_intensity: intensity map for current frame
|
||||
Provides (per-instance, using instance name):
|
||||
- framebuffer.{name}.history: list of previous buffers (most recent first)
|
||||
- framebuffer.{name}.intensity_history: list of corresponding intensity maps
|
||||
- framebuffer.{name}.current_intensity: intensity map for current frame
|
||||
|
||||
Capability: "framebuffer.history"
|
||||
Capability: "framebuffer.history.{name}"
|
||||
"""
|
||||
|
||||
import threading
|
||||
@@ -22,21 +22,32 @@ class FrameBufferConfig:
|
||||
"""Configuration for FrameBufferStage."""
|
||||
|
||||
history_depth: int = 2 # Number of previous frames to keep
|
||||
name: str = "default" # Unique instance name for capability and context keys
|
||||
|
||||
|
||||
class FrameBufferStage(Stage):
|
||||
"""Stores frame history and computes intensity maps."""
|
||||
"""Stores frame history and computes intensity maps.
|
||||
|
||||
Supports multiple instances with unique capabilities and context keys.
|
||||
"""
|
||||
|
||||
name = "framebuffer"
|
||||
category = "effect" # It's an effect that enriches context with frame history
|
||||
|
||||
def __init__(self, config: FrameBufferConfig | None = None, history_depth: int = 2):
|
||||
self.config = config or FrameBufferConfig(history_depth=history_depth)
|
||||
def __init__(
|
||||
self,
|
||||
config: FrameBufferConfig | None = None,
|
||||
history_depth: int = 2,
|
||||
name: str = "default",
|
||||
):
|
||||
self.config = config or FrameBufferConfig(
|
||||
history_depth=history_depth, name=name
|
||||
)
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@property
|
||||
def capabilities(self) -> set[str]:
|
||||
return {"framebuffer.history"}
|
||||
return {f"framebuffer.history.{self.config.name}"}
|
||||
|
||||
@property
|
||||
def dependencies(self) -> set[str]:
|
||||
@@ -53,8 +64,9 @@ class FrameBufferStage(Stage):
|
||||
|
||||
def init(self, ctx: PipelineContext) -> bool:
|
||||
"""Initialize framebuffer state in context."""
|
||||
ctx.set("frame_history", [])
|
||||
ctx.set("intensity_history", [])
|
||||
prefix = f"framebuffer.{self.config.name}"
|
||||
ctx.set(f"{prefix}.history", [])
|
||||
ctx.set(f"{prefix}.intensity_history", [])
|
||||
return True
|
||||
|
||||
def process(self, data: Any, ctx: PipelineContext) -> Any:
|
||||
@@ -70,16 +82,18 @@ class FrameBufferStage(Stage):
|
||||
if not isinstance(data, list):
|
||||
return data
|
||||
|
||||
prefix = f"framebuffer.{self.config.name}"
|
||||
|
||||
# Compute intensity map for current buffer (per-row, length = buffer rows)
|
||||
intensity_map = self._compute_buffer_intensity(data, len(data))
|
||||
|
||||
# Store in context
|
||||
ctx.set("current_intensity", intensity_map)
|
||||
ctx.set(f"{prefix}.current_intensity", intensity_map)
|
||||
|
||||
with self._lock:
|
||||
# Get existing histories
|
||||
history = ctx.get("frame_history", [])
|
||||
intensity_hist = ctx.get("intensity_history", [])
|
||||
history = ctx.get(f"{prefix}.history", [])
|
||||
intensity_hist = ctx.get(f"{prefix}.intensity_history", [])
|
||||
|
||||
# Prepend current frame to history
|
||||
history.insert(0, data.copy())
|
||||
@@ -87,8 +101,8 @@ class FrameBufferStage(Stage):
|
||||
|
||||
# Trim to configured depth
|
||||
max_depth = self.config.history_depth
|
||||
ctx.set("frame_history", history[:max_depth])
|
||||
ctx.set("intensity_history", intensity_hist[:max_depth])
|
||||
ctx.set(f"{prefix}.history", history[:max_depth])
|
||||
ctx.set(f"{prefix}.intensity_history", intensity_hist[:max_depth])
|
||||
|
||||
return data
|
||||
|
||||
@@ -137,7 +151,8 @@ class FrameBufferStage(Stage):
|
||||
"""Get frame from history by index (0 = current, 1 = previous, etc)."""
|
||||
if ctx is None:
|
||||
return None
|
||||
history = ctx.get("frame_history", [])
|
||||
prefix = f"framebuffer.{self.config.name}"
|
||||
history = ctx.get(f"{prefix}.history", [])
|
||||
if 0 <= index < len(history):
|
||||
return history[index]
|
||||
return None
|
||||
@@ -148,7 +163,8 @@ class FrameBufferStage(Stage):
|
||||
"""Get intensity map from history by index."""
|
||||
if ctx is None:
|
||||
return None
|
||||
intensity_hist = ctx.get("intensity_history", [])
|
||||
prefix = f"framebuffer.{self.config.name}"
|
||||
intensity_hist = ctx.get(f"{prefix}.intensity_history", [])
|
||||
if 0 <= index < len(intensity_hist):
|
||||
return intensity_hist[index]
|
||||
return None
|
||||
|
||||
@@ -22,6 +22,8 @@ VALID_CAMERAS = [
|
||||
"omni",
|
||||
"floating",
|
||||
"bounce",
|
||||
"radial",
|
||||
"static",
|
||||
"none",
|
||||
"",
|
||||
]
|
||||
@@ -43,7 +45,7 @@ class ValidationResult:
|
||||
MVP_DEFAULTS = {
|
||||
"source": "fixture",
|
||||
"display": "terminal",
|
||||
"camera": "", # Empty = no camera stage (static viewport)
|
||||
"camera": "static", # Static camera provides camera_y=0 for viewport filtering
|
||||
"effects": [],
|
||||
"border": False,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user