mcp3d

package
v0.4.0-rc.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcp3d is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package mcp3d attaches optional 3D scene graph, camera, 3D physics, raycast, and 3D wireframe-overlay screenshot tools to a running game's *mcp.Bridge.

Call Attach once alongside mcp.Attach on the engine goroutine:

  • game3d_nodes_list: list nodes in a scene3d.Scene (or custom Provider) with stable paths, hierarchy links, tags, local and world transforms, world bounds, sockets, and model/material summaries.
  • game3d_node_inspect: inspect one 3D scene node in detail by path.
  • game3d_camera: read the active scene3d.Camera pose, projection, field of view, clip planes, and six frustum planes.
  • game3d_raycast: cast a ray from a screen point or world origin/direction through scene3d.Scene picking and physics3d.World.
  • game3d_bodies_list: list physics3d.World bodies with motion kind, pose, shape, velocities, sleep state, and active contacts.
  • game3d_screenshot: capture or software-project a 3D frame with optional wireframe overlays (node bounds, physics colliders, camera frusta, grid, axes) as a PNG.

Keeping this package separate from pkg/mcp lets 2D games avoid linking render3d and scenemodel. Under -tags release, Attach is a zero-cost no-op. Nodes, NodePaths, NodeFromScene3D and CameraFromScene3D produce the same reports as the tools without a bridge and stay available under -tags release.

Index

Examples

Constants

View Source
const (
	// ToolNodesList lists nodes in the 3D scene graph with transforms, bounds, sockets, and model/material summaries.
	ToolNodesList = "game3d_nodes_list"
	// ToolNodeInspect inspects one 3D scene node by path.
	ToolNodeInspect = "game3d_node_inspect"
	// ToolCamera reads the active 3D camera pose, projection, and 6 frustum planes.
	ToolCamera = "game3d_camera"
	// ToolRaycast casts a ray from a screen point or world ray through scene3d picking and physics3d.
	ToolRaycast = "game3d_raycast"
	// ToolBodiesList lists 3D physics bodies, shapes, velocities, sleep states, and active contacts.
	ToolBodiesList = "game3d_bodies_list"
	// ToolScreenshot captures or renders a 3D frame with optional wireframe overlays as a PNG.
	ToolScreenshot = "game3d_screenshot"
)

Tool names registered on an *mcp.Bridge by Attach.

Variables

View Source
var ErrNotFound = errors.New("mcp3d: node not found")

ErrNotFound reports that no node has the requested path.

Functions

func Attach

func Attach(bridge *mcp.Bridge, cfg Config) error

Attach registers the 3D scene, camera, raycast, physics, and screenshot MCP tools on bridge. Passing a nil bridge is a no-op returning nil. Call Attach on the engine goroutine alongside mcp.Attach.

func NodePaths

func NodePaths(sc *scene3d.Scene) map[*scene3d.Node]string

NodePaths returns the path game3d_nodes_list assigns to each node of sc: the root's name (or "root"), then "/"-separated child names (or "node" for an unnamed child), with "#N" appended to siblings sharing a name and to any path that would otherwise collide. It returns nil when sc is nil.

Types

type Body

type Body struct {
	ID              int           `json:"id"`
	Tag             string        `json:"tag,omitempty"`
	Kind            string        `json:"kind"`
	Position        Vec3          `json:"position"`
	Rotation        Quat          `json:"rotation"`
	Velocity        Vec3          `json:"velocity"`
	AngularVelocity Vec3          `json:"angularVelocity"`
	Mass            float32       `json:"mass,omitempty"`
	Sleeping        bool          `json:"sleeping"`
	IsTrigger       bool          `json:"isTrigger,omitempty"`
	Layer           uint32        `json:"layer,omitempty"`
	Mask            uint32        `json:"mask,omitempty"`
	Shape           BodyShape     `json:"shape"`
	Contacts        []BodyContact `json:"contacts,omitempty"`
}

Body describes one rigid body, kinematic body, static collider, or trigger in a physics3d.World.

type BodyContact

type BodyContact struct {
	OtherBodyID  int     `json:"otherBodyId"`
	OtherBodyTag string  `json:"otherBodyTag,omitempty"`
	Point        Vec3    `json:"point"`
	Normal       Vec3    `json:"normal"`
	Depth        float32 `json:"depth"`
	IsTrigger    bool    `json:"isTrigger,omitempty"`
}

BodyContact describes one active contact pair involving a physics3d body.

type BodyShape

type BodyShape struct {
	Kind        string  `json:"kind"`
	Center      *Vec3   `json:"center,omitempty"`
	HalfExtents *Vec3   `json:"halfExtents,omitempty"`
	Radius      float32 `json:"radius,omitempty"`
	Height      float32 `json:"height,omitempty"`
	A           *Vec3   `json:"a,omitempty"`
	B           *Vec3   `json:"b,omitempty"`
	VertexCount int     `json:"vertexCount,omitempty"`
	ChildCount  int     `json:"childCount,omitempty"`
}

BodyShape summarizes a physics3d.Shape for inspection over MCP.

type Camera

type Camera struct {
	Position    Vec3    `json:"position"`
	Forward     Vec3    `json:"forward"`
	Projection  string  `json:"projection"`
	FOV         float32 `json:"fov,omitempty"`
	Up          Vec3    `json:"up,omitempty"`
	Right       Vec3    `json:"right,omitempty"`
	Rotation    Quat    `json:"rotation,omitempty"`
	OrthoHeight float32 `json:"orthoHeight,omitempty"`
	Aspect      float32 `json:"aspect,omitempty"`
	Near        float32 `json:"near,omitempty"`
	Far         float32 `json:"far,omitempty"`
	Frustum     []Plane `json:"frustum,omitempty"`
}

Camera is the active camera's pose, projection, and view frustum. Projection is "perspective" or "orthographic"; FOV is the vertical field of view in degrees for a perspective camera.

func CameraFromScene3D

func CameraFromScene3D(cam *scene3d.Camera) (Camera, error)

CameraFromScene3D reports cam as game3d_camera does: pose, projection, field of view in degrees, clip planes and the six inward-pointing frustum planes. Non-finite or degenerate rotation and projection values are replaced with the same defaults the tool uses. It returns an error when cam is nil or its position is not finite.

type Config

type Config struct {
	// Scene is the active scene3d.Scene for node listing, inspection, picking, and bounds overlays.
	Scene *scene3d.Scene
	// SceneFunc dynamically resolves the active scene3d.Scene on each tool call.
	SceneFunc func() *scene3d.Scene

	// Camera is the active scene3d.Camera for camera inspection, screen raycasts, and 3D screenshots.
	Camera *scene3d.Camera
	// CameraFunc dynamically resolves the active scene3d.Camera on each tool call.
	CameraFunc func() *scene3d.Camera
	// ExtraCameras optionally returns additional cameras whose frusta are drawn when frustum overlays are enabled.
	ExtraCameras func() []*scene3d.Camera

	// Physics is the active physics3d.World for body listing, raycasts, and collider overlays.
	Physics *physics3d.World
	// PhysicsFunc dynamically resolves the active physics3d.World on each tool call.
	PhysicsFunc func() *physics3d.World

	// Built is an optional scenemodel.Built level supplying mesh/material summaries, cameras, and wireframe geometry.
	Built *scenemodel.Built
	// BuiltFunc dynamically resolves the active scenemodel.Built on each tool call.
	BuiltFunc func() *scenemodel.Built

	// GridMaps optionally registers named world3d.GridMap instances for scene inspection.
	GridMaps map[string]*world3d.GridMap

	// Provider optionally supplies custom 3D nodes, camera, and raycast behavior when Scene/Camera are unset (or alongside them for raycasts).
	Provider Provider

	// CaptureFrame optionally returns an already-rendered 3D frame (for example from a GPU readback) that game3d_screenshot composites wireframe overlays onto. When nil, game3d_screenshot renders a deterministic software wireframe view through render3d.DebugDraw.
	CaptureFrame func(ctx context.Context, width, height int) (*image.RGBA, error)
	// ScreenshotDir confines relative output paths written by game3d_screenshot through os.Root. When empty, falls back to the attached Bridge's ScreenshotDir.
	ScreenshotDir string
	// ScreenshotBackground fills the canvas before drawing when CaptureFrame is nil (defaults to dark slate #0d1322 when zero).
	ScreenshotBackground core.Color
	// ViewSizeFunc supplies the viewport size used by screen-point raycasts and default screenshot dimensions. When nil, falls back to the attached Bridge's ViewSize and then 640x360.
	ViewSizeFunc func() core.Size
}

Config names the 3D subsystems exposed over MCP by Attach. Every field is optional; *Func getters override the corresponding static pointer when returning non-nil.

type Hit

type Hit struct {
	NodePath      string  `json:"nodePath,omitempty"`
	Point         Vec3    `json:"point"`
	Normal        Vec3    `json:"normal"`
	Distance      float32 `json:"distance"`
	Source        string  `json:"source,omitempty"`
	NodeID        uint64  `json:"nodeId,omitempty"`
	NodeName      string  `json:"nodeName,omitempty"`
	BodyID        int     `json:"bodyId,omitempty"`
	BodyTag       string  `json:"bodyTag,omitempty"`
	TriangleIndex *int    `json:"triangleIndex,omitempty"`
}

Hit is one raycast intersection in world space, from scene3d picking, physics3d, or a custom Provider.

type MaterialSummary

type MaterialSummary struct {
	Name              string     `json:"name,omitempty"`
	BaseColor         [4]float32 `json:"baseColor,omitempty"`
	Metallic          float32    `json:"metallic,omitempty"`
	Roughness         float32    `json:"roughness,omitempty"`
	Emissive          Vec3       `json:"emissive,omitempty"`
	BaseColorTexture  string     `json:"baseColorTexture,omitempty"`
	AlphaMode         string     `json:"alphaMode,omitempty"`
	DoubleSided       bool       `json:"doubleSided,omitempty"`
	DistinctMaterials int        `json:"distinctMaterials,omitempty"`
}

MaterialSummary describes the surface material properties attached to a drawable node.

type Node

type Node struct {
	Path          string           `json:"path"`
	Kind          string           `json:"kind,omitempty"`
	Name          string           `json:"name,omitempty"`
	Position      Vec3             `json:"position"`
	Scale         Vec3             `json:"scale"`
	BoundsMin     Vec3             `json:"boundsMin"`
	BoundsMax     Vec3             `json:"boundsMax"`
	Model         string           `json:"model,omitempty"`
	Material      string           `json:"material,omitempty"`
	ID            uint64           `json:"id,omitempty"`
	Parent        string           `json:"parent,omitempty"`
	Children      []string         `json:"children,omitempty"`
	Tags          []string         `json:"tags,omitempty"`
	Visible       bool             `json:"visible"`
	Enabled       bool             `json:"enabled"`
	Layer         uint32           `json:"layer,omitempty"`
	HasBounds     bool             `json:"hasBounds,omitempty"`
	Local         *Transform       `json:"local,omitempty"`
	World         *Transform       `json:"world,omitempty"`
	Sockets       []Socket         `json:"sockets,omitempty"`
	MeshCount     int              `json:"meshCount,omitempty"`
	TriangleCount int              `json:"triangleCount,omitempty"`
	MaterialInfo  *MaterialSummary `json:"materialInfo,omitempty"`
}

Node is one node of the 3D scene graph. Path is unique within the scene; BoundsMin and BoundsMax are the node's world-space axis-aligned bounds, and Model and Material name the assets it draws with, if any.

func Find

func Find(nodes []Node, path string) (Node, error)

Find returns the node whose path equals path, or ErrNotFound.

Example

ExampleFind inspects an in-memory scene through the Provider contract.

package main

import (
	"errors"
	"fmt"

	"github.com/nsgo-dev/game/pkg/mcp/mcp3d"
)

// scene is a tiny in-memory Provider: a ground plane and a player standing on it.
type scene struct{ nodes []mcp3d.Node }

func (s scene) Nodes() []mcp3d.Node { return s.nodes }

func (scene) Camera() mcp3d.Camera {
	return mcp3d.Camera{Position: mcp3d.Vec3{Y: 2, Z: -5}, Forward: mcp3d.Vec3{Z: 1}, Projection: "perspective", FOV: 60}
}

// Raycast hits the ground for any ray pointing down and misses otherwise.
func (scene) Raycast(origin, direction mcp3d.Vec3) (mcp3d.Hit, bool) {
	if direction.Y >= 0 {
		return mcp3d.Hit{}, false
	}
	return mcp3d.Hit{NodePath: "world/ground", Point: mcp3d.Vec3{X: origin.X, Z: origin.Z}, Normal: mcp3d.Vec3{Y: 1}, Distance: origin.Y}, true
}

// ExampleFind inspects an in-memory scene through the Provider contract.
func main() {
	var p mcp3d.Provider = scene{nodes: []mcp3d.Node{
		{Path: "world/ground", Kind: "mesh", Model: "models/ground.glb"},
		{Path: "world/player", Kind: "mesh", Name: "Player", Position: mcp3d.Vec3{Y: 1}},
	}}

	player, err := mcp3d.Find(p.Nodes(), "world/player")
	fmt.Println(player.Name, player.Position.Y, err)
	_, err = mcp3d.Find(p.Nodes(), "world/enemy")
	fmt.Println(errors.Is(err, mcp3d.ErrNotFound))

	cam := p.Camera()
	fmt.Println(cam.Projection, cam.FOV)

	hit, ok := p.Raycast(mcp3d.Vec3{Y: 3}, mcp3d.Vec3{Y: -1})
	fmt.Println(ok, hit.NodePath, hit.Distance)
	_, ok = p.Raycast(mcp3d.Vec3{Y: 3}, mcp3d.Vec3{Y: 1})
	fmt.Println(ok)
}
Output:
Player 1 <nil>
true
perspective 60
true world/ground 3
false

func NodeFromScene3D

func NodeFromScene3D(n *scene3d.Node, paths map[*scene3d.Node]string, built *scenemodel.Built) Node

NodeFromScene3D reports one node as game3d_node_inspect does. paths maps nodes to their paths, as NodePaths returns them, and resolves the node's own path and those of its parent, children and sockets. built may be nil. The caller must have updated sc's transforms (scene3d.Scene.UpdateTransforms) for world values to be current.

func Nodes

func Nodes(sc *scene3d.Scene, built *scenemodel.Built) []Node

Nodes returns every node of sc in pre-order as game3d_nodes_list reports it, with the same stable paths. built supplies camera and light kinds and may be nil. Nodes calls sc.UpdateTransforms first, so world transforms and bounds are current. It returns nil when sc is nil.

type Plane

type Plane struct {
	Name     string  `json:"name"`
	Normal   Vec3    `json:"normal"`
	Distance float32 `json:"distance"`
}

Plane is one normalized inward-pointing view-frustum half-space (Normal·p + Distance >= 0).

type Provider

type Provider interface {
	Nodes() []Node
	Camera() Camera
	Raycast(origin, direction Vec3) (Hit, bool)
}

Provider is implemented by a game that supplies custom 3D scene graph, camera, and raycast data instead of (or alongside) scene3d and physics3d. Raycast reports false when the ray hits nothing.

type Quat

type Quat struct {
	X float32 `json:"x"`
	Y float32 `json:"y"`
	Z float32 `json:"z"`
	W float32 `json:"w"`
}

Quat is a unit orientation quaternion in (x, y, z, w) order.

type ScreenshotOverlays

type ScreenshotOverlays struct {
	Bounds    bool  `json:"bounds,omitempty"`
	Colliders bool  `json:"colliders,omitempty"`
	Physics   bool  `json:"physics,omitempty"`
	Frusta    bool  `json:"frusta,omitempty"`
	Cameras   bool  `json:"cameras,omitempty"`
	Grid      bool  `json:"grid,omitempty"`
	Axes      bool  `json:"axes,omitempty"`
	Wireframe *bool `json:"wireframe,omitempty"`
}

ScreenshotOverlays configures wireframe debug overlays drawn by game3d_screenshot.

type ScreenshotOverlaysDrawn

type ScreenshotOverlaysDrawn struct {
	Meshes    int `json:"meshes,omitempty"`
	Bounds    int `json:"bounds,omitempty"`
	Colliders int `json:"colliders,omitempty"`
	Frusta    int `json:"frusta,omitempty"`
	Grid      int `json:"grid,omitempty"`
	Axes      int `json:"axes,omitempty"`
	Lines     int `json:"lines,omitempty"`
}

ScreenshotOverlaysDrawn counts wireframe primitives projected onto a game3d_screenshot image.

type ScreenshotResult

type ScreenshotResult struct {
	Width         int                     `json:"width"`
	Height        int                     `json:"height"`
	Format        string                  `json:"format"`
	Path          string                  `json:"path,omitempty"`
	Bytes         int                     `json:"bytes"`
	PNGBase64     string                  `json:"png_base64,omitempty"`
	OverlaysDrawn ScreenshotOverlaysDrawn `json:"overlays_drawn"`
}

ScreenshotResult is the JSON response returned by game3d_screenshot.

type Socket

type Socket struct {
	Name          string   `json:"name"`
	Path          string   `json:"path,omitempty"`
	LocalPosition Vec3     `json:"localPosition"`
	WorldPosition Vec3     `json:"worldPosition"`
	Attached      []string `json:"attached,omitempty"`
}

Socket describes one named attachment socket on a 3D scene node.

type Transform

type Transform struct {
	Position Vec3 `json:"position"`
	Rotation Quat `json:"rotation"`
	Scale    Vec3 `json:"scale"`
}

Transform describes a position, orientation, and scale in 3D space.

type Vec3

type Vec3 struct {
	X float32 `json:"x"`
	Y float32 `json:"y"`
	Z float32 `json:"z"`
}

Vec3 is a position, direction or scale in world space.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL