Merge branch 'master' of https://github.com/FlaxEngine/FlaxEngine into feature/1151-play-mode-actions

This commit is contained in:
envision3d
2023-07-20 02:00:53 -05:00
128 changed files with 1679 additions and 608 deletions

View File

@@ -29,7 +29,7 @@ namespace FlaxEditor.Content
if (asset)
{
var source = Editor.GetShaderSourceCode(asset);
Utilities.Utils.ShowSourceCodeWindow(source, "Shader Source", item.RootWindow.Window);
Utilities.Utils.ShowSourceCodeWindow(source, "Shader Source", item.RootWindow?.Window);
}
return null;
}

View File

@@ -3,7 +3,6 @@
using FlaxEditor.CustomEditors;
using FlaxEditor.Windows;
using FlaxEngine.GUI;
using FlaxEngine;
using DockState = FlaxEditor.GUI.Docking.DockState;
namespace FlaxEditor
@@ -86,8 +85,12 @@ namespace FlaxEditor
if (!FlaxEngine.Scripting.IsTypeFromGameScripts(type))
return;
Editor.Instance.Windows.AddToRestore(this);
if (!Window.IsHidden)
{
Editor.Instance.Windows.AddToRestore(this);
}
Window.Close();
Window.Dispose();
}
/// <summary>

View File

@@ -167,7 +167,7 @@ namespace FlaxEditor.CustomEditors.Dedicated
Presenter.Undo?.AddAction(new MultiUndoAction(actions));
// Build ragdoll
SceneGraph.Actors.AnimatedModelNode.BuildRagdoll(animatedModel, options, ragdoll);
AnimatedModelNode.BuildRagdoll(animatedModel, options, ragdoll);
}
private void OnRebuildBone(Button button)
@@ -191,7 +191,7 @@ namespace FlaxEditor.CustomEditors.Dedicated
}
// Build ragdoll
SceneGraph.Actors.AnimatedModelNode.BuildRagdoll(animatedModel, new AnimatedModelNode.RebuildOptions(), ragdoll, name);
AnimatedModelNode.BuildRagdoll(animatedModel, new AnimatedModelNode.RebuildOptions(), ragdoll, name);
}
private void OnRemoveBone(Button button)

View File

@@ -33,7 +33,12 @@ namespace FlaxEditor.CustomEditors.Editors
[CustomEditor(typeof(Asset)), DefaultEditor]
public class AssetRefEditor : CustomEditor
{
private AssetPicker _picker;
/// <summary>
/// The asset picker used to get a reference to an asset.
/// </summary>
public AssetPicker Picker;
private bool _isRefreshing;
private ScriptType _valueType;
/// <inheritdoc />
@@ -44,7 +49,7 @@ namespace FlaxEditor.CustomEditors.Editors
{
if (HasDifferentTypes)
return;
_picker = layout.Custom<AssetPicker>().CustomControl;
Picker = layout.Custom<AssetPicker>().CustomControl;
_valueType = Values.Type.Type != typeof(object) || Values[0] == null ? Values.Type : TypeUtils.GetObjectType(Values[0]);
var assetType = _valueType;
@@ -66,7 +71,7 @@ namespace FlaxEditor.CustomEditors.Editors
{
// Generic file picker
assetType = ScriptType.Null;
_picker.FileExtension = assetReference.TypeName;
Picker.FileExtension = assetReference.TypeName;
}
else
{
@@ -78,23 +83,25 @@ namespace FlaxEditor.CustomEditors.Editors
}
}
_picker.AssetType = assetType;
_picker.Height = height;
_picker.SelectedItemChanged += OnSelectedItemChanged;
Picker.AssetType = assetType;
Picker.Height = height;
Picker.SelectedItemChanged += OnSelectedItemChanged;
}
private void OnSelectedItemChanged()
{
if (_isRefreshing)
return;
if (typeof(AssetItem).IsAssignableFrom(_valueType.Type))
SetValue(_picker.SelectedItem);
SetValue(Picker.SelectedItem);
else if (_valueType.Type == typeof(Guid))
SetValue(_picker.SelectedID);
SetValue(Picker.SelectedID);
else if (_valueType.Type == typeof(SceneReference))
SetValue(new SceneReference(_picker.SelectedID));
SetValue(new SceneReference(Picker.SelectedID));
else if (_valueType.Type == typeof(string))
SetValue(_picker.SelectedPath);
SetValue(Picker.SelectedPath);
else
SetValue(_picker.SelectedAsset);
SetValue(Picker.SelectedAsset);
}
/// <inheritdoc />
@@ -104,16 +111,18 @@ namespace FlaxEditor.CustomEditors.Editors
if (!HasDifferentValues)
{
_isRefreshing = true;
if (Values[0] is AssetItem assetItem)
_picker.SelectedItem = assetItem;
Picker.SelectedItem = assetItem;
else if (Values[0] is Guid guid)
_picker.SelectedID = guid;
Picker.SelectedID = guid;
else if (Values[0] is SceneReference sceneAsset)
_picker.SelectedItem = Editor.Instance.ContentDatabase.FindAsset(sceneAsset.ID);
Picker.SelectedItem = Editor.Instance.ContentDatabase.FindAsset(sceneAsset.ID);
else if (Values[0] is string path)
_picker.SelectedPath = path;
Picker.SelectedPath = path;
else
_picker.SelectedAsset = Values[0] as Asset;
Picker.SelectedAsset = Values[0] as Asset;
_isRefreshing = false;
}
}
}

View File

@@ -41,7 +41,17 @@ namespace FlaxEditor.CustomEditors.Editors
}
else
{
element.CustomControl.Value = (Color)Values[0];
var value = Values[0];
if (value is Color asColor)
element.CustomControl.Value = asColor;
else if (value is Color32 asColor32)
element.CustomControl.Value = asColor32;
else if (value is Float4 asFloat4)
element.CustomControl.Value = asFloat4;
else if (value is Double4 asDouble4)
element.CustomControl.Value = (Float4)asDouble4;
else if (value is Vector4 asVector4)
element.CustomControl.Value = asVector4;
}
}
}

View File

@@ -1,6 +1,8 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
using FlaxEditor.CustomEditors.Elements;
using FlaxEditor.CustomEditors.GUI;
using FlaxEditor.Scripting;
using FlaxEngine;
namespace FlaxEditor.CustomEditors.Editors
@@ -13,6 +15,11 @@ namespace FlaxEditor.CustomEditors.Editors
{
private GroupElement _group;
private bool _updateName;
private int _entryIndex;
private bool _isRefreshing;
private MaterialBase _material;
private ModelInstanceActor _modelInstance;
private AssetRefEditor _materialEditor;
/// <inheritdoc />
public override void Initialize(LayoutElementsContainer layout)
@@ -21,47 +28,122 @@ namespace FlaxEditor.CustomEditors.Editors
var group = layout.Group("Entry");
_group = group;
if (ParentEditor == null)
return;
var entry = (ModelInstanceEntry)Values[0];
var entryIndex = ParentEditor.ChildrenEditors.IndexOf(this);
var materialLabel = new PropertyNameLabel("Material");
materialLabel.TooltipText = "The mesh surface material used for the rendering.";
if (ParentEditor.ParentEditor?.Values[0] is ModelInstanceActor modelInstance)
{
_entryIndex = entryIndex;
_modelInstance = modelInstance;
var slots = modelInstance.MaterialSlots;
if (entry.Material == slots[entryIndex].Material)
{
// Ensure that entry with default material set is set back to null
modelInstance.SetMaterial(entryIndex, null);
}
_material = modelInstance.GetMaterial(entryIndex);
var defaultValue = GPUDevice.Instance.DefaultMaterial;
if (slots[entryIndex].Material)
{
// Use default value set on asset (eg. Model Asset)
defaultValue = slots[entryIndex].Material;
}
// Create material picker
var materialValue = new CustomValueContainer(new ScriptType(typeof(MaterialBase)), _material, (instance, index) => _material, (instance, index, value) => _material = value as MaterialBase);
var materialEditor = (AssetRefEditor)_group.Property(materialLabel, materialValue);
materialEditor.Values.SetDefaultValue(defaultValue);
materialEditor.RefreshDefaultValue();
materialEditor.Picker.SelectedItemChanged += OnSelectedMaterialChanged;
_materialEditor = materialEditor;
}
base.Initialize(group);
}
private void OnSelectedMaterialChanged()
{
if (_isRefreshing)
return;
_isRefreshing = true;
var slots = _modelInstance.MaterialSlots;
var material = _materialEditor.Picker.SelectedAsset as MaterialBase;
var defaultMaterial = GPUDevice.Instance.DefaultMaterial;
var value = (ModelInstanceEntry)Values[0];
var prevMaterial = value.Material;
if (!material)
{
// Fallback to default material
_materialEditor.Picker.SelectedAsset = defaultMaterial;
value.Material = defaultMaterial;
}
else if (material == slots[_entryIndex].Material)
{
// Asset default material
value.Material = null;
}
else if (material == defaultMaterial && !slots[_entryIndex].Material)
{
// Default material while asset has no set as well
value.Material = null;
}
else
{
// Custom material
value.Material = material;
}
if (prevMaterial != value.Material)
SetValue(value);
_isRefreshing = false;
}
/// <inheritdoc />
protected override void SpawnProperty(LayoutElementsContainer itemLayout, ValueContainer itemValues, ItemInfo item)
{
// Skip material member as it is overridden
if (item.Info.Name == "Material" && _materialEditor != null)
return;
base.SpawnProperty(itemLayout, itemValues, item);
}
/// <inheritdoc />
public override void Refresh()
{
// Update panel title to match material slot name
if (_updateName &&
_group != null &&
ParentEditor?.ParentEditor != null &&
ParentEditor.ParentEditor.Values.Count > 0)
{
var entryIndex = ParentEditor.ChildrenEditors.IndexOf(this);
if (ParentEditor.ParentEditor.Values[0] is StaticModel staticModel)
if (ParentEditor.ParentEditor.Values[0] is ModelInstanceActor modelInstance)
{
var model = staticModel.Model;
if (model && model.IsLoaded)
var slots = modelInstance.MaterialSlots;
if (slots != null && slots.Length > entryIndex)
{
var slots = model.MaterialSlots;
if (slots != null && slots.Length > entryIndex)
{
_group.Panel.HeaderText = "Entry " + slots[entryIndex].Name;
_updateName = false;
}
}
}
else if (ParentEditor.ParentEditor.Values[0] is AnimatedModel animatedModel)
{
var model = animatedModel.SkinnedModel;
if (model && model.IsLoaded)
{
var slots = model.MaterialSlots;
if (slots != null && slots.Length > entryIndex)
{
_group.Panel.HeaderText = "Entry " + slots[entryIndex].Name;
_updateName = false;
}
_updateName = false;
_group.Panel.HeaderText = "Entry " + slots[entryIndex].Name;
}
}
}
// Refresh currently selected material
_material = _modelInstance.GetMaterial(_entryIndex);
base.Refresh();
}
/// <inheritdoc />
protected override void Deinitialize()
{
_material = null;
_modelInstance = null;
_materialEditor = null;
base.Deinitialize();
}
}
}

View File

@@ -390,7 +390,6 @@ namespace FlaxEditor.CustomEditors.Editors
if (addTagDropPanel.IsClosed)
{
Debug.Log("Hit");
nameTextBox.BorderColor = Color.Transparent;
nameTextBox.BorderSelectedColor = FlaxEngine.GUI.Style.Current.BackgroundSelected;
return;

View File

@@ -37,7 +37,8 @@ public class Editor : EditorModule
{
base.Setup(options);
options.ScriptingAPI.SystemReferences.Add("System.Private.Xml");
options.ScriptingAPI.SystemReferences.Add("System.Xml");
options.ScriptingAPI.SystemReferences.Add("System.Xml.ReaderWriter");
options.ScriptingAPI.SystemReferences.Add("System.Text.RegularExpressions");
options.ScriptingAPI.SystemReferences.Add("System.ComponentModel.TypeConverter");
@@ -101,5 +102,7 @@ public class Editor : EditorModule
files.Add(Path.Combine(FolderPath, "Cooker/GameCooker.h"));
files.Add(Path.Combine(FolderPath, "Cooker/PlatformTools.h"));
files.Add(Path.Combine(FolderPath, "Cooker/Steps/CookAssetsStep.h"));
files.Add(Path.Combine(FolderPath, "Utilities/ScreenUtilities.h"));
files.Add(Path.Combine(FolderPath, "Utilities/ViewportIconsRenderer.h"));
}
}

View File

@@ -27,6 +27,17 @@ namespace FlaxEditor.GUI
/// </summary>
public ScriptType Type => _type;
/// <summary>
/// Initializes a new instance of the <see cref="TypeItemView"/> class.
/// </summary>
public TypeItemView()
{
_type = ScriptType.Null;
Name = "<null>";
TooltipText = "Unset value.";
Tag = _type;
}
/// <summary>
/// Initializes a new instance of the <see cref="TypeItemView"/> class.
/// </summary>
@@ -83,6 +94,7 @@ namespace FlaxEditor.GUI
// TODO: use async thread to search types without UI stall
var allTypes = Editor.Instance.CodeEditing.All.Get();
AddItem(new TypeItemView());
for (int i = 0; i < allTypes.Count; i++)
{
var type = allTypes[i];

View File

@@ -178,6 +178,8 @@ namespace FlaxEditor.Gizmo
if (selection[i] is ActorNode actorNode && actorNode.Actor != null)
CollectActors(actorNode.Actor);
}
if (_actors.Count == 0)
return;
// Render selected objects depth
Renderer.DrawSceneDepth(context, task, customDepth, _actors);

View File

@@ -20,7 +20,7 @@ namespace FlaxEditor
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
@@ -44,7 +44,7 @@ namespace FlaxEditor
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{

View File

@@ -112,6 +112,7 @@ public:
{
Version = ::Version(1, 0);
DefaultSceneSpawn = Ray(Vector3::Zero, Vector3::Forward);
DefaultScene = Guid::Empty;
}
/// <summary>

View File

@@ -613,6 +613,28 @@ bool ScriptsBuilderService::Init()
const String targetOutput = Globals::ProjectFolder / TEXT("Binaries") / target / platform / architecture / configuration;
Array<String> files;
FileSystem::DirectoryGetFiles(files, targetOutput, TEXT("*.HotReload.*"), DirectorySearchOption::TopDirectoryOnly);
for (const auto& reference : Editor::Project->References)
{
if (reference.Project->Name == TEXT("Flax"))
continue;
String referenceTarget;
if (reference.Project->EditorTarget.HasChars())
{
referenceTarget = reference.Project->EditorTarget.Get();
}
else if (reference.Project->GameTarget.HasChars())
{
referenceTarget = reference.Project->GameTarget.Get();
}
if (referenceTarget.IsEmpty())
continue;
const String referenceTargetOutput = reference.Project->ProjectFolderPath / TEXT("Binaries") / referenceTarget / platform / architecture / configuration;
FileSystem::DirectoryGetFiles(files, referenceTargetOutput, TEXT("*.HotReload.*"), DirectorySearchOption::TopDirectoryOnly);
}
if (files.HasItems())
LOG(Info, "Removing {0} files from previous Editor run hot-reloads", files.Count());
for (auto& file : files)

View File

@@ -363,7 +363,6 @@ namespace FlaxEditor.Surface.ContextMenu
Profiler.BeginEvent("VisjectCM.RemoveGroup");
if (group.Archetypes.Count == 0)
{
Debug.Log("Remove");
_groups.RemoveAt(i);
group.Dispose();
}

View File

@@ -292,7 +292,6 @@ void FoliageTools::Paint(Foliage* foliage, Span<int32> foliageTypesIndices, cons
{
PROFILE_CPU_NAMED("Place Instances");
Matrix matrix;
FoliageInstance instance;
Quaternion tmp;
Matrix world;

View File

@@ -1538,6 +1538,7 @@ namespace FlaxEditor.Viewport
new ViewFlagOptions(ViewFlags.MotionBlur, "Motion Blur"),
new ViewFlagOptions(ViewFlags.ContactShadows, "Contact Shadows"),
new ViewFlagOptions(ViewFlags.PhysicsDebug, "Physics Debug"),
new ViewFlagOptions(ViewFlags.LightsDebug, "Lights Debug"),
new ViewFlagOptions(ViewFlags.DebugDraw, "Debug Draw"),
};

View File

@@ -3,8 +3,6 @@
using System;
using FlaxEditor.GUI.ContextMenu;
using FlaxEngine;
using FlaxEditor.GUI.Input;
using FlaxEngine.GUI;
using Object = FlaxEngine.Object;
namespace FlaxEditor.Viewport.Previews
@@ -15,11 +13,10 @@ namespace FlaxEditor.Viewport.Previews
/// <seealso cref="AssetPreview" />
public class AnimatedModelPreview : AssetPreview
{
private ContextMenuButton _showNodesButton, _showBoundsButton, _showFloorButton, _showNodesNamesButton;
private bool _showNodes, _showBounds, _showFloor, _showCurrentLOD, _showNodesNames;
private AnimatedModel _previewModel;
private ContextMenuButton _showNodesButton, _showBoundsButton, _showFloorButton, _showNodesNamesButton;
private bool _showNodes, _showBounds, _showFloor, _showNodesNames;
private StaticModel _floorModel;
private ContextMenuButton _showCurrentLODButton;
private bool _playAnimation, _playAnimationOnce;
private float _playSpeed = 1.0f;
@@ -188,8 +185,8 @@ namespace FlaxEditor.Viewport.Previews
{
UseTimeScale = false,
UpdateWhenOffscreen = true,
//_previewModel.BoundsScale = 1000.0f;
UpdateMode = AnimatedModel.AnimationUpdateMode.Manual
BoundsScale = 100.0f,
UpdateMode = AnimatedModel.AnimationUpdateMode.Manual,
};
Task.AddCustomActor(_previewModel);
@@ -207,26 +204,6 @@ namespace FlaxEditor.Viewport.Previews
// Show Floor
_showFloorButton = ViewWidgetShowMenu.AddButton("Floor", button => ShowFloor = !ShowFloor);
_showFloorButton.IndexInParent = 1;
// Show Current LOD
_showCurrentLODButton = ViewWidgetShowMenu.AddButton("Current LOD", button =>
{
_showCurrentLOD = !_showCurrentLOD;
_showCurrentLODButton.Icon = _showCurrentLOD ? Style.Current.CheckBoxTick : SpriteHandle.Invalid;
});
_showCurrentLODButton.IndexInParent = 2;
// Preview LOD
{
var previewLOD = ViewWidgetButtonMenu.AddButton("Preview LOD");
previewLOD.CloseMenuOnClick = false;
var previewLODValue = new IntValueBox(-1, 90, 2, 70.0f, -1, 10, 0.02f)
{
Parent = previewLOD
};
previewLODValue.ValueChanged += () => _previewModel.ForcedLOD = previewLODValue.Value;
ViewWidgetButtonMenu.VisibleChanged += control => previewLODValue.Value = _previewModel.ForcedLOD;
}
}
// Enable shadows
@@ -339,44 +316,6 @@ namespace FlaxEditor.Viewport.Previews
_previewModel.ResetAnimation();
}
private int ComputeLODIndex(SkinnedModel model)
{
if (PreviewActor.ForcedLOD != -1)
return PreviewActor.ForcedLOD;
// Based on RenderTools::ComputeModelLOD
CreateProjectionMatrix(out var projectionMatrix);
float screenMultiple = 0.5f * Mathf.Max(projectionMatrix.M11, projectionMatrix.M22);
var sphere = PreviewActor.Sphere;
var viewOrigin = ViewPosition;
var distSqr = Vector3.DistanceSquared(ref sphere.Center, ref viewOrigin);
var screenRadiusSquared = Mathf.Square(screenMultiple * sphere.Radius) / Mathf.Max(1.0f, distSqr);
// Check if model is being culled
if (Mathf.Square(model.MinScreenSize * 0.5f) > screenRadiusSquared)
return -1;
// Skip if no need to calculate LOD
if (model.LoadedLODs == 0)
return -1;
var lods = model.LODs;
if (lods.Length == 0)
return -1;
if (lods.Length == 1)
return 0;
// Iterate backwards and return the first matching LOD
for (int lodIndex = lods.Length - 1; lodIndex >= 0; lodIndex--)
{
if (Mathf.Square(lods[lodIndex].ScreenSize * 0.5f) >= screenRadiusSquared)
{
return lodIndex + PreviewActor.LODBias;
}
}
return 0;
}
/// <inheritdoc />
protected override void OnDebugDraw(GPUContext context, ref RenderContext renderContext)
{
@@ -440,45 +379,6 @@ namespace FlaxEditor.Viewport.Previews
}
}
/// <inheritdoc />
public override void Draw()
{
base.Draw();
var skinnedModel = _previewModel.SkinnedModel;
if (skinnedModel == null || !skinnedModel.IsLoaded)
return;
var lods = skinnedModel.LODs;
if (lods.Length == 0)
{
// Force show skeleton for models without geometry
ShowNodes = true;
return;
}
if (_showCurrentLOD)
{
var lodIndex = ComputeLODIndex(skinnedModel);
string text = string.Format("Current LOD: {0}", lodIndex);
if (lodIndex != -1)
{
lodIndex = Mathf.Clamp(lodIndex + PreviewActor.LODBias, 0, lods.Length - 1);
var lod = lods[lodIndex];
int triangleCount = 0, vertexCount = 0;
for (int meshIndex = 0; meshIndex < lod.Meshes.Length; meshIndex++)
{
var mesh = lod.Meshes[meshIndex];
triangleCount += mesh.TriangleCount;
vertexCount += mesh.VertexCount;
}
text += string.Format("\nTriangles: {0:N0}\nVertices: {1:N0}", triangleCount, vertexCount);
}
var font = Style.Current.FontMedium;
var pos = new Float2(10, 50);
Render2D.DrawText(font, text, new Rectangle(pos + Float2.One, Size), Color.Black);
Render2D.DrawText(font, text, new Rectangle(pos, Size), Color.White);
}
}
/// <inheritdoc />
public override void Update(float deltaTime)
{
@@ -498,14 +398,21 @@ namespace FlaxEditor.Viewport.Previews
}
}
/// <summary>
/// Resets the camera to focus on a object.
/// </summary>
public void ResetCamera()
{
ViewportCamera.SetArcBallView(_previewModel.Box);
}
/// <inheritdoc />
public override bool OnKeyDown(KeyboardKeys key)
{
switch (key)
{
case KeyboardKeys.F:
// Pay respect..
ViewportCamera.SetArcBallView(_previewModel.Box);
ResetCamera();
return true;
case KeyboardKeys.Spacebar:
PlayAnimation = !PlayAnimation;
@@ -525,7 +432,6 @@ namespace FlaxEditor.Viewport.Previews
_showNodesButton = null;
_showBoundsButton = null;
_showFloorButton = null;
_showCurrentLODButton = null;
_showNodesNamesButton = null;
base.OnDestroy();

View File

@@ -4,6 +4,8 @@ using System;
using FlaxEditor.Surface;
using FlaxEngine;
using FlaxEngine.GUI;
using FlaxEditor.Viewport.Widgets;
using FlaxEditor.GUI.ContextMenu;
using Object = FlaxEngine.Object;
namespace FlaxEditor.Viewport.Previews
@@ -46,6 +48,7 @@ namespace FlaxEditor.Viewport.Previews
private int _selectedModelIndex;
private Image _guiMaterialControl;
private readonly MaterialBase[] _postFxMaterialsCache = new MaterialBase[1];
private ContextMenu _modelWidgetButtonMenu;
/// <summary>
/// Gets or sets the material asset to preview. It can be <see cref="FlaxEngine.Material"/> or <see cref="FlaxEngine.MaterialInstance"/>.
@@ -95,20 +98,33 @@ namespace FlaxEditor.Viewport.Previews
Task.AddCustomActor(_previewModel);
// Create context menu for primitive switching
if (useWidgets && ViewWidgetButtonMenu != null)
if (useWidgets)
{
ViewWidgetButtonMenu.AddSeparator();
var modelSelect = ViewWidgetButtonMenu.AddChildMenu("Model").ContextMenu;
// Fill out all models
for (int i = 0; i < Models.Length; i++)
// Model mode widget
var modelMode = new ViewportWidgetsContainer(ViewportWidgetLocation.UpperRight);
_modelWidgetButtonMenu = new ContextMenu();
_modelWidgetButtonMenu.VisibleChanged += control =>
{
var button = modelSelect.AddButton(Models[i]);
button.Tag = i;
}
if (!control.Visible)
return;
_modelWidgetButtonMenu.ItemsContainer.DisposeChildren();
// Link the action
modelSelect.ButtonClicked += (button) => SelectedModelIndex = (int)button.Tag;
// Fill out all models
for (int i = 0; i < Models.Length; i++)
{
var index = i;
var button = _modelWidgetButtonMenu.AddButton(Models[index]);
button.ButtonClicked += _ => SelectedModelIndex = index;
button.Checked = SelectedModelIndex == index;
button.Tag = index;
}
};
new ViewportWidgetButton("Model", SpriteHandle.Invalid, _modelWidgetButtonMenu)
{
TooltipText = "Change material model",
Parent = modelMode,
};
modelMode.Parent = this;
}
}

View File

@@ -1,6 +1,5 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
using FlaxEditor.GUI.Input;
using FlaxEngine;
using Object = FlaxEngine.Object;
@@ -56,25 +55,14 @@ namespace FlaxEditor.Viewport.Previews
// Link actors for rendering
Task.AddCustomActor(StaticModel);
Task.AddCustomActor(AnimatedModel);
}
if (useWidgets)
{
// Preview LOD
{
var previewLOD = ViewWidgetButtonMenu.AddButton("Preview LOD");
previewLOD.CloseMenuOnClick = false;
var previewLODValue = new IntValueBox(-1, 90, 2, 70.0f, -1, 10, 0.02f)
{
Parent = previewLOD
};
previewLODValue.ValueChanged += () =>
{
StaticModel.ForcedLOD = previewLODValue.Value;
AnimatedModel.ForcedLOD = previewLODValue.Value;
};
ViewWidgetButtonMenu.VisibleChanged += control => previewLODValue.Value = StaticModel.ForcedLOD;
}
}
/// <summary>
/// Resets the camera to focus on a object.
/// </summary>
public void ResetCamera()
{
ViewportCamera.SetArcBallView(StaticModel.Model != null ? StaticModel.Box : AnimatedModel.Box);
}
private void OnBegin(RenderTask task, GPUContext context)
@@ -103,8 +91,7 @@ namespace FlaxEditor.Viewport.Previews
switch (key)
{
case KeyboardKeys.F:
// Pay respect..
ViewportCamera.SetArcBallView(StaticModel.Model != null ? StaticModel.Box : AnimatedModel.Box);
ResetCamera();
break;
}
return base.OnKeyDown(key);

View File

@@ -1,10 +1,10 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
using FlaxEditor.GUI.ContextMenu;
using FlaxEditor.GUI.Input;
using FlaxEngine;
using FlaxEngine.GUI;
using FlaxEngine.Utilities;
using FlaxEditor.Viewport.Widgets;
using Object = FlaxEngine.Object;
namespace FlaxEditor.Viewport.Previews
@@ -16,10 +16,27 @@ namespace FlaxEditor.Viewport.Previews
public class ModelPreview : AssetPreview
{
private ContextMenuButton _showBoundsButton, _showCurrentLODButton, _showNormalsButton, _showTangentsButton, _showBitangentsButton, _showFloorButton;
private ContextMenu _previewLODsWidgetButtonMenu;
private StaticModel _previewModel, _floorModel;
private bool _showBounds, _showCurrentLOD, _showNormals, _showTangents, _showBitangents, _showFloor;
private MeshDataCache _meshDatas;
/// <summary>
/// Gets or sets a value that shows LOD statistics
/// </summary>
public bool ShowCurrentLOD
{
get => _showCurrentLOD;
set
{
if (_showCurrentLOD == value)
return;
_showCurrentLOD = value;
if (_showCurrentLODButton != null)
_showCurrentLODButton.Checked = value;
}
}
/// <summary>
/// Gets or sets the model asset to preview.
/// </summary>
@@ -198,17 +215,36 @@ namespace FlaxEditor.Viewport.Previews
});
_showCurrentLODButton.IndexInParent = 2;
// Preview LOD
// Preview LODs mode widget
var PreviewLODsMode = new ViewportWidgetsContainer(ViewportWidgetLocation.UpperRight);
_previewLODsWidgetButtonMenu = new ContextMenu();
_previewLODsWidgetButtonMenu.VisibleChanged += control =>
{
var previewLOD = ViewWidgetButtonMenu.AddButton("Preview LOD");
previewLOD.CloseMenuOnClick = false;
var previewLODValue = new IntValueBox(-1, 90, 2, 70.0f, -1, 10, 0.02f)
if (!control.Visible)
return;
var model = _previewModel.Model;
if (model && !model.WaitForLoaded())
{
Parent = previewLOD
};
previewLODValue.ValueChanged += () => _previewModel.ForcedLOD = previewLODValue.Value;
ViewWidgetButtonMenu.VisibleChanged += control => previewLODValue.Value = _previewModel.ForcedLOD;
}
_previewLODsWidgetButtonMenu.ItemsContainer.DisposeChildren();
var lods = model.LODs.Length;
for (int i = -1; i < lods; i++)
{
var index = i;
var button = _previewLODsWidgetButtonMenu.AddButton("LOD " + (index == -1 ? "Auto" : index));
button.ButtonClicked += _ => _previewModel.ForcedLOD = index;
button.Checked = _previewModel.ForcedLOD == index;
button.Tag = index;
if (lods <= 1)
break;
}
}
};
new ViewportWidgetButton("Preview LOD", SpriteHandle.Invalid, _previewLODsWidgetButtonMenu)
{
TooltipText = "Preview LOD properties",
Parent = PreviewLODsMode,
};
PreviewLODsMode.Parent = this;
}
}
@@ -312,7 +348,7 @@ namespace FlaxEditor.Viewport.Previews
var distSqr = Vector3.DistanceSquared(ref sphere.Center, ref viewOrigin);
var screenRadiusSquared = Mathf.Square(screenMultiple * sphere.Radius) / Mathf.Max(1.0f, distSqr);
screenSize = Mathf.Sqrt((float)screenRadiusSquared) * 2.0f;
// Check if model is being culled
if (Mathf.Square(model.MinScreenSize * 0.5f) > screenRadiusSquared)
return -1;
@@ -346,8 +382,11 @@ namespace FlaxEditor.Viewport.Previews
if (_showCurrentLOD)
{
var asset = Model;
var lodIndex = ComputeLODIndex(asset, out var screenSize);
string text = string.Format("Current LOD: {0}\nScreen Size: {1:F2}", lodIndex, screenSize);
var lodIndex = ComputeLODIndex(asset, out var screenSize);
var auto = _previewModel.ForcedLOD == -1;
string text = auto ? "LOD Automatic" : "";
text += auto ? string.Format("\nScreen Size: {0:F2}", screenSize) : "";
text += string.Format("\nCurrent LOD: {0}", lodIndex);
if (lodIndex != -1)
{
var lods = asset.LODs;
@@ -369,14 +408,21 @@ namespace FlaxEditor.Viewport.Previews
}
}
/// <summary>
/// Resets the camera to focus on a object.
/// </summary>
public void ResetCamera()
{
ViewportCamera.SetArcBallView(_previewModel.Box);
}
/// <inheritdoc />
public override bool OnKeyDown(KeyboardKeys key)
{
switch (key)
{
case KeyboardKeys.F:
// Pay respect..
ViewportCamera.SetArcBallView(_previewModel.Box);
ResetCamera();
break;
}
return base.OnKeyDown(key);
@@ -389,6 +435,7 @@ namespace FlaxEditor.Viewport.Previews
Object.Destroy(ref _previewModel);
_showBoundsButton = null;
_showCurrentLODButton = null;
_previewLODsWidgetButtonMenu = null;
_showNormalsButton = null;
_showTangentsButton = null;
_showBitangentsButton = null;

View File

@@ -0,0 +1,177 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
using FlaxEditor.GUI.ContextMenu;
using FlaxEngine;
using FlaxEngine.GUI;
using FlaxEditor.Viewport.Widgets;
namespace FlaxEditor.Viewport.Previews
{
/// <summary>
/// Animation asset preview editor viewport.
/// </summary>
/// <seealso cref="AnimatedModelPreview" />
public class SkinnedModelPreview : AnimatedModelPreview
{
private bool _showCurrentLOD;
private ContextMenuButton _showCurrentLODButton;
private ContextMenu _previewLODsWidgetButtonMenu;
/// <summary>
/// Gets or sets a value that shows LOD statistics
/// </summary>
public bool ShowCurrentLOD
{
get => _showCurrentLOD;
set
{
if (_showCurrentLOD == value)
return;
_showCurrentLOD = value;
if (_showCurrentLODButton != null)
_showCurrentLODButton.Checked = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SkinnedModelPreview"/> class.
/// </summary>
/// <param name="useWidgets">if set to <c>true</c> use widgets.</param>
public SkinnedModelPreview(bool useWidgets)
: base(useWidgets)
{
if (useWidgets)
{
// Show Current LOD
_showCurrentLODButton = ViewWidgetShowMenu.AddButton("Current LOD", button =>
{
_showCurrentLOD = !_showCurrentLOD;
_showCurrentLODButton.Icon = _showCurrentLOD ? Style.Current.CheckBoxTick : SpriteHandle.Invalid;
});
_showCurrentLODButton.IndexInParent = 2;
// PreviewLODS mode widget
var PreviewLODSMode = new ViewportWidgetsContainer(ViewportWidgetLocation.UpperRight);
_previewLODsWidgetButtonMenu = new ContextMenu();
_previewLODsWidgetButtonMenu.VisibleChanged += control =>
{
if (!control.Visible)
return;
var skinned = PreviewActor.SkinnedModel;
if (skinned && !skinned.WaitForLoaded())
{
_previewLODsWidgetButtonMenu.ItemsContainer.DisposeChildren();
var lods = skinned.LODs.Length;
for (int i = -1; i < lods; i++)
{
var index = i;
var button = _previewLODsWidgetButtonMenu.AddButton("LOD " + (index == -1 ? "Auto" : index));
button.ButtonClicked += (button) => PreviewActor.ForcedLOD = index;
button.Checked = PreviewActor.ForcedLOD == index;
button.Tag = index;
if (lods <= 1)
break;
}
}
};
new ViewportWidgetButton("Preview LOD", SpriteHandle.Invalid, _previewLODsWidgetButtonMenu)
{
TooltipText = "Preview LOD properties",
Parent = PreviewLODSMode,
};
PreviewLODSMode.Parent = this;
}
}
private int ComputeLODIndex(SkinnedModel model, out float screenSize)
{
screenSize = 1.0f;
if (PreviewActor.ForcedLOD != -1)
return PreviewActor.ForcedLOD;
// Based on RenderTools::ComputeModelLOD
CreateProjectionMatrix(out var projectionMatrix);
float screenMultiple = 0.5f * Mathf.Max(projectionMatrix.M11, projectionMatrix.M22);
var sphere = PreviewActor.Sphere;
var viewOrigin = ViewPosition;
var distSqr = Vector3.DistanceSquared(ref sphere.Center, ref viewOrigin);
var screenRadiusSquared = Mathf.Square(screenMultiple * sphere.Radius) / Mathf.Max(1.0f, distSqr);
screenSize = Mathf.Sqrt((float)screenRadiusSquared) * 2.0f;
// Check if model is being culled
if (Mathf.Square(model.MinScreenSize * 0.5f) > screenRadiusSquared)
return -1;
// Skip if no need to calculate LOD
if (model.LoadedLODs == 0)
return -1;
var lods = model.LODs;
if (lods.Length == 0)
return -1;
if (lods.Length == 1)
return 0;
// Iterate backwards and return the first matching LOD
for (int lodIndex = lods.Length - 1; lodIndex >= 0; lodIndex--)
{
if (Mathf.Square(lods[lodIndex].ScreenSize * 0.5f) >= screenRadiusSquared)
{
return lodIndex + PreviewActor.LODBias;
}
}
return 0;
}
/// <inheritdoc />
public override void Draw()
{
base.Draw();
var skinnedModel = PreviewActor.SkinnedModel;
if (skinnedModel == null || !skinnedModel.IsLoaded)
return;
var lods = skinnedModel.LODs;
if (lods.Length == 0)
{
// Force show skeleton for models without geometry
ShowNodes = true;
return;
}
if (_showCurrentLOD)
{
var lodIndex = ComputeLODIndex(skinnedModel, out var screenSize);
var auto = PreviewActor.ForcedLOD == -1;
string text = auto ? "LOD Automatic" : "";
text += auto ? string.Format("\nScreen Size: {0:F2}", screenSize) : "";
text += string.Format("\nCurrent LOD: {0}", lodIndex);
if (lodIndex != -1)
{
lodIndex = Mathf.Clamp(lodIndex + PreviewActor.LODBias, 0, lods.Length - 1);
var lod = lods[lodIndex];
int triangleCount = 0, vertexCount = 0;
for (int meshIndex = 0; meshIndex < lod.Meshes.Length; meshIndex++)
{
var mesh = lod.Meshes[meshIndex];
triangleCount += mesh.TriangleCount;
vertexCount += mesh.VertexCount;
}
text += string.Format("\nTriangles: {0:N0}\nVertices: {1:N0}", triangleCount, vertexCount);
}
var font = Style.Current.FontMedium;
var pos = new Float2(10, 50);
Render2D.DrawText(font, text, new Rectangle(pos + Float2.One, Size), Color.Black);
Render2D.DrawText(font, text, new Rectangle(pos, Size), Color.White);
}
}
/// <inheritdoc />
public override void OnDestroy()
{
_showCurrentLODButton = null;
_previewLODsWidgetButtonMenu = null;
base.OnDestroy();
}
}
}

View File

@@ -182,6 +182,7 @@ namespace FlaxEditor.Windows.Assets
{
// Toolstrip
_toolstrip.AddSeparator();
_toolstrip.AddButton(editor.Icons.CenterView64, () => _preview.ResetCamera()).LinkTooltip("Show whole collision");
_toolstrip.AddButton(editor.Icons.Docs64, () => Platform.OpenUrl(Utilities.Constants.DocsUrl + "manual/physics/colliders/collision-data.html")).LinkTooltip("See documentation to learn more");
// Split Panel

View File

@@ -779,6 +779,7 @@ namespace FlaxEditor.Windows.Assets
private MeshDataCache _meshData;
private ModelImportSettings _importSettings = new ModelImportSettings();
private float _backfacesThreshold = 0.6f;
private ToolStripButton _showCurrentLODButton;
/// <inheritdoc />
public ModelWindow(Editor editor, AssetItem item)
@@ -786,6 +787,9 @@ namespace FlaxEditor.Windows.Assets
{
// Toolstrip
_toolstrip.AddSeparator();
_showCurrentLODButton = (ToolStripButton)_toolstrip.AddButton(editor.Icons.Info64, () => _preview.ShowCurrentLOD = !_preview.ShowCurrentLOD).LinkTooltip("Show LOD statistics");
_toolstrip.AddButton(editor.Icons.CenterView64, () => _preview.ResetCamera()).LinkTooltip("Show whole model");
_toolstrip.AddSeparator();
_toolstrip.AddButton(editor.Icons.Docs64, () => Platform.OpenUrl(Utilities.Constants.DocsUrl + "manual/graphics/models/index.html")).LinkTooltip("See documentation to learn more");
// Model preview
@@ -869,6 +873,8 @@ namespace FlaxEditor.Windows.Assets
}
}
_showCurrentLODButton.Checked = _preview.ShowCurrentLOD;
base.Update(deltaTime);
}
@@ -946,6 +952,7 @@ namespace FlaxEditor.Windows.Assets
base.OnDestroy();
Object.Destroy(ref _highlightActor);
_showCurrentLODButton = null;
}
}
}

View File

@@ -31,7 +31,7 @@ namespace FlaxEditor.Windows.Assets
/// <seealso cref="FlaxEditor.Windows.Assets.AssetEditorWindow" />
public sealed class SkinnedModelWindow : ModelBaseWindow<SkinnedModel, SkinnedModelWindow>
{
private sealed class Preview : AnimatedModelPreview
private sealed class Preview : SkinnedModelPreview
{
private readonly SkinnedModelWindow _window;
@@ -1105,6 +1105,7 @@ namespace FlaxEditor.Windows.Assets
private Preview _preview;
private AnimatedModel _highlightActor;
private ToolStripButton _showNodesButton;
private ToolStripButton _showCurrentLODButton;
private MeshData[][] _meshDatas;
private bool _meshDatasInProgress;
@@ -1116,7 +1117,9 @@ namespace FlaxEditor.Windows.Assets
{
// Toolstrip
_toolstrip.AddSeparator();
_showCurrentLODButton = (ToolStripButton)_toolstrip.AddButton(editor.Icons.Info64, () => _preview.ShowCurrentLOD = !_preview.ShowCurrentLOD).LinkTooltip("Show LOD statistics");
_showNodesButton = (ToolStripButton)_toolstrip.AddButton(editor.Icons.Bone64, () => _preview.ShowNodes = !_preview.ShowNodes).LinkTooltip("Show animated model nodes debug view");
_toolstrip.AddButton(editor.Icons.CenterView64, () => _preview.ResetCamera()).LinkTooltip("Show whole model");
_toolstrip.AddSeparator();
_toolstrip.AddButton(editor.Icons.Docs64, () => Platform.OpenUrl(Utilities.Constants.DocsUrl + "manual/animation/skinned-model/index.html")).LinkTooltip("See documentation to learn more");
@@ -1265,6 +1268,7 @@ namespace FlaxEditor.Windows.Assets
}
}
_showCurrentLODButton.Checked = _preview.ShowCurrentLOD;
_showNodesButton.Checked = _preview.ShowNodes;
base.Update(deltaTime);
@@ -1349,6 +1353,7 @@ namespace FlaxEditor.Windows.Assets
Object.Destroy(ref _highlightActor);
_preview = null;
_showNodesButton = null;
_showCurrentLODButton = null;
}
}
}

View File

@@ -80,6 +80,7 @@ namespace FlaxEditor.Windows
public LogGroup Group;
public LogEntryDescription Desc;
public SpriteHandle Icon;
public int LogCount = 1;
public LogEntry(DebugLogWindow window, ref LogEntryDescription desc)
: base(0, 0, 120, DefaultHeight)
@@ -137,7 +138,14 @@ namespace FlaxEditor.Windows
// Title
var textRect = new Rectangle(38, 2, clientRect.Width - 40, clientRect.Height - 10);
Render2D.PushClip(ref clientRect);
Render2D.DrawText(style.FontMedium, Desc.Title, textRect, style.Foreground);
if (LogCount == 1)
{
Render2D.DrawText(style.FontMedium, Desc.Title, textRect, style.Foreground);
}
else if (LogCount > 1)
{
Render2D.DrawText(style.FontMedium, $"{Desc.Title} ({LogCount})", textRect, style.Foreground);
}
Render2D.PopClip();
}
@@ -289,6 +297,7 @@ namespace FlaxEditor.Windows
private readonly List<LogEntry> _pendingEntries = new List<LogEntry>(32);
private readonly ToolStripButton _clearOnPlayButton;
private readonly ToolStripButton _collapseLogsButton;
private readonly ToolStripButton _pauseOnErrorButton;
private readonly ToolStripButton[] _groupButtons = new ToolStripButton[3];
@@ -316,6 +325,7 @@ namespace FlaxEditor.Windows
};
toolstrip.AddButton("Clear", Clear).LinkTooltip("Clears all log entries");
_clearOnPlayButton = (ToolStripButton)toolstrip.AddButton("Clear on Play").SetAutoCheck(true).SetChecked(true).LinkTooltip("Clears all log entries on enter playmode");
_collapseLogsButton = (ToolStripButton)toolstrip.AddButton("Collapse").SetAutoCheck(true).SetChecked(true).LinkTooltip("Collapses similar logs.");
_pauseOnErrorButton = (ToolStripButton)toolstrip.AddButton("Pause on Error").SetAutoCheck(true).LinkTooltip("Performs auto pause on error");
toolstrip.AddSeparator();
_groupButtons[0] = (ToolStripButton)toolstrip.AddButton(editor.Icons.Error32, () => UpdateLogTypeVisibility(LogGroup.Error, _groupButtons[0].Checked)).SetAutoCheck(true).SetChecked(true).LinkTooltip("Shows/hides error messages");
@@ -612,6 +622,30 @@ namespace FlaxEditor.Windows
var top = _entriesPanel.Children.Count != 0 ? _entriesPanel.Children[_entriesPanel.Children.Count - 1].Bottom + spacing : margin.Top;
for (int i = 0; i < _pendingEntries.Count; i++)
{
if (_collapseLogsButton.Checked)
{
bool logExists = false;
foreach (var child in _entriesPanel.Children)
{
if (child is LogEntry entry)
{
var pendingEntry = _pendingEntries[i];
if (string.Equals(entry.Desc.Title, pendingEntry.Desc.Title, StringComparison.Ordinal) &&
string.Equals(entry.Desc.LocationFile, pendingEntry.Desc.LocationFile, StringComparison.Ordinal) &&
entry.Desc.Level == pendingEntry.Desc.Level &&
string.Equals(entry.Desc.Description, pendingEntry.Desc.Description, StringComparison.Ordinal) &&
entry.Desc.LocationLine == pendingEntry.Desc.LocationLine)
{
entry.LogCount += 1;
newEntry = entry;
logExists = true;
break;
}
}
}
if (logExists)
continue;
}
newEntry = _pendingEntries[i];
newEntry.Visible = _groupButtons[(int)newEntry.Group].Checked;
anyVisible |= newEntry.Visible;