Editor/GolfCourseSetupTool.cs
using Sandbox;
using Editor;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// "Set up course": a Scene toolbar button (next to the Course Wall Builder) that makes the open scene
/// ready for the game in one go. It removes every Camera Component that is not on a Golf Menu
/// Camera (the map template's Main Camera, which otherwise fights the game's own camera), adds a
/// Golf Course Info object when there is none, a Sun (Directional Light with an Ambient Light) and a
/// 2D Sky when the scene has none, and a Golf Menu Camera from the kit prefab when there is none.
/// It never removes anything else: an object whose camera went stays where it is. Every action is
/// written to the console and shown in the tool's sidebar, and the whole run is one undo step. It
/// also fills in the project's course metadata (see <see cref="GolfCourseProjectMeta"/>).
/// </summary>
[EditorTool( "golfcoursesetup" )]
[Title( "Set up course" )]
[Icon( "golf_course" )]
public sealed class GolfCourseSetupTool : EditorTool
{
List<string> _actions = new();
Editor.Label _report;
public override void OnEnabled()
{
_actions = GolfCourseSetup.Run( SceneEditorSession.Active );
}
public override Widget CreateToolSidebar()
{
var sidebar = new ToolSidebarWidget();
sidebar.AddTitle( "Set up course", "golf_course" );
sidebar.MinimumWidth = 320;
var what = sidebar.AddGroup( "What it does" );
what.Add( new Editor.Label( "Removes cameras that are not the Golf Menu Camera or the kit's Preview Camera (the map template's Main Camera).\nAdds a Golf Course Info, a Sun with ambient light, a 2D Sky and a Golf Menu Camera when the scene has none.\nAdds the kit's template hole when the scene has no hole.\nKeeps the project an addon with no parent game while you edit, and notes the primary scene; Golf Kit > Publish course.. publishes the course scene as a map package of the game.\nNothing else is removed; one undo step." ) );
var run = sidebar.AddGroup( "Run" );
var button = new Editor.Button( "Set up course again", "golf_course" );
button.Clicked = () => _actions = GolfCourseSetup.Run( SceneEditorSession.Active );
run.Add( button );
var done = sidebar.AddGroup( "This run" );
_report = new Editor.Label( Report() );
_report.WordWrap = true;
done.Add( _report );
return sidebar;
}
public override void OnUpdate()
{
if ( _report.IsValid() ) _report.Text = Report();
}
string Report() => _actions.Count == 0 ? "Nothing to do: the scene already has everything." : string.Join( "\n", _actions.Select( a => "- " + a ) );
}
/// <summary>The work behind the Set up course button, usable on any scene with an editor session.</summary>
public static class GolfCourseSetup
{
public const string MenuCameraPrefab = "prefabs/menu_camera.prefab";
public const string HoleTemplatePrefab = "prefabs/holekit/hole_template.prefab";
public const string SkyMaterialPath = "materials/skybox/skybox_sunrise_01.vmat";
/// <summary>Runs the set-up on the session's scene; returns what was done, each line also logged.</summary>
public static List<string> Run( SceneEditorSession session )
{
var actions = new List<string>();
var scene = session?.Scene;
if ( scene is null )
{
Log.Warning( "Golf Kit: Set up course needs an open scene" );
return actions;
}
using var sceneScope = scene.Push();
// Cameras first, so the undo scope knows which components go.
var extraCameras = scene.GetAllComponents<CameraComponent>()
.Concat( scene.GetAllObjects( true ).Select( o => o.GetComponent<CameraComponent>( true ) ) )
.Where( c => c.IsValid() && c.GameObject.GetComponent<GolfMenuCamera>( true ) is null && c.GameObject.GetComponent<GolfPreviewCamera>( true ) is null && !IsEditorObject( c.GameObject ) )
.Distinct()
.ToList();
using var undo = session.UndoScope( "Set up course" ).WithGameObjectCreations().WithComponentCreations().WithComponentDestructions( extraCameras ).Push();
foreach ( var camera in extraCameras )
{
var name = camera.GameObject.Name;
camera.Destroy();
Say( actions, $"Camera Component removed from \"{name}\" (the object itself stays; the game brings its own camera)" );
}
if ( !scene.GetAllComponents<GolfCourseInfo>().Any() && !scene.GetAllObjects( true ).Any( o => o.GetComponent<GolfCourseInfo>( true ) is not null ) )
{
var go = new GameObject( true, "Course Info" );
var info = go.AddComponent<GolfCourseInfo>();
info.CourseName = CourseName( scene );
Say( actions, $"Golf Course Info added (\"{info.CourseName}\"; set the name, wall style and ambience on it)" );
}
if ( !scene.GetAllComponents<DirectionalLight>().Any() )
{
var go = new GameObject( true, "Sun" );
go.WorldRotation = Rotation.From( 50f, 40f, 0f );
var sun = go.AddComponent<DirectionalLight>();
sun.LightColor = new Color( 0.91f, 0.98f, 1f );
sun.Shadows = true;
sun.SkyColor = Color.Transparent;
Say( actions, "Sun added (Directional Light with shadows)" );
}
if ( !scene.GetAllComponents<AmbientLight>().Any() )
{
var host = scene.GetAllComponents<DirectionalLight>().FirstOrDefault()?.GameObject;
var go = host.IsValid() ? host : new GameObject( true, "Ambient Light" );
var ambient = go.AddComponent<AmbientLight>();
ambient.Color = new Color( 0.24f, 0.24f, 0.24f );
Say( actions, $"Ambient Light added on \"{go.Name}\"" );
}
if ( !scene.GetAllComponents<SkyBox2D>().Any() )
{
var go = new GameObject( true, "Sky" );
var sky = go.AddComponent<SkyBox2D>();
var material = Material.Load( SkyMaterialPath );
if ( material is not null && !material.IsError ) sky.SkyMaterial = material;
Say( actions, $"2D Sky added ({( sky.SkyMaterial is null ? "default material" : SkyMaterialPath )})" );
}
if ( !scene.GetAllComponents<GolfMenuCamera>().Any() && !scene.GetAllObjects( true ).Any( o => o.GetComponent<GolfMenuCamera>( true ) is not null ) )
{
var transform = MenuCameraTransform( scene );
var go = GameObject.Clone( MenuCameraPrefab, transform, null, true, "Menu Camera" );
if ( go.IsValid() && go.GetComponent<GolfMenuCamera>( true ) is not null )
{
Say( actions, $"Golf Menu Camera added from {MenuCameraPrefab} at {transform.Position:0} looking at the course (move it where the menu should look; add a child named End to pan)" );
}
else
{
if ( go.IsValid() ) go.Destroy();
var made = new GameObject( true, "Menu Camera" );
made.WorldTransform = transform;
made.AddComponent<GolfMenuCamera>();
Say( actions, $"Golf Menu Camera added (the prefab {MenuCameraPrefab} was not found, so a plain object with the component)" );
}
}
// No hole at all: the kit's template hole at the origin, so the scene is playable at once.
var hasHole = scene.GetAllComponents<Hole>().Any()
|| scene.GetAllObjects( true ).Any( o => o.GetComponent<Hole>( true ) is not null );
if ( !hasHole )
{
var go = GameObject.Clone( HoleTemplatePrefab, new Transform( Vector3.Zero, Rotation.Identity ), null, true, "Hole 1" );
if ( go.IsValid() )
Say( actions, $"Hole 1 added from {HoleTemplatePrefab} at the origin (a straight par 2 with tee, cup and hedges; edit it or drag more copies for the next holes)" );
else
Say( actions, $"no hole in the scene and {HoleTemplatePrefab} could not be loaded; build a Hole 1 group by hand" );
}
if ( actions.Count == 0 )
Log.Info( "Golf Kit: Set up course found nothing to add or remove" );
// The project side: type, parent game and primary scene, so publishing needs no hand edit.
try
{
GolfCourseProjectMeta.Apply( Project.Current, scene.Source?.ResourcePath, "set up course" );
}
catch ( Exception e )
{
Log.Warning( e, "Golf Kit: the project metadata could not be set" );
}
return actions;
}
/// <summary>
/// The editor's own objects in a scene session (its editor camera and the like) are hidden, not
/// saved or editor-only, and are never touched; nor is anything under such an object.
/// </summary>
static bool IsEditorObject( GameObject go )
{
const GameObjectFlags editorFlags = GameObjectFlags.Hidden | GameObjectFlags.NotSaved | GameObjectFlags.EditorOnly;
for ( var o = go; o.IsValid(); o = o.Parent )
{
if ( o == o.Scene ) break;
if ( (o.Flags & editorFlags) != 0 ) return true;
if ( string.Equals( o.Name, "editor_camera", StringComparison.OrdinalIgnoreCase ) ) return true;
}
return false;
}
/// <summary>"Hole 1", "hole 12": a hole group by name, as the game finds them.</summary>
static bool IsHoleGroupName( string name )
{
if ( string.IsNullOrWhiteSpace( name ) ) return false;
var trimmed = name.Trim();
if ( !trimmed.StartsWith( "Hole ", StringComparison.OrdinalIgnoreCase ) ) return false;
return trimmed.Length > 5 && trimmed.Substring( 5 ).Trim().All( char.IsDigit );
}
static void Say( List<string> actions, string line )
{
actions.Add( line );
Log.Info( "Golf Kit: Set up course: " + line );
}
static string CourseName( Scene scene )
{
var title = Project.Current?.Config?.Title;
if ( !string.IsNullOrWhiteSpace( title ) ) return title;
var name = scene.Source?.ResourceName ?? scene.Name;
return string.IsNullOrWhiteSpace( name ) ? "My Course" : name;
}
/// <summary>
/// Somewhere sensible for a new menu camera: back from the first hole's tee looking across the
/// hole, else above and beside everything with a renderer looking at its middle, else a default spot.
/// </summary>
static Transform MenuCameraTransform( Scene scene )
{
var hole = scene.GetAllComponents<Hole>().FirstOrDefault();
if ( hole.IsValid() )
{
var cup = hole.CupPosition;
var tee = hole.TeePosition;
var along = (tee - cup).WithZ( 0f );
var dir = along.IsNearlyZero() ? Vector3.Forward : along.Normal;
var position = tee + dir * 220f + Vector3.Up * 140f;
var look = (cup + tee) * 0.5f;
return new Transform( position, Rotation.LookAt( (look - position).Normal, Vector3.Up ) );
}
var renderers = scene.GetAllComponents<ModelRenderer>().Where( r => r.IsValid() ).ToList();
if ( renderers.Count > 0 )
{
var bounds = renderers[0].Bounds;
foreach ( var r in renderers.Skip( 1 ) ) bounds = bounds.AddBBox( r.Bounds );
var span = MathF.Max( 200f, bounds.Size.Length );
var position = bounds.Center + new Vector3( -0.6f, -0.6f, 0.45f ) * span;
return new Transform( position, Rotation.LookAt( (bounds.Center - position).Normal, Vector3.Up ) );
}
return new Transform( new Vector3( -300f, -300f, 200f ), Rotation.LookAt( new Vector3( 1f, 1f, -0.5f ).Normal, Vector3.Up ) );
}
}