Skip to content

Game.Objects.ObjectUtils

Assembly: Assembly-CSharp
Namespace: Game.Objects

Type: static class

Base: none

Summary: ObjectUtils is a large collection of static helper routines used by the game for working with placeable objects, props, trees and characters. It provides geometry and bounds calculations, transform helpers (local/world conversions), collision mask resolution, economic cost/refund calculations, tree growth/wood calculations, animation root-motion utilities, placement/terrain sampling helpers and a variety of small utilities used by object placement, animation and simulation systems. These helpers are commonly used by mod code that needs to interact with object geometry, placement, animations or tree/resource logic.


Fields

  • public struct ActivityStartPositionCache
    Contains cached data used when resolving an activity start transform for animated characters/props. Fields:
  • public ActivityType m_ActivityType — cached activity type.
  • public float3 m_PositionOffset — cached local position offset to apply to activity transform.
  • public quaternion m_RotationOffset — cached rotation offset to apply to activity transform.

{{ The struct is used to avoid recomputing root-motion based offsets repeatedly when resolving a repeated activity start position. }}

  • public const float MAX_SPAWN_LOCATION_CONNECTION_DISTANCE
    {{ Value: 32f. Maximum distance used when connecting spawn locations. }}

  • public const float MIN_TREE_WOOD_RESOURCE
    {{ Value: 1f. Minimum wood resource amount considered for trees. }}

  • public const float MAX_TREE_AGE
    {{ Value: 40f. Maximum tree age constant. }}

  • public const float TREE_AGE_PHASE_CHILD
    {{ Value: 0.1f. Age threshold phases used for tree initialization/growth. }}

  • public const float TREE_AGE_PHASE_TEEN
    {{ Value: 0.15f. }}

  • public const float TREE_AGE_PHASE_ADULT
    {{ Value: 0.35f. }}

  • public const float TREE_AGE_PHASE_ELDERLY
    {{ Value: 0.35f. }}

  • public const float TREE_AGE_PHASE_DEAD
    {{ Value: 0.05f. }}

  • public const float TREE_WOOD_GROWTH_CHILD
    {{ Value: 0.2f. Wood growth weight for child phase. }}

  • public const float TREE_WOOD_GROWTH_TEEN
    {{ Value: 0.5f. }}

  • public const float TREE_WOOD_GROWTH_ADULT
    {{ Value: 0.3f. }}

Properties

  • This static class exposes no public properties.

{{ Use the methods directly; there are no instance properties to set or read. }}

Constructors

  • This is a static utility class — there are no public constructors.

Methods

Below are the primary public methods exposed by ObjectUtils. Only the most relevant overloads are listed; see method signatures for parameter details.

  • public static float3 GetSize(Bounds3 bounds)
    Returns a size vector derived from a Bounds3. XZ is the max extent (abs of min/max) * 2, Y is bounds.max.y.

  • public static Bounds3 CalculateBounds(float3 position, quaternion rotation, ObjectGeometryData geometryData)
    Calculates world-space bounds for a prefab given its local geometry data. Handles circular geometry flags specially.

  • public static Bounds3 CalculateBounds(float3 position, quaternion rotation, Bounds3 bounds)
    Transforms an axis-aligned local Bounds3 by a rotation and a translation and returns the world-space Bounds3.

  • public static Bounds3 CalculateBounds(Line3.Segment positionRange, quaternion rotation, Bounds3 bounds)
    Like the above but computes bounds for an object that spans along a segment (used by stacked/stack-range objects).

  • public static Bounds3 GetBounds(ObjectGeometryData geometryData)
    Returns the local Bounds3 for the object geometry; accounts for circular flag by using m_Size.

  • public static Bounds3 GetBounds(Stack stack, ObjectGeometryData geometryData, StackData stackData)
    Returns bounds adjusted for stacking direction/range.

  • public static Bounds3 CalculateBounds(float3 position, quaternion rotation, Stack stack, ObjectGeometryData geometryData, StackData stackData)
    Computes world bounds for stacked objects using stack ranges and geometry flags.

  • public static Quad3 CalculateBaseCorners(float3 position, quaternion rotation, Bounds3 bounds)
    Returns the four bottom corners (base quad) transformed into world space.

  • public static Quad3 CalculateBaseCorners(float3 position, quaternion rotation, float2 size)
    Calculates base corners using a centered size.

  • public static float3 CalculatePointVelocity(float3 offset, Moving moving)
    Computes linear velocity of a point offset from a moving object (v + ω × r).

  • public static float3 CalculateMomentOfInertia(quaternion rotation, float3 size)
    Estimates the moment-of-inertia vector for a box of given size and rotation (used by physics/rigidbody-like systems).

  • public static Transform InverseTransform(Transform transform)
    Returns an inverse-like Transform: position negated, rotation inverted. Useful for parent/child transform math where inverse parent's transform is approximated.

  • public static float3 LocalToWorld(Transform transform, float3 position)
    Transforms a local-space position by a Transform to world-space.

  • public static float3 LocalToWorld(float3 transformPosition, quaternion transformRotation, float3 position)
    Overload that accepts position and quaternion.

  • public static Bezier4x3 LocalToWorld(float3 transformPosition, quaternion transformRotation, Bezier4x3 curve)
    Transforms a bezier curve from local to world by transforming each control point.

  • public static Transform LocalToWorld(Transform transform, float3 position, quaternion rotation)
    Returns a Transform in world-space composed by applying position and rotation relative to a parent Transform.

  • public static InterpolatedTransform LocalToWorld(InterpolatedTransform transform, float3 position, quaternion rotation)
    Same as above for InterpolatedTransform type.

  • public static Transform LocalToWorld(Transform parentTransform, Transform transform)
    Combines parent and child transforms.

  • public static Transform WorldToLocal(Transform inverseParentTransform, Transform transform)
    Converts a world transform into the parent's local space using inverseParentTransform (pre-inverted transform).

  • public static float3 WorldToLocal(Transform inverseParentTransform, float3 position)
    World -> local using pre-inverted parent transform.

  • public static CollisionMask GetCollisionMask(ObjectGeometryData geometryData, Elevation elevation, bool ignoreMarkers)
    Resolves the collision mask (OnGround/Overground/Underground/ExclusiveGround) for an object based on geometry flags and elevation.

  • public static CollisionMask GetCollisionMask(ObjectGeometryData geometryData, bool ignoreMarkers)
    Simpler overload ignoring elevation; mainly resolves ExclusiveGround/BaseCollision flags.

  • public static int GetContructionCost(int constructionCost, Tree tree, in EconomyParameterData economyParameterData)
    Adjusts construction cost for tree state (teen/adult/elderly multipliers loaded from economy parameters).

  • public static int GetRelocationCost(int constructionCost, EconomyParameterData economyParameterData)
    Computes relocation cost using configured relocation cost multiplier and clamping.

  • public static int GetRelocationCost(int constructionCost, Recent recent, uint simulationFrame, EconomyParameterData economyParameterData)
    Considers recent build/refund history to reduce relocation cost.

  • public static int GetRebuildCost(int constructionCost)
    Computes rebuild cost (rounded to nearest 500 with lower/upper clamps).

  • public static int GetRebuildCost(int constructionCost, Recent recent, uint simulationFrame, EconomyParameterData economyParameterData)
    Considers refunds when computing rebuild cost.

  • public static int GetUpgradeCost(int constructionCost, int originalCost)
    Returns upgrade cost as max(0, constructionCost - originalCost).

  • public static int GetUpgradeCost(int constructionCost, int originalCost, Recent recent, uint simulationFrame, EconomyParameterData economyParameterData)
    If new cost is lower than original, will charge negative (refund) using GetRefundAmount.

  • public static int GetRefundAmount(Recent recent, uint simulationFrame, EconomyParameterData economyParameterData)
    Calculates refund amount by checking how recently a modification was made (time ranges and percentages come from economy parameters).

  • public static float CalculateWoodAmount(Tree tree, Plant plant, Damaged damaged, TreeData treeData)
    Returns how much wood you can get from a tree based on its state (growth/stage), pollution and damage.

  • public static float CalculateGrowthRate(Tree tree, Plant plant, TreeData treeData)
    Computes rate of wood growth per simulation tick for trees, modulated by pollution.

  • public static Tree InitializeTreeState(float age)
    Creates/initializes a Tree struct from an age value (0..1 ranges mapped to growth/state bytes).

  • public static void UpdateAnimation(Entity prefab, float timeStep, DynamicBuffer<MeshGroup> meshGroups, ref BufferLookup<SubMeshGroup> subMeshGroupBuffers, ref BufferLookup<CharacterElement> characterElementBuffers, ref BufferLookup<SubMesh> subMeshBuffers, ref BufferLookup<Game.Prefabs.AnimationClip> animationClipBuffers, ref BufferLookup<AnimationMotion> animationMotionBuffers, AnimatedPropID oldPropID, AnimatedPropID newPropID, ActivityCondition conditions, ref float maxSpeed, ref byte activity, ref float3 targetPosition, ref float3 targetDirection, ref Transform transform, ref TransformFrame oldFrameData, ref TransformFrame newFrameData)
    High-level function used to update a character/animated prop's TransformFrame between frames. It queries animation clips, state durations, applies root-motion when required, handles state transitions (Idle, Start, End, Action, Done) and cross-fading. This is a core method for animators/AI that drive animated props/characters.

  • public static Transform GetActivityStartPosition(Entity prefab, DynamicBuffer<MeshGroup> meshGroups, Transform activityTransform, TransformState state, ActivityType activityType, AnimatedPropID propID, ActivityCondition conditions, ref BufferLookup<SubMeshGroup> subMeshGroupBuffers, ref BufferLookup<CharacterElement> characterElementBuffers, ref BufferLookup<SubMesh> subMeshBuffers, ref BufferLookup<Game.Prefabs.AnimationClip> animationClipBuffers, ref BufferLookup<AnimationMotion> animationMotionBuffers, ref ActivityStartPositionCache cache)
    Returns a Transform representing where a character/prop should start an activity. Uses cached root-motion offsets in ActivityStartPositionCache to translate an activity anchor to the correct physical start pose when animations have root offsets.

  • public static float GetTotalDamage(Damaged damaged)
    Sums damage channels and applies a small adjustment; result is clamped to [0,1].

  • public static void UpdateResourcesDamage(Entity entity, float totalDamage, ref BufferLookup<Renter> renterData, ref BufferLookup<Game.Economy.Resources> resourcesData)
    Multiplies non-money resource amounts for renters attached to an entity by (1 - totalDamage). Used when an object is damaged/destroyed to proportionally reduce stored resources (wood, goods, etc).

  • public static Transform AdjustPosition(Transform transform, ref Elevation elevation, Entity prefab, out bool angledSample, ref TerrainHeightData terrainHeightData, ref WaterSurfaceData waterSurfaceData, ref ComponentLookup<PlaceableObjectData> placeableObjectDatas, ref ComponentLookup<ObjectGeometryData> objectGeometryDatas)
    Samples terrain and water to adjust a prefab's Transform before placement. Handles placement flags (Hovering, Shoreline, Floating), object geometry flags (Standing, HasBase) and computes angled placement (samples corner heights and creates an aligned rotation when needed). Returns adjusted transform and modifies elevation (adds floating offset). angledSample indicates whether terrain sampling used angled corner-sample logic.

  • public static int GetSubParentMesh(ElevationFlags elevationFlags)
    Returns special sub-parent mesh indices for certain elevation flag combinations:

  • OnGround => -2
  • Stacked => 1000
  • Stacked | OnGround => -1001
  • otherwise 0

  • public static float GetTerrainSmoothingWidth(ObjectGeometryData objectGeometryData)
    Computes smoothing width from the object's bounds size.

  • public static float GetTerrainSmoothingWidth(float2 size)
    Computes smoothing width as max(8, length(size) / 12).

  • public static uint GetRemainingConstructionFrames(UnderConstruction underConstruction)
    Returns remaining frames to finish construction given progress and speed (used for animation/timers).

  • public static uint GetTripDelayFrames(UnderConstruction underConstruction, PathInformation pathInformation)
    Returns delay frames for a trip given remaining construction frames and path duration; clamps to zero when the path duration exceeds remaining construction frames.

  • public static bool GetStandingLegCount(ObjectGeometryData objectGeometryData, out int legCount)
    Determines whether an object has standing legs and computes how many (1 or 2) based on m_LegOffset and GeometryFlags. Returns true if object is standing.

  • public static float3 GetStandingLegPosition(ObjectGeometryData objectGeometryData, Transform transform, int legIndex)
    Returns world position for a standing-leg given index (0/1), by applying transform and leg offset.

  • public static float3 GetStandingLegOffset(ObjectGeometryData objectGeometryData, int legIndex)
    Returns local offset for a standing-leg (xz vector).

Private/internal animation helpers (listed for completeness; these are private in the source but are critical to how animation logic works):

  • private static byte GetParentActivity(byte activity)
    Small helper used to find a "parent" activity type for some activities (e.g., maps activity 6 => 5).

  • private static void ApplyRootMotion(ref Transform transform, ref TransformFrame newFrameData, DynamicBuffer<AnimationMotion> motions, Game.Rendering.BlendWeights weights, int2 motionRange, float3 deltaRange)
    Applies root motion computed from animation motions to current transform and frame velocities.

  • private static void ApplyRootMotion(ref Transform transform, ref float3 targetPosition, ref float3 targetDirection, float3 rootOffset, quaternion rootRotation)
    Applies a provided root offset/rotation to transform and target information.

  • private static float GetStateDuration(Entity prefab, TransformState state, byte activity, AnimatedPropID propID, ActivityCondition conditions, DynamicBuffer<MeshGroup> meshGroups, ref BufferLookup<SubMeshGroup> subMeshGroupBuffers, ref BufferLookup<CharacterElement> characterElementBuffers, ref BufferLookup<SubMesh> subMeshBuffers, ref BufferLookup<Game.Prefabs.AnimationClip> animationClipBuffers, out CharacterElement characterElement, out Game.Prefabs.AnimationClip animationClip, out bool crossFade)
    Searches animation clip buffers across character elements/submeshes to determine the longest matching animation length for a given state/activity/prop combination and returns that duration. Also outputs matched character element and animation clip and whether crossfade data is available.

  • public static void GetRootMotion(DynamicBuffer<AnimationMotion> motions, int2 range, Game.Rendering.BlendWeights weights, float t, out float3 rootOffset, out float3 rootVelocity, out quaternion rootRotation)
    Computes blended root offset/velocity/rotation at time t for an animation that may be blended between submeshes/weights.

  • private static void GetRootMotion(AnimationMotion motion, float t, out float3 rootOffset, out float3 rootVelocity, out quaternion rootRotation)
    Extracts root motion from a single AnimationMotion using a simple bezier/tangent/slerp approximation.

{{ Remarks: Many of the animation methods depend on buffer lookups (BufferLookup), DynamicBuffer structures and entity prefab component data. Use these from within ECS systems or when you have the correct World/EntityManager context. }}

Usage Example

// Example: Calculate world bounds and adjust placement for a prefab before placing it

Entity prefab = /* your prefab entity */;
ObjectGeometryData geometry = objectGeometryDatas[prefab]; // obtained from ComponentLookup<ObjectGeometryData>
Transform initialTransform = new Transform { m_Position = new float3(100, 0, 200), m_Rotation = quaternion.identity };

// 1) Compute world bounds for default orientation
Bounds3 worldBounds = ObjectUtils.CalculateBounds(initialTransform.m_Position, initialTransform.m_Rotation, geometry);

// 2) Adjust transform to terrain/water with placement rules
Elevation elevation = new Elevation { m_Elevation = 0f, m_Flags = 0 };
bool angledSample;
Transform adjusted = ObjectUtils.AdjustPosition(initialTransform, ref elevation, prefab, out angledSample,
    ref terrainHeightData, ref waterSurfaceData, ref placeableObjectDatas, ref objectGeometryDatas);

// 3) Get base corners (useful for snapping or placement visualization)
Quad3 baseQuad = ObjectUtils.CalculateBaseCorners(adjusted.m_Position, adjusted.m_Rotation, geometry.m_Bounds);

{{ YOUR_INFO }} - Tips for modders: - Use AdjustPosition when placing objects to match the game's built-in terrain & water handling (floating, shoreline, hovering). - Use GetActivityStartPosition and UpdateAnimation when implementing custom AI/interaction that must respect root-motion and activity start offsets. - Tree-related helpers (InitializeTreeState, CalculateWoodAmount) are useful if you add custom tree spawning or harvesting logic. - Many animation methods depend on ECS buffer access (BufferLookup, DynamicBuffer). Ensure you run in the correct World/System and have queried buffers before calling these helpers.