Networked appearance component for the roleplay framework. Syncs model, material, skin, bodygroups, tint, nodraw, outfit and avatar JSON from the host, then applies them to the object's main ModelRenderer and Dresser, retrying when content is still mounting.
using System;
using System.Collections.Generic;
using System.Linq;
namespace RoleplayFramework.Scripting;
/// <summary>
/// Networked look of an entity or player, set from Lua (<c>SetModel</c>, <c>SetMaterial</c>, <c>SetSkin</c>,
/// <c>SetBodygroup</c>, <c>SetNoDraw</c>). The host writes the values; every machine applies them to the object's main
/// renderer. Content that isn't there yet on a client (a package still mounting) is retried until it loads.
/// Empty values mean "leave as authored".
/// </summary>
public sealed class RpAppearance : Component
{
[Sync( SyncFlags.FromHost )] public string ModelPath { get; set; } = "";
[Sync( SyncFlags.FromHost )] public string MaterialPath { get; set; } = "";
[Sync( SyncFlags.FromHost )] public int Skin { get; set; }
[Sync( SyncFlags.FromHost )] public string BodyGroups { get; set; } = ""; // "name=value;name2=value2"
[Sync( SyncFlags.FromHost )] public bool NoDraw { get; set; }
[Sync( SyncFlags.FromHost )] public Color Tint { get; set; } = Color.White;
/// <summary>
/// Player clothing: "" = the player's own Steam avatar outfit; otherwise "path[@tint];path[@tint]..." (may be "-" for
/// "nothing", i.e. underwear). Applied by every machine through the player's <see cref="Dresser"/>.
/// </summary>
[Sync( SyncFlags.FromHost )] public string Outfit { get; set; } = "";
/// <summary>Skin tone 0-1 (light to dark), or -1 for the outfit's/avatar's own.</summary>
[Sync( SyncFlags.FromHost )] public float SkinTone { get; set; } = -1;
/// <summary>Body height 0-1, or -1 for the default.</summary>
[Sync( SyncFlags.FromHost )] public float BodyHeight { get; set; } = -1;
/// <summary>
/// The owner's s&box avatar outfit as the host verified it (serialized ClothingContainer). Only the host (or the
/// player themself) may check what a player owns, so clients don't read other players' avatars themselves: they
/// wear what the host sends here.
/// </summary>
[Sync( SyncFlags.FromHost )] public string AvatarJson { get; set; } = "";
string _model, _material, _bodyGroups;
int _skin = -1;
bool? _noDraw;
Color? _tint;
string _dress;
int _outfitTries;
RealTimeSince _lastAttempt = 10; // first apply happens right away
Model _defaultModel;
/// <summary>The renderer the look applies to: the first one that isn't clothing bone-merged onto another.</summary>
public ModelRenderer MainRenderer =>
Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants )
.FirstOrDefault( r => r is not SkinnedModelRenderer s || s.BoneMergeTarget is null );
/// <summary>Gets or adds the component. When added to an already networked object, the host re-sends that object.</summary>
public static RpAppearance Ensure( GameObject go )
{
var a = go.Components.Get<RpAppearance>();
if ( a is not null ) return a;
a = go.Components.Create<RpAppearance>();
if ( go.Network.Active && Networking.IsHost ) go.Network.Refresh();
return a;
}
protected override void OnUpdate()
{
// Host: read and verify the owner's avatar once (a body may get its owner a moment after it spawned).
if ( Networking.IsHost && string.IsNullOrEmpty( AvatarJson ) && GameObject.Network.Owner is { } owner )
{
try { AvatarJson = ClothingContainer.CreateFromConnection( owner, true ).Serialize(); }
catch ( Exception e ) { Diagnostics.RpLog.Warn( "players", $"Could not read {owner.DisplayName}'s avatar: {e.Message}" ); AvatarJson = "{}"; }
}
if ( ModelPath == _model && MaterialPath == _material && Skin == _skin && BodyGroups == _bodyGroups && NoDraw == _noDraw && Tint == _tint && DressKey == _dress ) return;
if ( _lastAttempt < 0.5f ) return; // missing content: retry twice a second, not every frame
_lastAttempt = 0;
Apply();
}
void Apply()
{
var r = MainRenderer;
if ( r is null ) { Trace( "no renderer yet" ); return; }
_defaultModel ??= r.Model;
if ( ModelPath != _model )
{
if ( string.IsNullOrEmpty( ModelPath ) )
{
if ( _defaultModel is not null ) r.Model = _defaultModel;
SetDresser( true );
_model = ModelPath;
}
else
{
var m = Model.Load( ModelPath );
if ( m is null || m.IsError ) { Trace( $"model {ModelPath} not loaded yet" ); return; } // not mounted here yet; try again
r.Model = m;
// Compare by path: on a client the default model and Model.Load's result can be different objects.
SetDresser( IsCitizen( m ) );
_model = ModelPath;
_skin = -1; _bodyGroups = null; _material = null; _tint = null; // re-apply for the new model
}
}
if ( MaterialPath != _material )
{
if ( string.IsNullOrEmpty( MaterialPath ) ) r.MaterialOverride = null;
else
{
var mat = Material.Load( MaterialPath );
if ( mat is null ) return;
r.MaterialOverride = mat;
}
_material = MaterialPath;
}
if ( Skin != _skin )
{
var model = r.Model;
r.MaterialGroup = model is not null && Skin > 0 && Skin < model.MaterialGroupCount ? model.GetMaterialGroupName( Skin ) : null;
_skin = Skin;
}
if ( BodyGroups != _bodyGroups )
{
foreach ( var part in (BodyGroups ?? "").Split( ';', StringSplitOptions.RemoveEmptyEntries ) )
{
int eq = part.IndexOf( '=' );
if ( eq > 0 && int.TryParse( part.Substring( eq + 1 ), out var v ) ) r.SetBodyGroup( part.Substring( 0, eq ), v );
}
_bodyGroups = BodyGroups;
}
if ( Tint != _tint )
{
if ( Components.Get<LuaEntity>() is null ) r.Tint = Tint; // entities keep LuaEntity.Tint (ent:SetColor)
_tint = Tint;
}
if ( DressKey != _dress ) ApplyOutfit();
if ( NoDraw != _noDraw )
{
foreach ( var mr in Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) ) mr.Enabled = !NoDraw;
_noDraw = NoDraw;
}
}
// The owner is part of the key: a client may learn who owns a body after it first sees it.
/// <summary>Clothing fits this model: the body's original model, or the citizen/human models clothing is made for.</summary>
bool IsCitizen( Model m )
{
var path = m?.ResourcePath ?? "";
if ( _defaultModel is not null && string.Equals( path, _defaultModel.ResourcePath, StringComparison.OrdinalIgnoreCase ) ) return true;
return path.StartsWith( "models/citizen", StringComparison.OrdinalIgnoreCase );
}
string DressKey => $"{Outfit}|{SkinTone}|{BodyHeight}|{_model}|{GameObject.Network.OwnerId}|{AvatarJson?.Length}|{AvatarJson?.GetHashCode()}";
/// <summary>Parses <see cref="Outfit"/> into clothing entries; unknown items are skipped (they may still be mounting).</summary>
public static System.Collections.Generic.List<ClothingContainer.ClothingEntry> ParseOutfit( string outfit, out int missing )
{
missing = 0;
var list = new System.Collections.Generic.List<ClothingContainer.ClothingEntry>();
foreach ( var part in (outfit ?? "").Split( ';', StringSplitOptions.RemoveEmptyEntries ) )
{
if ( part == "-" ) continue;
var at = part.IndexOf( '@' );
var path = at > 0 ? part.Substring( 0, at ) : part;
var clothing = ResourceLibrary.Get<Clothing>( path );
if ( clothing is null ) { missing++; continue; }
var entry = new ClothingContainer.ClothingEntry( clothing );
if ( at > 0 && float.TryParse( part.Substring( at + 1 ), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var t ) )
entry.Tint = Math.Clamp( t, 0f, 1f );
list.Add( entry );
}
return list;
}
/// <summary>
/// The outfit the player picked in the s&box menu: the owning connection's avatar (every machine knows every
/// connection's avatar), or this machine's own avatar when offline.
/// </summary>
ClothingContainer OwnAvatar()
{
// What the host verified and sent (works for every player on every machine).
if ( !string.IsNullOrEmpty( AvatarJson ) && AvatarJson != "{}" )
{
try { return ClothingContainer.CreateFromJson( AvatarJson ); }
catch ( Exception ) { }
}
// Until it arrives: the local player may read their own avatar; offline it is this machine's user.
var owner = GameObject.Network.Owner;
if ( owner is not null && owner == Connection.Local ) return ClothingContainer.CreateFromConnection( owner, true );
if ( !Networking.IsActive ) return ClothingContainer.CreateFromLocalUser();
return new ClothingContainer();
}
void ApplyOutfit()
{
var dresser = Components.Get<Dresser>( FindMode.EverythingInSelfAndDescendants );
if ( dresser is null || !dresser.Enabled ) { Trace( dresser is null ? "no dresser" : "dresser disabled" ); _dress = DressKey; return; } // no dresser, or a non-citizen model
List<ClothingContainer.ClothingEntry> entries;
float tint, height;
if ( string.IsNullOrEmpty( Outfit ) )
{
// Own avatar. Dressed explicitly: the Dresser's OwnerConnection mode doesn't dress bodies that were spawned
// before they got their owner (all of ours).
var avatar = OwnAvatar();
entries = avatar.Clothing.ToList();
tint = avatar.Tint;
height = avatar.Height;
}
else
{
entries = ParseOutfit( Outfit, out var missing );
// A clothing package may still be mounting: retry (twice a second) for a few seconds, then dress without it.
if ( missing > 0 && ++_outfitTries < 10 ) return;
// Forced outfits keep the player's own skin tone and height unless Lua sets them.
var avatar = OwnAvatar();
tint = avatar.Tint;
height = avatar.Height;
// The avatar's skin (body) item stays, so the face/body matches the player's choice.
foreach ( var skin in avatar.Clothing.Where( c => c.Clothing?.Category == Clothing.ClothingCategory.Skin ) )
if ( !entries.Any( e => e.Clothing?.Category == Clothing.ClothingCategory.Skin ) ) entries.Insert( 0, skin );
}
dresser.Source = Dresser.ClothingSource.Manual;
dresser.Clothing = entries;
dresser.ManualTint = SkinTone >= 0 ? Math.Clamp( SkinTone, 0f, 1f ) : tint;
dresser.ManualHeight = BodyHeight >= 0 ? Math.Clamp( BodyHeight, 0f, 1f ) : height;
_ = dresser.Apply();
_dress = DressKey;
_outfitTries = 0;
Diagnostics.RpLog.Info( "players", $"Dressed {GameObject.Name}: {entries.Count} item(s) ({(string.IsNullOrEmpty( Outfit ) ? (string.IsNullOrEmpty( AvatarJson ) ? "own avatar, local" : "own avatar, from host") : "outfit")})" );
}
/// <summary>Player clothing only fits the default citizen: take it off for other models, put it back after.</summary>
void SetDresser( bool on )
{
var dresser = Components.Get<Dresser>( FindMode.EverythingInSelfAndDescendants );
if ( dresser is null || dresser.Enabled == on ) return;
if ( !on ) dresser.Clear();
dresser.Enabled = on;
if ( on ) _ = dresser.Apply();
}
string _lastTrace;
/// <summary>Logs why a look couldn't be applied (once per reason), so "a player has no clothes" is diagnosable.</summary>
void Trace( string why )
{
if ( why == _lastTrace ) return;
_lastTrace = why;
Diagnostics.RpLog.Info( "players", $"{GameObject.Name}: look not applied yet ({why})" );
}
public int GetBodyGroup( string name )
{
foreach ( var part in (BodyGroups ?? "").Split( ';', StringSplitOptions.RemoveEmptyEntries ) )
{
int eq = part.IndexOf( '=' );
if ( eq > 0 && part.Substring( 0, eq ) == name && int.TryParse( part.Substring( eq + 1 ), out var v ) ) return v;
}
return MainRenderer?.GetBodyGroup( name ) ?? 0;
}
public void SetBodyGroup( string name, int value )
{
var parts = (BodyGroups ?? "").Split( ';', StringSplitOptions.RemoveEmptyEntries ).Where( p => !p.StartsWith( name + "=" ) ).ToList();
parts.Add( $"{name}={value}" );
BodyGroups = string.Join( ";", parts );
}
}