VR-Engage  2.3
Loading...
Searching...
No Matches
Frontend Attributes

VR-Engage uses DtAttribute to share values among frontend systems. Attributes form one process-local hierarchy: application services, state for each Player Station, and reflected entity state all have different branches and lifetimes. An attribute holds a current value that can be read or observed for changes. Use messages for discrete events and cross-process commands; ordinary attributes do not synchronize between processes.

The common API is defined in vreUtil/attribute.h, vreUtil/attributeHandle.h, and vreUtil/attributeCallback.h. The examples below apply to a writable application or player branch. Reflected entity values are populated by the network connector; consumers should not write them.

Select a scope

  • Root (DtAttribute::Root())
    • App (appAttributeStore())
      • Players
        • <entityId>
          • <stationName> (playerAttributeStore())
            • Ownship — alias of this entity under Root.Entities
    • Entities (entityStateStore())
      • <ownship entity ID> — target of the Player Station's Ownship alias
      • <other entity ID or UUID> — another reflected entity
Scope Entry point Ownership
Application DtPlayerStationApp::appAttributeStore() Producers publish application-wide frontend state.
Player Station DtPlayerComponent::playerAttributeStore() The station owns this branch.
Reflected entity DtPlayerStationApp::entityStateStore() The connector populates requested state.

The corresponding canonical paths are Root.App, Root.App.Players.<entityId>.<stationName>, and Root.Entities. DtPlayerStation::playerAttributeStore() also returns the player branch. The station marks its branch non-persistent on destruction. Remote entity nodes are normally non-persistent: consumers must retain an interest handle or callback. See Player attribute store for station-specific publishing, role initialization, and lifecycle guidance.

App.Entities is an alias of Root.Entities, not its canonical parent. The Ownship child of a player's branch aliases that player's entity under Root.Entities; DtPlayerStation::ownshipState() and DtPlayerComponent::ownshipState() provide direct access. See Reflected Entity Attributes for subscription timing, ownship lifetime, and the available entity fields.

Work with paths and handles

DtAttribute::Root() returns a DtAttributeHandle. Indexing a handle with ["child"] accesses a child; a dot separates path segments, so store["engine.temperature"] and store["engine"]["temperature"] resolve the same node. store->attribute("engine.temperature") is another way to obtain its handle. Attribute paths are not file paths: engine/temperature names a different, single child. Use stable names and the exact value type agreed on by producers and consumers.

Use the maintained producer/consumer examples below to establish each path's owner and value type.

Lookup creates nodes, including lookups made only to read a value. A newly created node does not necessarily have a value. handle.assigned() means that the handle refers to a node; handle->isSet() means the node has a value. store->hasAttribute("engine.temperature") tests whether a node already exists without creating it, but does not tell you whether that node has a value. Prefer isSet() when the distinction matters.

Keep a handle as a member when accessing a path frequently: the path is resolved when the handle is created, not on every subsequent value read. The untyped DtAttributeHandle exposes the node API through ->. A DtAttributeHandleType<T> constructed from an untyped handle also supports ->get(), assignment from a T, and conversion to a T. It checks type compatibility when assigned to a node with an established value; future reads and writes must still use the same type. There is no handle.as<T>() conversion method.

// Source: examples/playerStateAttribute/sampleComponent.cxx, initialize() excerpt
myGearAttributeHandle = playerAttributeStore()["set-gear"];

The complete method calls base initialization first. sampleComponent.h declares the retained member. It reads the gear published by the configured vehicle components; lookup alone does not publish a value.

store->first() returns a handle to its first child; child.next() advances that handle through its siblings. store->forEach(...) visits each immediate child. Use parent(), name(), and path() for inspection. An alias resolves to the same underlying node, but parent() and path() report its original location; isAlias() and aliasName() identify an alias lookup.

Read and write values

// Source: examples/qmlHud/driverQmlHudComponent.cxx, postInitialize() excerpt
myVehicleDamageState = playerAttributeStore()["vehicle-status"];
myVehicleDamageState["mobility-kill"]->set<bool>(false);
myVehicleDamageState["firepower-kill"]->set<bool>(false);

The complete method calls base post-initialization before these writes. The member handle is declared in driverQmlHudComponent.h, which includes vreUtil/attribute.h. Its simulation-state handler later updates these frontend display flags; they are not backend damage commands.

get<T>() returns T() when the value is unset; it does not assert on an unset node. Use isSet() when absence must be distinguished from a valid zero or false value. getOr<T>(fallback) supplies a non-default fallback without setting the node. Reading a node with an established explicit type as the wrong T asserts. A value first written with setFromString() has an implicit string type and may instead be converted on its first typed access. Prefer typed producers and consumers; types must otherwise match exactly, including float versus double or DtString versus std::string.

set<T>(value) returns true for a new or changed value and notifies change callbacks; it returns false if the value was unchanged or the write was blocked by a lock. setIfNot<T>(value) only initializes an unset node. setType<T>() establishes the type and a default-constructed value without issuing a change notification: afterward isSet() is true, so setIfNot() will not initialize it. getAttribute<T>(path), getAttributeOr<T>(path, fallback), and setAttribute<T>(path, value) are corresponding convenience methods on the node: call store->setAttribute(...), not store.setAttribute(...).

previousValue<T>() returns the value before the last change, or T() when no prior value is available. getAsString() and setFromString() provide string representations where supported by the value type; prefer typed access when both sides know the type. unset() makes a node typeless and unset, while unsetRecursive() also unsets its descendants. Unset does not send a change callback; do not use it to signal consumers that a value disappeared.

Observe changes

DtAttributeCallbackManager owns callback objects and their attribute handles. Use a member manager so the connection lasts as long as its consumer; disconnect during shutdown if that object may remain alive after it stops consuming attributes.

// Source: examples/playerStateAttribute/sampleComponent.cxx (excerpts)
{
DtPlayerComponent::postInitialize();
return true;
}
{
DtPlayerComponent::shutdown();
}
virtual bool postInitialize() override
Performs post-initialization after all components are initialized.
virtual void onGearChanged(const DtString &newGear)
Callback invoked when "Ownship.stateProperties.set-gear" changes.
virtual void shutdown() override
Shutdown callback for cleanup.
makVre::DtAttributeHandle myGearAttributeHandle
Handle to the "Ownship.stateProperties.set-gear" player attribute.
Definition sampleComponent.h:155
void connect(DtAttributeHandle attr, OBJECT_T *object, void(OBJECT_T::*method)(const DtAttributeHandle &), bool includeChildren=false, bool invokeNowIfSet=false)
Connects a member function callback for untyped attribute changes.
void disconnectAll()
Removes and destroys all registered callbacks.
DtAttributeCallbackManager myAttributeCallbacks
Member-scope instance of Attribute callback manager.
Definition playerComponent.h:275

The complete example declares onGearChanged(const std::string&) and resolves the handle during initialization. This excerpt preserves the source's base call and cleanup. It does not request immediate callback delivery.

The typed connect<T> overload passes the new value to the callback. Untyped connect passes the changed DtAttributeHandle; its includeChildren argument also observes descendants of the connected node. invokeNowIfSet is optional and defaults to false. Connect after the consumer is ready to handle an immediate notification if requesting invokeNowIfSet.

A callback keeps its node of interest alive. A manager holds one callback per full attribute path: connecting another callback to the same path through that manager replaces the previous one. Use separate managers or explicitly owned DtAttributeChangeCallback / DtAttributeValueCallback<T> objects when multiple connections to the same path are required. Destroying a callback disconnects it. Callbacks run when a changed value is delivered, not merely because a path was looked up; the callback thread and delivery timing are described below.

Read and modify complex values

get<T>() copies its value. For a large value, read<ReturnType, T>(function) lets the function inspect a const reference under a read lock and return a smaller result. modify<T>(function) changes a value in place under a write lock, compares before and after, and notifies callbacks only when different. When the function can determine whether it changed the value, modifyFast<T>(function) takes a boolean-returning function and avoids that comparison. Do not call other methods on the same attribute from inside either modifying function: its value lock is held until the function returns.

The exact template signatures and lock/change-notification behavior are in include/utilities/vreUtil/attribute.h and attribute.inl. Keep the callable's return type consistent with read<ReturnType, T>() or the boolean result expected by modifyFast<T>().

Manage persistence and locks

Persistence controls whether a node remains in the tree without assigned handles, not whether its value is currently set. Nodes are persistent by default and inherit their parent's persistence when created. A non-persistent node is removed after its last interested handle is released. setPersistence() changes one node; setPersistenceRecursive() changes its existing descendants too. The player branch and reflected entity branch have different framework-managed persistence rules: do not override them in consumer components merely to keep data available.

DtAttributeHandle::lock() and recursiveLock() reject writes by ordinary set() calls until the lock is released. They are producer-side guards against accidental writes, not security or general-purpose synchronization primitives. A producer can use exclusiveSet() to temporarily release its handle's lock, write, and reacquire it; another writer can intervene during that interval. Use the shortest practical lock lifetime and do not rely on these APIs to coordinate unrelated threads.

Threading and readiness

Value access uses internal locks, but a thread-safe read does not make an external pointer's lifetime safe or make a sequence of reads atomic. Use read() to inspect a stored object under its read lock. Coordinate consumer lifetime with callback disconnection, especially if another thread publishes values.

Callbacks are associated with registered callback threads. A change made on a registered callback thread can invoke its callbacks immediately; a change made on another thread can be delivered when the registered thread calls DtAttribute::callbackDispatchTick(). VR-Engage registers and dispatches its render and connector threads. Register callbacks on the intended thread and do not assume one invocation per intermediate value when changes are pending. await() blocks until a value or condition becomes available or times out; use it only when another thread can satisfy the condition, not in a per-frame frontend update.

Attributes themselves are process-local. Reflected entity attributes are updated through a connector on the network thread; other attribute branches do not acquire network synchronization merely by using this API.

Application attributes

DtPlayerStationApp::appAttributeStore() returns a handle to Root.App by value; it has a const overload for readers. The application creates this branch in its constructor, before any Player Station is engaged. The App node itself holds a DtPlayerStationApp*, while its children hold application-wide values such as services, UI state, connection state, and configuration shared across roles.

Use the DtPlayerStationApp* passed to a frontend plugin's initialization function, or obtain it from a component's player().app(). Code without either context can use DtPlayerStationApp::instance(), but it throws if called before the application is constructed; do not call it during static initialization. Prefer direct application accessors where they exist rather than retrieving a service pointer from an attribute unnecessarily. Do not bind a non-const reference to the temporary handle returned by appAttributeStore().

The component base reads the application-owned display engine during initialization:

// Source: libsrc/framework/vrePlayerStation/playerComponent.cxx, initialize() excerpt
myDe = player->app()->appAttributeStore()["DtDe"]->get<makVrv::DtDe*>();

The complete method validates this pointer and reports initialization failure when the service is absent. Consumers must not overwrite application-owned service keys.

Existing frontend code uses this branch without needing to know which role is currently engaged:

Path Value type Publisher Consumer
App.currentState std::string DtPlayerStationState DtVreChatManager
App.DtDe makVrv::DtDe* DtPlayerStationApp DtPlayerComponent

The state machine publishes currentState on entry or exposure through appAttributeStore()->setAttribute(...), and the chat manager subscribes through appAttributeStore()["currentState"]. This is an application-wide notification, not a per-role player attribute. The application publishes the display-engine pointer as DtDe; the player-component base reads it during initialization. If a subscriber needs the current value as well as future changes, connect with invokeNowIfSet = true after it is ready to receive the initial callback.

App.vreStatus.local and App.vreStatus.stations are also application-scoped status branches. DtSessionStatusConnector uses local status for status messages and populates remote-station status from received messages. This is an explicit connector bridge, not automatic synchronization of arbitrary application attributes. These status keys are framework-owned; consumers should not overwrite them.

The App branch is not torn down when a player changes roles. Its children are persistent by default; do not assume that destroying a component clears a custom application key. Arrange for a plugin or service to disconnect its observers and clear values it owns during its own shutdown, before destroying objects referenced by those values. A retained attribute handle does not keep a pointed-to service alive. The application sets the App node's DtPlayerStationApp* value to null during destruction; do not use application services after shutdown. Since unset() does not notify change callbacks, publish an explicit final state first if subscribers need to observe it.

Reserve the framework-owned App.Players subtree for Player Stations. App.Entities is an alias of the separate Root.Entities tree, not a place to publish application-owned values. Use a distinct, stable prefix for custom application keys to avoid collisions with framework keys; see Attribute Store Reference to discover existing names.

See also