| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162 |
- //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
- //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using BansheeEngine;
- namespace BansheeEditor
- {
- /** @addtogroup Windows
- * @{
- */
- /// <summary>
- /// Displays animation curve editor window. Allows the user to manipulate keyframes of animation curves, add/remove
- /// curves from an animation clip, and manipulate animation events.
- /// </summary>
- [DefaultSize(900, 500), UndoRedoLocal]
- internal class AnimationWindow : EditorWindow
- {
- private const int FIELD_DISPLAY_WIDTH = 300;
- private const int DRAG_START_DISTANCE = 3;
- private const float DRAG_SCALE = 3.0f;
- private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
- private SceneObject selectedSO;
- /// <summary>
- /// Scene object for which are we currently changing the animation for.
- /// </summary>
- internal SceneObject SelectedSO
- {
- get { return selectedSO; }
- }
- #region Overrides
- /// <summary>
- /// Opens the animation window.
- /// </summary>
- [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
- private static void OpenGameWindow()
- {
- OpenWindow<AnimationWindow>();
- }
- /// <inheritdoc/>
- protected override LocString GetDisplayName()
- {
- return new LocEdString("Animation");
- }
- private void OnInitialize()
- {
- Selection.OnSelectionChanged += OnSelectionChanged;
- UpdateSelectedSO(true);
- }
- private void OnEditorUpdate()
- {
- if (selectedSO == null)
- return;
- HandleDragAndZoomInput();
- if (state == State.Playback)
- {
- Animation animation = selectedSO.GetComponent<Animation>();
- if (animation != null)
- {
- float time = animation.EditorGetTime();
- int frameIdx = (int)(time * fps);
- SetCurrentFrame(frameIdx);
- animation.UpdateFloatProperties();
- }
- }
- else if (state == State.Recording)
- {
- if (!delayRecord)
- {
- float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
- if (RecordState(time))
- {
- ApplyClipChanges();
- guiCurveEditor.Redraw();
- }
- }
- }
- delayRecord = false;
- }
- private void OnDestroy()
- {
- SwitchState(State.Empty);
- Selection.OnSelectionChanged -= OnSelectionChanged;
- if (selectedSO != null)
- {
- EditorInput.OnPointerPressed -= OnPointerPressed;
- EditorInput.OnPointerMoved -= OnPointerMoved;
- EditorInput.OnPointerReleased -= OnPointerReleased;
- EditorInput.OnButtonUp -= OnButtonUp;
- }
- }
- /// <inheritdoc/>
- protected override void WindowResized(int width, int height)
- {
- if (selectedSO == null)
- return;
- ResizeGUI(width, height);
- }
- #endregion
- #region GUI
- private GUIToggle playButton;
- private GUIToggle recordButton;
- private GUIButton prevFrameButton;
- private GUIIntField frameInputField;
- private GUIButton nextFrameButton;
- private GUIButton addKeyframeButton;
- private GUIButton addEventButton;
- private GUIButton optionsButton;
- private GUIButton addPropertyBtn;
- private GUIButton delPropertyBtn;
- private GUILayout buttonLayout;
- private int buttonLayoutHeight;
- private int scrollBarWidth;
- private int scrollBarHeight;
- private GUIResizeableScrollBarH horzScrollBar;
- private GUIResizeableScrollBarV vertScrollBar;
- private GUIPanel editorPanel;
- private GUIAnimFieldDisplay guiFieldDisplay;
- private GUICurveEditor guiCurveEditor;
- /// <summary>
- /// Recreates the entire curve editor GUI depending on the currently selected scene object.
- /// </summary>
- private void RebuildGUI()
- {
- GUI.Clear();
- guiCurveEditor = null;
- guiFieldDisplay = null;
- if (selectedSO == null)
- {
- GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
- GUILayoutY vertLayout = GUI.AddLayoutY();
- vertLayout.AddFlexibleSpace();
- GUILayoutX horzLayout = vertLayout.AddLayoutX();
- vertLayout.AddFlexibleSpace();
- horzLayout.AddFlexibleSpace();
- horzLayout.AddElement(warningLbl);
- horzLayout.AddFlexibleSpace();
- return;
- }
- // Top button row
- GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
- new LocEdString("Play"));
- GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
- new LocEdString("Record"));
- GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
- new LocEdString("Previous frame"));
- GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
- new LocEdString("Next frame"));
- GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
- new LocEdString("Add keyframe"));
- GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
- new LocEdString("Add event"));
- GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
- new LocEdString("Options"));
- playButton = new GUIToggle(playIcon, EditorStyles.Button);
- recordButton = new GUIToggle(recordIcon, EditorStyles.Button);
- prevFrameButton = new GUIButton(prevFrameIcon);
- frameInputField = new GUIIntField();
- nextFrameButton = new GUIButton(nextFrameIcon);
- addKeyframeButton = new GUIButton(addKeyframeIcon);
- addEventButton = new GUIButton(addEventIcon);
- optionsButton = new GUIButton(optionsIcon);
- playButton.OnToggled += x =>
- {
- if(x)
- SwitchState(State.Playback);
- else
- SwitchState(State.Normal);
- };
- recordButton.OnToggled += x =>
- {
- if (x)
- SwitchState(State.Recording);
- else
- SwitchState(State.Normal);
- };
- prevFrameButton.OnClick += () =>
- {
- SetCurrentFrame(currentFrameIdx - 1);
- switch (state)
- {
- case State.Recording:
- case State.Normal:
- PreviewFrame(currentFrameIdx);
- break;
- default:
- SwitchState(State.Normal);
- break;
- }
- };
- frameInputField.OnChanged += x =>
- {
- SetCurrentFrame(x);
- switch (state)
- {
- case State.Recording:
- case State.Normal:
- PreviewFrame(currentFrameIdx);
- break;
- default:
- SwitchState(State.Normal);
- break;
- }
- };
- nextFrameButton.OnClick += () =>
- {
- SetCurrentFrame(currentFrameIdx + 1);
- switch (state)
- {
- case State.Recording:
- case State.Normal:
- PreviewFrame(currentFrameIdx);
- break;
- default:
- SwitchState(State.Normal);
- break;
- }
- };
- addKeyframeButton.OnClick += () =>
- {
- SwitchState(State.Normal);
- guiCurveEditor.AddKeyFrameAtMarker();
- };
- addEventButton.OnClick += () =>
- {
- SwitchState(State.Normal);
- guiCurveEditor.AddEventAtMarker();
- };
- optionsButton.OnClick += () =>
- {
- Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
- AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(this, openPosition);
- dropDown.Initialize(this);
- };
- // Property buttons
- addPropertyBtn = new GUIButton(new LocEdString("Add property"));
- delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
- addPropertyBtn.OnClick += () =>
- {
- Action openPropertyWindow = () =>
- {
- Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
- FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(this, windowPos);
- fieldSelection.OnFieldSelected += OnFieldAdded;
- };
- if (clipInfo.clip == null)
- {
- LocEdString title = new LocEdString("Warning");
- LocEdString message =
- new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
- " a new animation clip?");
- DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
- {
- if (type == DialogBox.ResultType.Yes)
- {
- string clipSavePath;
- if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.asset", out clipSavePath))
- {
- SwitchState(State.Empty);
- clipSavePath = Path.ChangeExtension(clipSavePath, ".asset");
- AnimationClip newClip = new AnimationClip();
- ProjectLibrary.Create(newClip, clipSavePath);
- LoadAnimClip(newClip);
- Animation animation = selectedSO.GetComponent<Animation>();
- if (animation == null)
- animation = selectedSO.AddComponent<Animation>();
- animation.DefaultClip = newClip;
- EditorApplication.SetSceneDirty();
- SwitchState(State.Normal);
- openPropertyWindow();
- }
- }
- });
- }
- else
- {
- if (clipInfo.isImported)
- {
- LocEdString title = new LocEdString("Warning");
- LocEdString message =
- new LocEdString("You cannot add/edit/remove curves from animation clips that" +
- " are imported from an external file.");
- DialogBox.Open(title, message, DialogBox.Type.OK);
- }
- else
- {
- SwitchState(State.Normal);
- openPropertyWindow();
- }
- }
- };
- delPropertyBtn.OnClick += () =>
- {
- if (clipInfo.clip == null)
- return;
- SwitchState(State.Normal);
- if (clipInfo.isImported)
- {
- LocEdString title = new LocEdString("Warning");
- LocEdString message =
- new LocEdString("You cannot add/edit/remove curves from animation clips that" +
- " are imported from an external file.");
- DialogBox.Open(title, message, DialogBox.Type.OK);
- }
- else
- {
- LocEdString title = new LocEdString("Warning");
- LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
- DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
- {
- if (x == DialogBox.ResultType.Yes)
- {
- RemoveSelectedFields();
- ApplyClipChanges();
- }
- });
- }
- };
- GUIPanel mainPanel = GUI.AddPanel();
- GUIPanel backgroundPanel = GUI.AddPanel(1);
- GUILayout mainLayout = mainPanel.AddLayoutY();
- buttonLayout = mainLayout.AddLayoutX();
- buttonLayout.AddSpace(5);
- buttonLayout.AddElement(playButton);
- buttonLayout.AddElement(recordButton);
- buttonLayout.AddSpace(5);
- buttonLayout.AddElement(prevFrameButton);
- buttonLayout.AddElement(frameInputField);
- buttonLayout.AddElement(nextFrameButton);
- buttonLayout.AddSpace(5);
- buttonLayout.AddElement(addKeyframeButton);
- buttonLayout.AddElement(addEventButton);
- buttonLayout.AddSpace(5);
- buttonLayout.AddElement(optionsButton);
- buttonLayout.AddFlexibleSpace();
- buttonLayoutHeight = playButton.Bounds.height;
- GUITexture buttonBackground = new GUITexture(null, EditorStyles.HeaderBackground);
- buttonBackground.Bounds = new Rect2I(0, 0, Width, buttonLayoutHeight);
- backgroundPanel.AddElement(buttonBackground);
- GUILayout contentLayout = mainLayout.AddLayoutX();
- GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
- guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
- Height - buttonLayoutHeight * 2, selectedSO);
- guiFieldDisplay.OnEntrySelected += OnFieldSelected;
- GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
- bottomButtonLayout.AddElement(addPropertyBtn);
- bottomButtonLayout.AddElement(delPropertyBtn);
- horzScrollBar = new GUIResizeableScrollBarH();
- horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
- vertScrollBar = new GUIResizeableScrollBarV();
- vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
- GUITexture separator = new GUITexture(null, EditorStyles.Separator, GUIOption.FixedWidth(3));
- contentLayout.AddElement(separator);
- GUILayout curveLayout = contentLayout.AddLayoutY();
- GUILayout curveLayoutHorz = curveLayout.AddLayoutX();
- GUILayout horzScrollBarLayout = curveLayout.AddLayoutX();
- horzScrollBarLayout.AddElement(horzScrollBar);
- horzScrollBarLayout.AddFlexibleSpace();
- editorPanel = curveLayoutHorz.AddPanel();
- curveLayoutHorz.AddElement(vertScrollBar);
- curveLayoutHorz.AddFlexibleSpace();
- scrollBarHeight = horzScrollBar.Bounds.height;
- scrollBarWidth = vertScrollBar.Bounds.width;
- Vector2I curveEditorSize = GetCurveEditorSize();
- guiCurveEditor = new GUICurveEditor(this, editorPanel, curveEditorSize.x, curveEditorSize.y);
- guiCurveEditor.OnFrameSelected += OnFrameSelected;
- guiCurveEditor.OnEventAdded += OnEventsChanged;
- guiCurveEditor.OnEventModified += EditorApplication.SetProjectDirty;
- guiCurveEditor.OnEventDeleted += OnEventsChanged;
- guiCurveEditor.OnCurveModified += () =>
- {
- SwitchState(State.Normal);
- ApplyClipChanges();
- PreviewFrame(currentFrameIdx);
- EditorApplication.SetProjectDirty();
- };
- guiCurveEditor.OnClicked += () =>
- {
- if(state != State.Recording)
- SwitchState(State.Normal);
- };
- guiCurveEditor.Redraw();
- horzScrollBar.SetWidth(curveEditorSize.x);
- vertScrollBar.SetHeight(curveEditorSize.y);
- UpdateScrollBarSize();
- }
- /// <summary>
- /// Resizes GUI elements so they fit within the provided boundaries.
- /// </summary>
- /// <param name="width">Width of the GUI bounds, in pixels.</param>
- /// <param name="height">Height of the GUI bounds, in pixels.</param>
- private void ResizeGUI(int width, int height)
- {
- guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
- Vector2I curveEditorSize = GetCurveEditorSize();
- guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
- guiCurveEditor.Redraw();
- horzScrollBar.SetWidth(curveEditorSize.x);
- vertScrollBar.SetHeight(curveEditorSize.y);
- UpdateScrollBarSize();
- UpdateScrollBarPosition();
- }
- #endregion
- #region Scroll, drag, zoom
- private Vector2I dragStartPos;
- private bool isButtonHeld;
- private bool isDragInProgress;
- private float zoomAmount;
- /// <summary>
- /// Handles mouse scroll wheel and dragging events in order to zoom or drag the displayed curve editor contents.
- /// </summary>
- private void HandleDragAndZoomInput()
- {
- // Handle middle mouse dragging
- if (isDragInProgress)
- {
- float lengthPerPixel = guiCurveEditor.Range.x / guiCurveEditor.Width;
- float heightPerPixel = guiCurveEditor.Range.y / guiCurveEditor.Height;
- float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
- float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
- Vector2 offset = guiCurveEditor.Offset;
- offset.x = Math.Max(0.0f, offset.x + dragX);
- offset.y -= dragY;
- guiCurveEditor.Offset = offset;
- UpdateScrollBarSize();
- UpdateScrollBarPosition();
- }
- // Handle zoom in/out
- float scroll = Input.GetAxisValue(InputAxis.MouseZ);
- if (scroll != 0.0f)
- {
- Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
- Vector2 curvePos;
- if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
- {
- float zoom = scroll * ZOOM_SCALE;
- Zoom(curvePos, zoom);
- }
- }
- }
- /// <summary>
- /// Moves or resizes the vertical scroll bar under the curve editor.
- /// </summary>
- /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
- /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
- private void SetVertScrollbarProperties(float position, float size)
- {
- Vector2 visibleRange = guiCurveEditor.Range;
- Vector2 totalRange = GetTotalRange();
- visibleRange.y = totalRange.y*size;
- guiCurveEditor.Range = visibleRange;
- float scrollableRange = totalRange.y - visibleRange.y;
- Vector2 offset = guiCurveEditor.Offset;
- offset.y = -scrollableRange * (position * 2.0f - 1.0f);
- guiCurveEditor.Offset = offset;
- }
- /// <summary>
- /// Moves or resizes the horizontal scroll bar under the curve editor.
- /// </summary>
- /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
- /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
- private void SetHorzScrollbarProperties(float position, float size)
- {
- Vector2 visibleRange = guiCurveEditor.Range;
- Vector2 totalRange = GetTotalRange();
- visibleRange.x = totalRange.x * size;
- guiCurveEditor.Range = visibleRange;
- float scrollableRange = totalRange.x - visibleRange.x;
- Vector2 offset = guiCurveEditor.Offset;
- offset.x = scrollableRange * position;
- guiCurveEditor.Offset = offset;
- }
- /// <summary>
- /// Updates the size of both scrollbars depending on the currently visible curve area vs. the total curve area.
- /// </summary>
- private void UpdateScrollBarSize()
- {
- Vector2 visibleRange = guiCurveEditor.Range;
- Vector2 totalRange = GetTotalRange();
- horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
- vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
- }
- /// <summary>
- /// Updates the position of both scrollbars depending on the offset currently applied to the visible curve area.
- /// </summary>
- private void UpdateScrollBarPosition()
- {
- Vector2 visibleRange = guiCurveEditor.Range;
- Vector2 totalRange = GetTotalRange();
- Vector2 scrollableRange = totalRange - visibleRange;
- Vector2 offset = guiCurveEditor.Offset;
- if (scrollableRange.x > 0.0f)
- horzScrollBar.Position = offset.x / scrollableRange.x;
- else
- horzScrollBar.Position = 0.0f;
- if (scrollableRange.y > 0.0f)
- {
- float pos = offset.y/scrollableRange.y;
- float sign = MathEx.Sign(pos);
- pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
- pos = (1.0f - pos) /2.0f;
- vertScrollBar.Position = pos;
- }
- else
- vertScrollBar.Position = 0.0f;
- }
- /// <summary>
- /// Calculates the width/height of the curve area depending on the current zoom level.
- /// </summary>
- /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
- private Vector2 GetZoomedRange()
- {
- float zoomLevel = MathEx.Pow(2, zoomAmount);
- Vector2 optimalRange = GetOptimalRange();
- return optimalRange / zoomLevel;
- }
- /// <summary>
- /// Returns the total width/height of the contents of the curve area.
- /// </summary>
- /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
- private Vector2 GetTotalRange()
- {
- // Return optimal range (that covers the visible curve)
- Vector2 optimalRange = GetOptimalRange();
- // Increase range in case user zoomed out
- Vector2 zoomedRange = GetZoomedRange();
- return Vector2.Max(optimalRange, zoomedRange);
- }
- /// <summary>
- /// Zooms in or out at the provided position in the curve display.
- /// </summary>
- /// <param name="curvePos">Position to zoom towards, relative to the curve display area, in curve space
- /// (value, time)</param>
- /// <param name="amount">Amount to zoom in (positive), or out (negative).</param>
- private void Zoom(Vector2 curvePos, float amount)
- {
- // Increase or decrease the visible range depending on zoom level
- Vector2 oldZoomedRange = GetZoomedRange();
- zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
- Vector2 zoomedRange = GetZoomedRange();
- Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
- Vector2 currentRange = guiCurveEditor.Range;
- Vector2 newRange = currentRange + zoomedDiff;
- guiCurveEditor.Range = newRange;
- // When zooming, make sure to focus on the point provided, so adjust the offset
- Vector2 rangeScale = newRange;
- rangeScale.x /= currentRange.x;
- rangeScale.y /= currentRange.y;
- Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
- Vector2 newCurvePos = relativeCurvePos * rangeScale;
- Vector2 diff = newCurvePos - relativeCurvePos;
- guiCurveEditor.Offset -= diff;
- UpdateScrollBarSize();
- UpdateScrollBarPosition();
- }
- #endregion
- #region Curve save/load
- private EditorAnimClipInfo clipInfo;
- /// <summary>
- /// Refreshes the contents of the curve and property display by loading animation curves from the provided
- /// animation clip.
- /// </summary>
- /// <param name="clip">Clip containing the animation to load.</param>
- private void LoadAnimClip(AnimationClip clip)
- {
- EditorPersistentData persistentData = EditorApplication.PersistentData;
- if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
- {
- // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
- // since last modification, so we re-load the clip. But we persist the events as those can only be set
- // within the editor.
- if (clipInfo.isImported)
- {
- EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
- newClipInfo.events = clipInfo.events;
- }
- }
- else
- clipInfo = EditorAnimClipInfo.Create(clip);
- persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
- AnimFieldInfo[] fieldInfos = new AnimFieldInfo[clipInfo.curves.Count];
- int idx = 0;
- foreach (var curve in clipInfo.curves)
- fieldInfos[idx++] = new AnimFieldInfo(curve.Key, curve.Value);
- guiFieldDisplay.SetFields(fieldInfos);
- guiCurveEditor.Events = clipInfo.events;
- guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
- SetCurrentFrame(0);
- FPS = clipInfo.sampleRate;
- }
- /// <summary>
- /// Applies any changes made to the animation curves and events to the actual animation clip resource.
- /// </summary>
- private void ApplyClipChanges()
- {
- if (clipInfo == null)
- return;
- EditorAnimClipTangents unused;
- clipInfo.Apply(out unused);
- }
- /// <summary>
- /// Checks if the currently selected object has changed, and rebuilds the GUI and loads the animation clip if needed.
- /// </summary>
- /// <param name="force">If true the GUI rebuild and animation clip load will be forced regardless if the active
- /// scene object changed.</param>
- private void UpdateSelectedSO(bool force)
- {
- SceneObject so = Selection.SceneObject;
- if (selectedSO != so || force)
- {
- if (selectedSO != null && so == null)
- {
- EditorInput.OnPointerPressed -= OnPointerPressed;
- EditorInput.OnPointerMoved -= OnPointerMoved;
- EditorInput.OnPointerReleased -= OnPointerReleased;
- EditorInput.OnButtonUp -= OnButtonUp;
- }
- else if (selectedSO == null && so != null)
- {
- EditorInput.OnPointerPressed += OnPointerPressed;
- EditorInput.OnPointerMoved += OnPointerMoved;
- EditorInput.OnPointerReleased += OnPointerReleased;
- EditorInput.OnButtonUp += OnButtonUp;
- }
- SwitchState(State.Empty);
- selectedSO = so;
- zoomAmount = 0.0f;
- selectedFields.Clear();
- clipInfo = null;
- UndoRedo.Clear();
- RebuildGUI();
- // Load existing clip if one exists
- if (selectedSO != null)
- {
- Animation animation = selectedSO.GetComponent<Animation>();
- if (animation != null)
- {
- AnimationClip clip = animation.DefaultClip;
- if (clip != null)
- LoadAnimClip(clip);
- }
- }
- if(clipInfo == null)
- clipInfo = new EditorAnimClipInfo();
- SwitchState(State.Normal);
- currentClipState = CreateClipState();
- if (selectedSO != null)
- {
- // Select first curve by default
- foreach (var KVP in clipInfo.curves)
- {
- SelectField(KVP.Key, false);
- break;
- }
- UpdateDisplayedCurves(true);
- }
- }
- }
- /// <summary>
- /// Stops animation preview on the selected object and resets it back to its non-animated state.
- /// </summary>
- private void ClearSO()
- {
- if (selectedSO != null)
- {
- Animation animation = selectedSO.GetComponent<Animation>();
- if (animation != null)
- animation.EditorStop();
- // Reset generic curves to their initial values
- UpdateGenericCurves(0.0f);
- }
- }
- #endregion
- #region Undo/Redo
- private AnimationClipState currentClipState;
- /// <summary>
- /// Records current clip state for undo/redo purposes.
- /// </summary>
- internal void RecordClipState()
- {
- AnimationClipState clipState = CreateClipState();
- AnimationUndo undoCommand = new AnimationUndo(currentClipState, clipState);
- UndoRedo.RegisterCommand(undoCommand);
- currentClipState = clipState;
- }
- /// <summary>
- /// Records current clip state for undo/redo purposes.
- /// </summary>
- internal AnimationClipState CreateClipState()
- {
- AnimationClipState clipState = new AnimationClipState();
- clipState.events = new AnimationEvent[clipInfo.events.Length];
- for (int i = 0; i < clipState.events.Length; i++)
- clipState.events[i] = new AnimationEvent(clipInfo.events[i].name, clipInfo.events[i].time);
- foreach (var curveField in clipInfo.curves)
- {
- AnimationCurveState[] curveData = new AnimationCurveState[curveField.Value.curveInfos.Length];
- for (int i = 0; i < curveData.Length; i++)
- {
- curveData[i] = new AnimationCurveState();
- TangentMode[] tangentModes = curveField.Value.curveInfos[i].curve.TangentModes;
- int numTangentModes = tangentModes.Length;
- curveData[i].tangentModes = new TangentMode[numTangentModes];
- Array.Copy(tangentModes, curveData[i].tangentModes, numTangentModes);
- KeyFrame[] keyFrames = curveField.Value.curveInfos[i].curve.KeyFrames;
- int numKeyframes = keyFrames.Length;
- curveData[i].keyFrames = new KeyFrame[numKeyframes];
- Array.Copy(keyFrames, curveData[i].keyFrames, numKeyframes);
- }
- clipState.curves[curveField.Key] = curveData;
- }
- return clipState;
- }
- /// <summary>
- /// Updates the current animation fields from the keyframes and events in the provided state.
- /// </summary>
- /// <param name="animationClipState">Saved state of an animation clip.</param>
- internal void ApplyClipState(AnimationClipState animationClipState)
- {
- if (state == State.Empty)
- return;
- SwitchState(State.Normal);
- AnimationEvent[] events = animationClipState.events;
- clipInfo.events = new AnimationEvent[events.Length];
- for(int i = 0; i < events.Length; i++)
- clipInfo.events[i] = new AnimationEvent(events[i].name, events[i].time);
- foreach (var KVP in animationClipState.curves)
- {
- FieldAnimCurves fieldCurves;
- if (!clipInfo.curves.TryGetValue(KVP.Key, out fieldCurves))
- continue;
- for (int i = 0; i < fieldCurves.curveInfos.Length; i++)
- {
- AnimationCurve curve = new AnimationCurve(KVP.Value[i].keyFrames);
- fieldCurves.curveInfos[i].curve = new EdAnimationCurve(curve, KVP.Value[i].tangentModes);
- }
- clipInfo.curves[KVP.Key] = fieldCurves;
- }
- // Clear all keyframes from curves not in the stored state
- foreach (var currentKVP in clipInfo.curves)
- {
- bool found = false;
- foreach (var stateKVP in animationClipState.curves)
- {
- if (currentKVP.Key == stateKVP.Key)
- {
- found = true;
- break;
- }
- }
- if (found)
- continue;
- FieldAnimCurves fieldCurves = currentKVP.Value;
- for (int i = 0; i < fieldCurves.curveInfos.Length; i++)
- {
- AnimationCurve curve = new AnimationCurve(new KeyFrame[0]);
- fieldCurves.curveInfos[i].curve = new EdAnimationCurve(curve, new TangentMode[0]);
- }
- }
- currentClipState = animationClipState;
- UpdateDisplayedCurves();
- ApplyClipChanges();
- PreviewFrame(currentFrameIdx);
- EditorApplication.SetProjectDirty();
- }
- #endregion
- #region Record/Playback
- /// <summary>
- /// Possible states the animation window can be in.
- /// </summary>
- private enum State
- {
- Empty,
- Normal,
- Recording,
- Playback
- }
- private State state = State.Empty;
- private bool delayRecord = false;
- /// <summary>
- /// Transitions the window into a different state. Caller must validate state transitions.
- /// </summary>
- /// <param name="state">New state to transition to.</param>
- private void SwitchState(State state)
- {
- switch (this.state)
- {
- case State.Normal:
- {
- switch (state)
- {
- case State.Playback:
- StartPlayback();
- break;
- case State.Recording:
- StartRecord();
- break;
- case State.Empty:
- ClearSO();
- break;
- }
- }
- break;
- case State.Playback:
- {
- switch (state)
- {
- case State.Normal:
- EndPlayback();
- PreviewFrame(currentFrameIdx);
- break;
- case State.Recording:
- EndPlayback();
- StartRecord();
- break;
- case State.Empty:
- EndPlayback();
- ClearSO();
- break;
- }
- }
- break;
- case State.Recording:
- {
- switch (state)
- {
- case State.Normal:
- EndRecord();
- PreviewFrame(currentFrameIdx);
- break;
- case State.Playback:
- EndRecord();
- StartPlayback();
- break;
- case State.Empty:
- EndRecord();
- ClearSO();
- break;
- }
- }
- break;
- case State.Empty:
- {
- switch (state)
- {
- case State.Normal:
- PreviewFrame(currentFrameIdx);
- break;
- case State.Playback:
- StartPlayback();
- break;
- case State.Recording:
- StartRecord();
- break;
- }
- }
- break;
- }
- this.state = state;
- }
- /// <summary>
- /// Plays back the animation on the currently selected object.
- /// </summary>
- private void StartPlayback()
- {
- EditorAnimClipTangents unused;
- clipInfo.Apply(out unused);
- Animation animation = selectedSO.GetComponent<Animation>();
- if (animation != null && clipInfo.clip != null)
- {
- float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
- animation.EditorPlay(clipInfo.clip, time);
- }
- playButton.Value = true;
- }
- /// <summary>
- /// Ends playback started with <see cref="StartPlayback"/>
- /// </summary>
- private void EndPlayback()
- {
- PreviewFrame(currentFrameIdx);
- playButton.Value = false;
- }
- /// <summary>
- /// Updates the visible animation to display the provided frame.
- /// </summary>
- /// <param name="frameIdx">Index of the animation frame to display.</param>
- private void PreviewFrame(int frameIdx)
- {
- if (selectedSO == null)
- return;
- float time = guiCurveEditor.GetTimeForFrame(frameIdx);
- Animation animation = selectedSO.GetComponent<Animation>();
- if (animation != null && clipInfo.clip != null)
- animation.EditorPlay(clipInfo.clip, time, true);
- UpdateGenericCurves(time);
- }
- /// <summary>
- /// Start recording modifications made to the selected scene object.
- /// </summary>
- private void StartRecord()
- {
- float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
- if (RecordState(time))
- {
- ApplyClipChanges();
- guiCurveEditor.Redraw();
- }
- recordButton.Value = true;
- }
- /// <summary>
- /// Stops recording modifications made to the selected scene object.
- /// </summary>
- private void EndRecord()
- {
- recordButton.Value = false;
- }
- /// <summary>
- /// Updates the states of all properties controlled by curves to the value of the curves at the provided time.
- /// </summary>
- /// <param name="time">Time at which to evaluate the curves controlling the properties.</param>
- private void UpdateGenericCurves(float time)
- {
- foreach (var KVP in clipInfo.curves)
- {
- FieldAnimCurves curves;
- if (!clipInfo.curves.TryGetValue(KVP.Key, out curves))
- continue;
- string suffix;
- SerializableProperty property = Animation.FindProperty(selectedSO, KVP.Key, out suffix);
- if (property == null)
- continue;
- float DoOnComponent(int index)
- {
- EdAnimationCurve curve = curves.curveInfos[index].curve;
- return curve.Evaluate(time);
- }
- ForEachPropertyComponentSet(property, DoOnComponent);
- }
- }
- /// <summary>
- /// Iterates over all curve path fields and records their current state. If the state differs from the current
- /// curve values, new keyframes are added.
- /// </summary>
- /// <param name="time">Time for which to record the state, in seconds.</param>
- /// <returns>True if any changes were recorded, false otherwise.</returns>
- private bool RecordState(float time)
- {
- bool changesMade = false;
- foreach (var KVP in clipInfo.curves)
- {
- if (RecordState(KVP.Key, time))
- changesMade = true;
- }
- return changesMade;
- }
- /// <summary>
- /// Records the state of the provided property and adds it as a keyframe to the related animation curve (or updates
- /// an existing keyframe if the value is different).
- /// </summary>
- /// <param name="path">Path to the property whose state to record.</param>
- /// <param name="time">Time for which to record the state, in seconds.</param>
- /// <returns>True if any changes were recorded, false otherwise.</returns>
- private bool RecordState(string path, float time)
- {
- FieldAnimCurves curves;
- if (!clipInfo.curves.TryGetValue(path, out curves))
- return false;
- string suffix;
- SerializableProperty property = Animation.FindProperty(selectedSO, path, out suffix);
- if (property == null)
- return false;
- bool changesMade = false;
- void DoOnComponent(float value, int index)
- {
- EdAnimationCurve curve = curves.curveInfos[index].curve;
- float curveVal = curve.Evaluate(time);
- if (!MathEx.ApproxEquals(value, curveVal, 0.001f))
- {
- KeyFrame[] keyframes = curve.KeyFrames;
- int keyframeIdx = -1;
- for (int i = 0; i < keyframes.Length; i++)
- {
- if (MathEx.ApproxEquals(keyframes[i].time, time))
- {
- keyframeIdx = i;
- break;
- }
- }
- if (keyframeIdx != -1)
- curve.UpdateKeyframe(keyframeIdx, time, value);
- else
- curve.AddKeyframe(time, value);
- curve.Apply();
- changesMade = true;
- }
- }
- ForEachPropertyComponentGet(property, DoOnComponent);
- return changesMade;
- }
- #endregion
- #region Curve display
- private int currentFrameIdx;
- private int fps = 1;
- /// <summary>
- /// Sampling rate of the animation in frames per second. Determines granularity at which positions keyframes can be
- /// placed.
- /// </summary>
- internal int FPS
- {
- get { return fps; }
- set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
- }
- /// <summary>
- /// Changes the currently selected frame in the curve display.
- /// </summary>
- /// <param name="frameIdx">Index of the frame to select.</param>
- private void SetCurrentFrame(int frameIdx)
- {
- currentFrameIdx = Math.Max(0, frameIdx);
- frameInputField.Value = currentFrameIdx;
- guiCurveEditor.SetMarkedFrame(currentFrameIdx);
- float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
- List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
- foreach (var kvp in clipInfo.curves)
- {
- GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
- fieldValue.path = kvp.Key;
- switch (kvp.Value.type)
- {
- case SerializableProperty.FieldType.Vector2:
- {
- Vector2 value = new Vector2();
- for (int i = 0; i < 2; i++)
- value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
- fieldValue.value = value;
- }
- break;
- case SerializableProperty.FieldType.Vector3:
- {
- Vector3 value = new Vector3();
- for (int i = 0; i < 3; i++)
- value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
- fieldValue.value = value;
- }
- break;
- case SerializableProperty.FieldType.Vector4:
- {
- Vector4 value = new Vector4();
- for (int i = 0; i < 4; i++)
- value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
- fieldValue.value = value;
- }
- break;
- case SerializableProperty.FieldType.Color:
- {
- Color value = new Color();
- for (int i = 0; i < 4; i++)
- value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
- fieldValue.value = value;
- }
- break;
- case SerializableProperty.FieldType.Bool:
- case SerializableProperty.FieldType.Int:
- case SerializableProperty.FieldType.Float:
- fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
- break;
- }
- values.Add(fieldValue);
- }
- guiFieldDisplay.SetDisplayValues(values.ToArray());
- }
- /// <summary>
- /// Returns a list of all animation curves that should be displayed in the curve display.
- /// </summary>
- /// <returns>Array of curves to display.</returns>
- private CurveDrawInfo[] GetDisplayedCurves()
- {
- List<CurveDrawInfo> curvesToDisplay = new List<CurveDrawInfo>();
- if (clipInfo == null)
- return curvesToDisplay.ToArray();
- for (int i = 0; i < selectedFields.Count; i++)
- {
- CurveDrawInfo[] curveInfos;
- if (TryGetCurve(selectedFields[i], out curveInfos))
- curvesToDisplay.AddRange(curveInfos);
- }
- return curvesToDisplay.ToArray();
- }
- /// <summary>
- /// Returns width/height required to show the entire contents of the currently displayed curves.
- /// </summary>
- /// <returns>Width/height of the curve area, in curve space (time, value).</returns>
- private Vector2 GetOptimalRange()
- {
- CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
- float xMin, xMax;
- float yMin, yMax;
- CalculateRange(curvesToDisplay, out xMin, out xMax, out yMin, out yMax);
- float xRange = xMax;
- float yRange = Math.Max(Math.Abs(yMin), Math.Abs(yMax));
- // Add padding to y range
- yRange *= 1.05f;
- // Don't allow zero range
- if (xRange == 0.0f)
- xRange = 60.0f;
- if (yRange == 0.0f)
- yRange = 10.0f;
- return new Vector2(xRange, yRange);
- }
- /// <summary>
- /// Returns the offset and range required for fully displaying the currently selected set of curves.
- /// </summary>
- /// <param name="offset">Offset used for centering the curves.</param>
- /// <param name="range">Range representing the width/height in curve space (time, value). </param>
- private void GetOptimalRangeAndOffset(out Vector2 offset, out Vector2 range)
- {
- CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
- float xMin, xMax;
- float yMin, yMax;
- CalculateRange(curvesToDisplay, out xMin, out xMax, out yMin, out yMax);
- float xRange = xMax - xMin;
- float yRange = (yMax - yMin) * 0.5f;
- float yOffset = yMin + yRange;
- // Add padding to y range
- yRange *= 1.05f;
- // Don't allow zero range
- if (xRange == 0.0f)
- xRange = 60.0f;
- if (yRange == 0.0f)
- yRange = 10.0f;
- offset = new Vector2(xMin, yOffset);
- range = new Vector2(xRange, yRange);
- }
- /// <summary>
- /// Calculates an unique color for each animation curve.
- /// </summary>
- private void UpdateCurveColors()
- {
- int globalCurveIdx = 0;
- foreach (var curveGroup in clipInfo.curves)
- {
- for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
- curveGroup.Value.curveInfos[i].color = GUICurveDrawing.GetUniqueColor(globalCurveIdx++);
- }
- }
- /// <summary>
- /// Updates the offset and range of the curve display to fully fit the currently selected set of curves.
- /// </summary>
- /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
- /// be kept as is.</param>
- private void CenterAndResizeCurveDisplay(bool resetTime)
- {
- Vector2 offset, range;
- GetOptimalRangeAndOffset(out offset, out range);
- if (!resetTime)
- {
- offset.x = guiCurveEditor.Offset.x;
- range.x = guiCurveEditor.Range.x;
- }
- guiCurveEditor.Range = range;
- guiCurveEditor.Offset = offset;
- UpdateScrollBarPosition();
- UpdateScrollBarSize();
- }
- /// <summary>
- /// Updates the curve display with currently selected curves.
- /// </summary>
- /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
- /// be kept as is.</param>
- private void UpdateDisplayedCurves(bool resetTime = false)
- {
- CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
- guiCurveEditor.SetCurves(curvesToDisplay);
- CenterAndResizeCurveDisplay(resetTime);
- }
- #endregion
- #region Field display
- private List<string> selectedFields = new List<string>();
- /// <summary>
- /// Registers a new animation curve field.
- /// </summary>
- /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
- /// <param name="type">Type of the field (float, vector, etc.)</param>
- private void AddNewField(string path, SerializableProperty.FieldType type)
- {
- bool isPropertyCurve = !clipInfo.isImported && !EditorAnimClipInfo.IsMorphShapeCurve(path);
- switch (type)
- {
- case SerializableProperty.FieldType.Vector4:
- {
- FieldAnimCurves fieldCurves = new FieldAnimCurves();
- fieldCurves.type = type;
- fieldCurves.isPropertyCurve = isPropertyCurve;
- fieldCurves.curveInfos = new CurveDrawInfo[4];
- string[] subPaths = { ".x", ".y", ".z", ".w" };
- for (int i = 0; i < subPaths.Length; i++)
- {
- string subFieldPath = path + subPaths[i];
- fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
- selectedFields.Add(subFieldPath);
- }
- clipInfo.curves[path] = fieldCurves;
- }
- break;
- case SerializableProperty.FieldType.Vector3:
- {
- FieldAnimCurves fieldCurves = new FieldAnimCurves();
- fieldCurves.type = type;
- fieldCurves.isPropertyCurve = isPropertyCurve;
- fieldCurves.curveInfos = new CurveDrawInfo[3];
- string[] subPaths = { ".x", ".y", ".z" };
- for (int i = 0; i < subPaths.Length; i++)
- {
- string subFieldPath = path + subPaths[i];
- fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
- selectedFields.Add(subFieldPath);
- }
- clipInfo.curves[path] = fieldCurves;
- }
- break;
- case SerializableProperty.FieldType.Vector2:
- {
- FieldAnimCurves fieldCurves = new FieldAnimCurves();
- fieldCurves.type = type;
- fieldCurves.isPropertyCurve = isPropertyCurve;
- fieldCurves.curveInfos = new CurveDrawInfo[2];
- string[] subPaths = { ".x", ".y" };
- for (int i = 0; i < subPaths.Length; i++)
- {
- string subFieldPath = path + subPaths[i];
- fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
- selectedFields.Add(subFieldPath);
- }
- clipInfo.curves[path] = fieldCurves;
- }
- break;
- case SerializableProperty.FieldType.Color:
- {
- FieldAnimCurves fieldCurves = new FieldAnimCurves();
- fieldCurves.type = type;
- fieldCurves.isPropertyCurve = isPropertyCurve;
- fieldCurves.curveInfos = new CurveDrawInfo[4];
- string[] subPaths = { ".r", ".g", ".b", ".a" };
- for (int i = 0; i < subPaths.Length; i++)
- {
- string subFieldPath = path + subPaths[i];
- fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
- selectedFields.Add(subFieldPath);
- }
- clipInfo.curves[path] = fieldCurves;
- }
- break;
- default: // Primitive type
- {
- FieldAnimCurves fieldCurves = new FieldAnimCurves();
- fieldCurves.type = type;
- fieldCurves.isPropertyCurve = isPropertyCurve;
- fieldCurves.curveInfos = new CurveDrawInfo[1];
- fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
- selectedFields.Add(path);
- clipInfo.curves[path] = fieldCurves;
- }
- break;
- }
- UpdateCurveColors();
- UpdateDisplayedFields();
- EditorApplication.SetProjectDirty();
- UpdateDisplayedCurves();
- }
- /// <summary>
- /// Selects a new animation curve field, making the curve display in the curve display GUI element.
- /// </summary>
- /// <param name="path">Path of the field to display.</param>
- /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
- /// only the provided field will be shown.</param>
- private void SelectField(string path, bool additive)
- {
- if (!additive)
- selectedFields.Clear();
- if (!string.IsNullOrEmpty(path))
- {
- selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
- selectedFields.Add(path);
- }
- guiFieldDisplay.SetSelection(selectedFields.ToArray());
- UpdateDisplayedCurves();
- }
- /// <summary>
- /// Deletes all currently selecting fields, removing them their curves permanently.
- /// </summary>
- private void RemoveSelectedFields()
- {
- for (int i = 0; i < selectedFields.Count; i++)
- clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
- UpdateCurveColors();
- UpdateDisplayedFields();
- selectedFields.Clear();
- EditorApplication.SetProjectDirty();
- UpdateDisplayedCurves();
- }
- /// <summary>
- /// Updates the GUI element displaying the current animation curve fields.
- /// </summary>
- private void UpdateDisplayedFields()
- {
- List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
- foreach (var KVP in clipInfo.curves)
- existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value));
- guiFieldDisplay.SetFields(existingFields.ToArray());
- }
- #endregion
- #region Helpers
- /// <summary>
- /// Returns the size of the curve editor GUI element.
- /// </summary>
- /// <returns>Width/height of the curve editor, in pixels.</returns>
- private Vector2I GetCurveEditorSize()
- {
- Vector2I output = new Vector2I();
- output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
- output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
- return output;
- }
- /// <summary>
- /// Calculates the total range covered by a set of curves.
- /// </summary>
- /// <param name="curveInfos">Curves to calculate range for.</param>
- /// <param name="xMin">Minimum time value present in the curves.</param>
- /// <param name="xMax">Maximum time value present in the curves.</param>
- /// <param name="yMin">Minimum curve value present in the curves.</param>
- /// <param name="yMax">Maximum curve value present in the curves.</param>
- private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xMin, out float xMax, out float yMin,
- out float yMax)
- {
- // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
- // tangents
- xMin = float.PositiveInfinity;
- xMax = float.NegativeInfinity;
- yMin = float.PositiveInfinity;
- yMax = float.NegativeInfinity;
- foreach (var curveInfo in curveInfos)
- {
- KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
- foreach (var key in keyframes)
- {
- xMin = Math.Min(xMin, key.time);
- xMax = Math.Max(xMax, key.time);
- yMin = Math.Min(yMin, key.value);
- yMax = Math.Max(yMax, key.value);
- }
- }
- if (xMin == float.PositiveInfinity)
- xMin = 0.0f;
- if (xMax == float.NegativeInfinity)
- xMax = 0.0f;
- if (yMin == float.PositiveInfinity)
- yMin = 0.0f;
- if (yMax == float.NegativeInfinity)
- yMax = 0.0f;
- }
- /// <summary>
- /// Attempts to find a curve field at the specified path.
- /// </summary>
- /// <param name="path">Path of the curve field to look for.</param>
- /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
- /// if it is a complex type, like a vector).</param>
- /// <returns>True if the curve field was found, false otherwise.</returns>
- private bool TryGetCurve(string path, out CurveDrawInfo[] curveInfos)
- {
- int index = path.LastIndexOf(".");
- string parentPath;
- string subPathSuffix = null;
- if (index == -1)
- {
- parentPath = path;
- }
- else
- {
- parentPath = path.Substring(0, index);
- subPathSuffix = path.Substring(index, path.Length - index);
- }
- FieldAnimCurves fieldCurves;
- if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
- {
- if (!string.IsNullOrEmpty(subPathSuffix))
- {
- if (subPathSuffix == ".x" || subPathSuffix == ".r")
- {
- curveInfos = new [] { fieldCurves.curveInfos[0] };
- return true;
- }
- else if (subPathSuffix == ".y" || subPathSuffix == ".g")
- {
- curveInfos = new[] { fieldCurves.curveInfos[1] };
- return true;
- }
- else if (subPathSuffix == ".z" || subPathSuffix == ".b")
- {
- curveInfos = new[] { fieldCurves.curveInfos[2] };
- return true;
- }
- else if (subPathSuffix == ".w" || subPathSuffix == ".a")
- {
- curveInfos = new[] { fieldCurves.curveInfos[3] };
- return true;
- }
- }
- else
- {
- curveInfos = fieldCurves.curveInfos;
- return true;
- }
- }
- curveInfos = new CurveDrawInfo[0];
- return false;
- }
- /// <summary>
- /// Checks if one curve field path a parent of the other.
- /// </summary>
- /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
- /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
- /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
- private bool IsPathParent(string child, string parent)
- {
- string[] childEntries = child.Split('/', '.');
- string[] parentEntries = parent.Split('/', '.');
- if (parentEntries.Length >= child.Length)
- return false;
- int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
- for (int i = 0; i < compareLength; i++)
- {
- if (childEntries[i] != parentEntries[i])
- return false;
- }
- return true;
- }
- /// <summary>
- /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
- /// path.
- /// </summary>
- /// <param name="path">Path to check.</param>
- /// <returns>Path without sub-elements.</returns>
- private string GetSubPathParent(string path)
- {
- int index = path.LastIndexOf(".");
- if (index == -1)
- return path;
- return path.Substring(0, index);
- }
- /// <summary>
- /// Iterates over all components of a property and calls the provided action for every component with the current
- /// value of the property. Only works with floating point (any dimension), integer, color and boolean property
- /// types. Since reported values are always floating point booleans are encoded as -1.0f for false and 1.0f for
- /// true, and integers are converted to floating point.
- /// </summary>
- /// <param name="property">Property whose components to iterate over.</param>
- /// <param name="action">
- /// Callback to trigger for each component. The callback receives the current value of the property's component
- /// and the sequential index of the component.
- /// </param>
- private void ForEachPropertyComponentGet(SerializableProperty property, Action<float, int> action)
- {
- switch (property.Type)
- {
- case SerializableProperty.FieldType.Vector2:
- {
- Vector2 value = property.GetValue<Vector2>();
- for (int i = 0; i < 2; i++)
- action(value[i], i);
- }
- break;
- case SerializableProperty.FieldType.Vector3:
- {
- Vector3 value = property.GetValue<Vector3>();
- for (int i = 0; i < 3; i++)
- action(value[i], i);
- }
- break;
- case SerializableProperty.FieldType.Vector4:
- {
- if (property.InternalType == typeof(Vector4))
- {
- Vector4 value = property.GetValue<Vector4>();
- for (int i = 0; i < 4; i++)
- action(value[i], i);
- }
- else if (property.InternalType == typeof(Quaternion))
- {
- Quaternion value = property.GetValue<Quaternion>();
- for (int i = 0; i < 4; i++)
- action(value[i], i);
- }
- }
- break;
- case SerializableProperty.FieldType.Color:
- {
- Color value = property.GetValue<Color>();
- for (int i = 0; i < 4; i++)
- action(value[i], i);
- }
- break;
- case SerializableProperty.FieldType.Bool:
- {
- bool value = property.GetValue<bool>();
- action(value ? 1.0f : -1.0f, 0);
- }
- break;
- case SerializableProperty.FieldType.Int:
- {
- int value = property.GetValue<int>();
- action(value, 0);
- }
- break;
- case SerializableProperty.FieldType.Float:
- {
- float value = property.GetValue<float>();
- action(value, 0);
- }
- break;
- }
- }
- /// <summary>
- /// Iterates over all components of a property, calls the provided action which returns a new value to be
- /// assigned to the property component. Only works with floating point (any dimension), integer, color and boolean
- /// property types. Since reported values are always floating point booleans are encoded as -1.0f for false and
- /// 1.0f for true, and integers are converted to floating point.
- /// </summary>
- /// <param name="property">Property whose components to iterate over.</param>
- /// <param name="action">
- /// Callback to trigger for each component. The callback receives the current value of the property's component
- /// and the sequential index of the component.
- /// </param>
- private void ForEachPropertyComponentSet(SerializableProperty property, Func<int, float> action)
- {
- switch (property.Type)
- {
- case SerializableProperty.FieldType.Vector2:
- {
- Vector2 value = new Vector2();
- for (int i = 0; i < 2; i++)
- value[i] = action(i);
- property.SetValue(value);
- }
- break;
- case SerializableProperty.FieldType.Vector3:
- {
- Vector3 value = new Vector3();
- for (int i = 0; i < 3; i++)
- value[i] = action(i);
- property.SetValue(value);
- }
- break;
- case SerializableProperty.FieldType.Vector4:
- {
- if (property.InternalType == typeof(Vector4))
- {
- Vector4 value = new Vector4();
- for (int i = 0; i < 4; i++)
- value[i] = action(i);
- property.SetValue(value);
- }
- else if (property.InternalType == typeof(Quaternion))
- {
- Quaternion value = new Quaternion();
- for (int i = 0; i < 4; i++)
- value[i] = action(i);
- property.SetValue(value);
- }
- }
- break;
- case SerializableProperty.FieldType.Color:
- {
- Color value = new Color();
- for (int i = 0; i < 4; i++)
- value[i] = action(i);
- property.SetValue(value);
- }
- break;
- case SerializableProperty.FieldType.Bool:
- {
- bool value = action(0) > 0.0f ? true : false;
- property.SetValue(value);
- }
- break;
- case SerializableProperty.FieldType.Int:
- {
- int value = (int)action(0);
- property.SetValue(value);
- }
- break;
- case SerializableProperty.FieldType.Float:
- {
- float value = action(0);
- property.SetValue(value);
- }
- break;
- }
- }
- #endregion
- #region Input callbacks
- /// <summary>
- /// Triggered when the user presses a mouse button.
- /// </summary>
- /// <param name="ev">Information about the mouse press event.</param>
- private void OnPointerPressed(PointerEvent ev)
- {
- guiCurveEditor.OnPointerPressed(ev);
- if (ev.button == PointerButton.Middle)
- {
- Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
- Vector2 curvePos;
- if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
- {
- dragStartPos = windowPos;
- isButtonHeld = true;
- }
- }
- }
- /// <summary>
- /// Triggered when the user moves the mouse.
- /// </summary>
- /// <param name="ev">Information about the mouse move event.</param>
- private void OnPointerMoved(PointerEvent ev)
- {
- guiCurveEditor.OnPointerMoved(ev);
- if (isButtonHeld)
- {
- Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
- int distance = Vector2I.Distance(dragStartPos, windowPos);
- if (distance >= DRAG_START_DISTANCE)
- {
- isDragInProgress = true;
- Cursor.Hide();
- Rect2I clipRect;
- clipRect.x = ev.ScreenPos.x - 2;
- clipRect.y = ev.ScreenPos.y - 2;
- clipRect.width = 4;
- clipRect.height = 4;
- Cursor.ClipToRect(clipRect);
- }
- }
- }
- /// <summary>
- /// Triggered when the user releases a mouse button.
- /// </summary>
- /// <param name="ev">Information about the mouse release event.</param>
- private void OnPointerReleased(PointerEvent ev)
- {
- if (isDragInProgress)
- {
- Cursor.Show();
- Cursor.ClipDisable();
- }
- isButtonHeld = false;
- isDragInProgress = false;
- guiCurveEditor.OnPointerReleased(ev);
- }
- /// <summary>
- /// Triggered when the user releases a keyboard button.
- /// </summary>
- /// <param name="ev">Information about the keyboard release event.</param>
- private void OnButtonUp(ButtonEvent ev)
- {
- guiCurveEditor.OnButtonUp(ev);
- }
- #endregion
- #region General callbacks
- /// <summary>
- /// Triggered by the field selector, when user selects a new curve field.
- /// </summary>
- /// <param name="path">Path of the selected curve field.</param>
- /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
- private void OnFieldAdded(string path, SerializableProperty.FieldType type)
- {
- // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
- string pathNoRoot = path.TrimStart('/');
- int separatorIdx = pathNoRoot.IndexOf("/");
- if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
- return;
- pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
- AddNewField(pathNoRoot, type);
- RecordState(pathNoRoot, 0.0f);
- ApplyClipChanges();
- }
- /// <summary>
- /// Triggered when the user moves or resizes the horizontal scrollbar.
- /// </summary>
- /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
- /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
- private void OnHorzScrollOrResize(float position, float size)
- {
- SetHorzScrollbarProperties(position, size);
- }
- /// <summary>
- /// Triggered when the user moves or resizes the vertical scrollbar.
- /// </summary>
- /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
- /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
- private void OnVertScrollOrResize(float position, float size)
- {
- SetVertScrollbarProperties(position, size);
- }
- /// <summary>
- /// Triggered when the user selects a new curve field.
- /// </summary>
- /// <param name="path">Path of the selected curve field.</param>
- private void OnFieldSelected(string path)
- {
- bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
- SelectField(path, additive);
- }
- /// <summary>
- /// Triggered when the user selects a new scene object or a resource.
- /// </summary>
- /// <param name="sceneObjects">Newly selected scene objects.</param>
- /// <param name="resourcePaths">Newly selected resources.</param>
- private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
- {
- // While recording allow other objects to be selected so the user can modify them
- if (state == State.Recording)
- return;
- UpdateSelectedSO(false);
- }
- /// <summary>
- /// Triggered when the user selects a new frame in the curve display.
- /// </summary>
- /// <param name="frameIdx">Index of the selected frame.</param>
- private void OnFrameSelected(int frameIdx)
- {
- SetCurrentFrame(frameIdx);
- PreviewFrame(currentFrameIdx);
- // HACK: Skip checking for record changes this frame, to give the preview a chance to update, otherwise
- // the changes would be detected any time a frame is delayed. A proper fix for this would be to force the
- // animation to be evaluated synchronously when PreviewFrame is called.
- delayRecord = true;
- }
- /// <summary>
- /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
- /// </summary>
- private void OnEventsChanged()
- {
- clipInfo.events = guiCurveEditor.Events;
- EditorApplication.SetProjectDirty();
- }
- #endregion
- }
- /// <summary>
- /// Drop down window that displays options used by the animation window.
- /// </summary>
- [DefaultSize(100, 50)]
- internal class AnimationOptions : DropDownWindow
- {
- /// <summary>
- /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
- /// use.
- /// </summary>
- /// <param name="parent">Animation window that this drop down window is a part of.</param>
- internal void Initialize(AnimationWindow parent)
- {
- GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
- fpsField.Value = parent.FPS;
- fpsField.OnChanged += x => { parent.FPS = x; };
-
- GUILayoutY vertLayout = GUI.AddLayoutY();
- vertLayout.AddFlexibleSpace();
- GUILayoutX contentLayout = vertLayout.AddLayoutX();
- contentLayout.AddFlexibleSpace();
- contentLayout.AddElement(fpsField);
- contentLayout.AddFlexibleSpace();
- vertLayout.AddFlexibleSpace();
- }
- }
- /// <summary>
- /// Raw data representing a single animation curve.
- /// </summary>
- class AnimationCurveState
- {
- public KeyFrame[] keyFrames;
- public TangentMode[] tangentModes;
- }
- /// <summary>
- /// Raw data representing a single animation clip state.
- /// </summary>
- class AnimationClipState
- {
- public Dictionary<string, AnimationCurveState[]> curves = new Dictionary<string, AnimationCurveState[]>();
- public AnimationEvent[] events;
- }
- /// <summary>
- /// Undo command used in the AnimationWindow.
- /// </summary>
- internal class AnimationUndo : UndoableCommand
- {
- private AnimationClipState prevClipState;
- private AnimationClipState clipState;
- public AnimationUndo(AnimationClipState prevClipState, AnimationClipState clipState)
- {
- this.prevClipState = prevClipState;
- this.clipState = clipState;
- }
- /// <inheritdoc/>
- protected override void Commit()
- {
- AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
- window?.ApplyClipState(clipState);
- }
- /// <inheritdoc/>
- protected override void Revert()
- {
- AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
- window?.ApplyClipState(prevClipState);
- }
- }
- /** @} */
- }
|