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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Unity.VisualScripting
{
    public abstract class StateTransitionWidget<TStateTransition> : NodeWidget<StateCanvas, TStateTransition>, IStateTransitionWidget
        where TStateTransition : class, IStateTransition
    {
        protected StateTransitionWidget(StateCanvas canvas, TStateTransition transition) : base(canvas, transition) { }


        #region Model

        protected TStateTransition transition => element;

        protected IStateTransitionDebugData transitionDebugData => GetDebugData<IStateTransitionDebugData>();

        private StateTransitionDescription description;

        private StateTransitionAnalysis analysis => transition.Analysis<StateTransitionAnalysis>(context);

        protected override void CacheDescription()
        {
            description = transition.Description<StateTransitionDescription>();

            label.text = description.label;
            label.image = description.icon?[IconSize.Small];
            label.tooltip = description.tooltip;

            if (!revealLabel)
            {
                label.tooltip = label.text + ": " + label.tooltip;
            }

            Reposition();
        }

        #endregion

        #region Lifecycle

        public override void BeforeFrame()
        {
            base.BeforeFrame();

            if (showDroplets)
            {
                GraphGUI.UpdateDroplets(canvas, droplets, transitionDebugData.lastBranchFrame, ref lastBranchTime, ref dropTime);
            }

            if (currentInnerWidth != targetInnerWidth)
            {
                Reposition();
            }
        }

        #endregion


        #region Contents

        private GUIContent label { get; } = new GUIContent();

        #endregion


        #region Positioning

        private readonly List<IStateTransition> siblingStateTransitions = new List<IStateTransition>();

        private Rect sourcePosition;

        private Rect destinationPosition;

        private Edge sourceEdge;

        private Edge entryEdge;

        private Edge exitEdge;

        private Edge destinationEdge;

        private Vector2 sourceEdgeCenter;

        private Vector2 entryEdgeCenter;

        private Vector2 exitEdgeCenter;

        private Vector2 destinationEdgeCenter;

        private Vector2 middle;

        private Rect _position;

        private Rect _clippingPosition;

        private float targetInnerWidth;

        private float currentInnerWidth;

        private bool revealInitialized;

        private float minBend
        {
            get
            {
                if (transition.source != transition.destination)
                {
                    return 15;
                }
                else
                {
                    return (middle.y - canvas.Widget(transition.source).position.center.y) / 2;
                }
            }
        }

        private float relativeBend => 1 / 4f;

        Edge IStateTransitionWidget.sourceEdge => sourceEdge;

        public override IEnumerable<IWidget> positionDependencies
        {
            get
            {
                yield return canvas.Widget(transition.source);
                yield return canvas.Widget(transition.destination);
            }
        }

        public override IEnumerable<IWidget> positionDependers
        {
            get
            {
                // Return all sibling transitions. This is an asymetrical dependency / depender
                // relation (because the siblings are not included in the dependers) to force
                // repositioning of siblings while avoiding stack overflow.

                foreach (var graphTransition in canvas.graph.transitions)
                {
                    var current = transition == graphTransition;

                    var analog =
                        transition.source == graphTransition.source &&
                        transition.destination == graphTransition.destination;

                    var inverted =
                        transition.source == graphTransition.destination &&
                        transition.destination == graphTransition.source;

                    if (!current && (analog || inverted))
                    {
                        var widget = canvas.Widget(graphTransition);

                        if (widget.isPositionValid) // Avoid stack overflow
                        {
                            yield return widget;
                        }
                    }
                }
            }
        }

        public Rect iconPosition { get; private set; }

        public Rect clipPosition { get; private set; }

        public Rect labelInnerPosition { get; private set; }

        public override Rect position
        {
            get { return _position; }
            set { }
        }

        public override Rect clippingPosition => _clippingPosition;

        public override void CachePositionFirstPass()
        {
            // Calculate the size immediately, because other transitions will rely on it for positioning

            targetInnerWidth = Styles.eventIcon.fixedWidth;

            var labelWidth = Styles.label.CalcSize(label).x;
            var labelHeight = EditorGUIUtility.singleLineHeight;

            if (revealLabel)
            {
                targetInnerWidth += Styles.spaceAroundIcon;
                targetInnerWidth += labelWidth;
            }

            if (!revealInitialized)
            {
                currentInnerWidth = targetInnerWidth;
                revealInitialized = true;
            }

            currentInnerWidth = Mathf.Lerp(currentInnerWidth, targetInnerWidth, canvas.repaintDeltaTime * Styles.revealSpeed);

            if (Mathf.Abs(targetInnerWidth - currentInnerWidth) < 1)
            {
                currentInnerWidth = targetInnerWidth;
            }

            var innerWidth = currentInnerWidth;
            var innerHeight = labelHeight;

            var edgeSize = InnerToEdgePosition(new Rect(0, 0, innerWidth, innerHeight)).size;
            var edgeWidth = edgeSize.x;
            var edgeHeight = edgeSize.y;

            _position.width = edgeWidth;
            _position.height = edgeHeight;
        }

        public override void CachePosition()
        {
            var innerWidth = innerPosition.width;
            var innerHeight = innerPosition.height;
            var edgeWidth = edgePosition.width;
            var edgeHeight = edgePosition.height;
            var labelWidth = Styles.label.CalcSize(label).x;
            var labelHeight = EditorGUIUtility.singleLineHeight;

            sourcePosition = canvas.Widget(transition.source).position;
            destinationPosition = canvas.Widget(transition.destination).position;

            Vector2 sourceClosestPoint;
            Vector2 destinationClosestPoint;
            LudiqGUIUtility.ClosestPoints(sourcePosition, destinationPosition, out sourceClosestPoint, out destinationClosestPoint);

            if (transition.destination != transition.source)
            {
                GraphGUI.GetConnectionEdge
                    (
                        sourceClosestPoint,
                        destinationClosestPoint,
                        out sourceEdge,
                        out destinationEdge
                    );
            }
            else
            {
                sourceEdge = Edge.Right;
                destinationEdge = Edge.Left;
            }

            sourceEdgeCenter = sourcePosition.GetEdgeCenter(sourceEdge);
            destinationEdgeCenter = destinationPosition.GetEdgeCenter(destinationEdge);

            siblingStateTransitions.Clear();

            var siblingIndex = 0;

            // Assign one common axis for transition for all siblings,
            // regardless of their inversion. The axis is arbitrarily
            // chosen as the axis for the first transition.
            var assignedTransitionAxis = false;
            var transitionAxis = Vector2.zero;

            foreach (var graphTransition in canvas.graph.transitions)
            {
                var current = transition == graphTransition;

                var analog =
                    transition.source == graphTransition.source &&
                    transition.destination == graphTransition.destination;

                var inverted =
                    transition.source == graphTransition.destination &&
                    transition.destination == graphTransition.source;

                if (current)
                {
                    siblingIndex = siblingStateTransitions.Count;
                }

                if (current || analog || inverted)
                {
                    if (!assignedTransitionAxis)
                    {
                        var siblingStateTransitionDrawer = canvas.Widget<IStateTransitionWidget>(graphTransition);

                        transitionAxis = siblingStateTransitionDrawer.sourceEdge.Normal();

                        assignedTransitionAxis = true;
                    }

                    siblingStateTransitions.Add(graphTransition);
                }
            }

            // Fix the edge case where the source and destination perfectly overlap

            if (transitionAxis == Vector2.zero)
            {
                transitionAxis = Vector2.right;
            }

            // Calculate the spread axis and origin for the set of siblings

            var spreadAxis = transitionAxis.Perpendicular1().Abs();
            var spreadOrigin = (sourceEdgeCenter + destinationEdgeCenter) / 2;

            if (transition.source == transition.destination)
            {
                spreadAxis = Vector2.up;
                spreadOrigin = sourcePosition.GetEdgeCenter(Edge.Bottom) - Vector2.down * 10;
            }

            if (BoltCore.Configuration.developerMode && BoltCore.Configuration.debug)
            {
                Handles.BeginGUI();
                Handles.color = Color.yellow;
                Handles.DrawLine(spreadOrigin + spreadAxis * -1000, spreadOrigin + spreadAxis * 1000);
                Handles.EndGUI();
            }

            // Calculate the offset of the current sibling by iterating over its predecessors

            var spreadOffset = 0f;
            var previousSpreadSize = 0f;

            for (var i = 0; i <= siblingIndex; i++)
            {
                var siblingSize = canvas.Widget<IStateTransitionWidget>(siblingStateTransitions[i]).outerPosition.size;
                var siblingSizeProjection = GraphGUI.SizeProjection(siblingSize, spreadOrigin, spreadAxis);
                spreadOffset += previousSpreadSize / 2 + siblingSizeProjection / 2;
                previousSpreadSize = siblingSizeProjection;
            }

            if (transition.source != transition.destination)
            {
                // Calculate the total spread size to center the sibling set

                var totalSpreadSize = 0f;

                for (var i = 0; i < siblingStateTransitions.Count; i++)
                {
                    var siblingSize = canvas.Widget<IStateTransitionWidget>(siblingStateTransitions[i]).outerPosition.size;
                    var siblingSizeProjection = GraphGUI.SizeProjection(siblingSize, spreadOrigin, spreadAxis);
                    totalSpreadSize += siblingSizeProjection;
                }

                spreadOffset -= totalSpreadSize / 2;
            }

            // Finally, calculate the positions

            middle = spreadOrigin + spreadOffset * spreadAxis;

            var edgeX = middle.x - edgeWidth / 2;
            var edgeY = middle.y - edgeHeight / 2;

            _position = new Rect
                (
                edgeX,
                edgeY,
                edgeWidth,
                edgeHeight
                ).PixelPerfect();

            var innerX = innerPosition.x;
            var innerY = innerPosition.y;

            _clippingPosition = _position.Encompass(sourceEdgeCenter).Encompass(destinationEdgeCenter);

            if (transition.source != transition.destination)
            {
                entryEdge = destinationEdge;
                exitEdge = sourceEdge;
            }
            else
            {
                entryEdge = sourceEdge;
                exitEdge = destinationEdge;
            }

            entryEdgeCenter = edgePosition.GetEdgeCenter(entryEdge);
            exitEdgeCenter = edgePosition.GetEdgeCenter(exitEdge);

            var x = innerX;

            iconPosition = new Rect
                (
                x,
                innerY,
                Styles.eventIcon.fixedWidth,
                Styles.eventIcon.fixedHeight
                ).PixelPerfect();

            x += iconPosition.width;

            var clipWidth = innerWidth - (x - innerX);

            clipPosition = new Rect
                (
                x,
                edgeY,
                clipWidth,
                edgeHeight
                ).PixelPerfect();

            labelInnerPosition = new Rect
                (
                Styles.spaceAroundIcon,
                innerY - edgeY,
                labelWidth,
                labelHeight
                ).PixelPerfect();
        }

        #endregion


        #region Drawing

        protected virtual NodeColorMix baseColor => NodeColor.Gray;

        protected override NodeColorMix color
        {
            get
            {
                if (transitionDebugData.runtimeException != null)
                {
                    return NodeColor.Red;
                }

                var color = baseColor;

                if (analysis.warnings.Count > 0)
                {
                    var mostSevereWarning = Warning.MostSevereLevel(analysis.warnings);

                    switch (mostSevereWarning)
                    {
                        case WarningLevel.Error:
                            color = NodeColor.Red;

                            break;

                        case WarningLevel.Severe:
                            color = NodeColor.Orange;

                            break;

                        case WarningLevel.Caution:
                            color = NodeColor.Yellow;

                            break;
                    }
                }

                if (EditorApplication.isPlaying)
                {
                    if (EditorApplication.isPaused)
                    {
                        if (EditorTimeBinding.frame == transitionDebugData.lastBranchFrame)
                        {
                            color = NodeColor.Blue;
                        }
                    }
                    else
                    {
                        color.blue = Mathf.Lerp(1, 0, (EditorTimeBinding.time - transitionDebugData.lastBranchTime) / StateWidget<IState>.Styles.enterFadeDuration);
                    }
                }

                return color;
            }
        }

        protected override NodeShape shape => NodeShape.Hex;

        private bool revealLabel
        {
            get
            {
                switch (BoltState.Configuration.transitionsReveal)
                {
                    case StateRevealCondition.Always:

                        return true;
                    case StateRevealCondition.Never:

                        return false;
                    case StateRevealCondition.OnHover:

                        return isMouseOver;
                    case StateRevealCondition.OnHoverWithAlt:

                        return isMouseOver && e.alt;
                    case StateRevealCondition.WhenSelected:

                        return selection.Contains(transition);
                    case StateRevealCondition.OnHoverOrSelected:

                        return isMouseOver || selection.Contains(transition);
                    case StateRevealCondition.OnHoverWithAltOrSelected:

                        return isMouseOver && e.alt || selection.Contains(transition);
                    default:

                        throw new UnexpectedEnumValueException<StateRevealCondition>(BoltState.Configuration.transitionsReveal);
                }
            }
        }

        private bool revealedLabel;

        private void CheckReveal()
        {
            var revealLabel = this.revealLabel;

            if (revealLabel != revealedLabel)
            {
                Reposition();
            }

            revealedLabel = revealLabel;
        }

        protected override bool dim
        {
            get
            {
                var dim = BoltCore.Configuration.dimInactiveNodes && !(transition.source.Analysis<StateAnalysis>(context).isEntered && analysis.isTraversed);

                if (isMouseOver || isSelected)
                {
                    dim = false;
                }

                return dim;
            }
        }

        public override void DrawForeground()
        {
            BeginDim();

            base.DrawForeground();

            GUI.Label(iconPosition, label, Styles.eventIcon);

            GUI.BeginClip(clipPosition);

            GUI.Label(labelInnerPosition, label, invertForeground ? Styles.labelInverted : Styles.label);

            GUI.EndClip();

            EndDim();

            CheckReveal();
        }

        public override void DrawBackground()
        {
            BeginDim();

            base.DrawBackground();

            DrawConnection();

            if (showDroplets)
            {
                DrawDroplets();
            }

            EndDim();
        }

        private void DrawConnection()
        {
            GraphGUI.DrawConnectionArrow(Color.white, sourceEdgeCenter, entryEdgeCenter, sourceEdge, entryEdge, relativeBend, minBend);

            if (BoltState.Configuration.transitionsEndArrow)
            {
                GraphGUI.DrawConnectionArrow(Color.white, exitEdgeCenter, destinationEdgeCenter, exitEdge, destinationEdge, relativeBend, minBend);
            }
            else
            {
                GraphGUI.DrawConnection(Color.white, exitEdgeCenter, destinationEdgeCenter, exitEdge, destinationEdge, null, Vector2.zero, relativeBend, minBend);
            }
        }

        #endregion


        #region Selecting

        public override bool canSelect => true;

        #endregion


        #region Dragging

        public override bool canDrag => false;

        protected override bool snapToGrid => false;

        #endregion


        #region Deleting

        public override bool canDelete => true;

        #endregion


        #region Droplets

        private readonly List<float> droplets = new List<float>();

        private float dropTime;

        private float lastBranchTime;

        protected virtual bool showDroplets => BoltState.Configuration.animateTransitions;

        protected virtual Vector2 GetDropletSize()
        {
            return BoltFlow.Icons.valuePortConnected?[12].Size() ?? 12 * Vector2.one;
        }

        protected virtual void DrawDroplet(Rect position)
        {
            GUI.DrawTexture(position, BoltFlow.Icons.valuePortConnected?[12]);
        }

        private void DrawDroplets()
        {
            foreach (var droplet in droplets)
            {
                Vector2 position;

                if (droplet < 0.5f)
                {
                    var t = droplet / 0.5f;
                    position = GraphGUI.GetPointOnConnection(t, sourceEdgeCenter, entryEdgeCenter, sourceEdge, entryEdge, relativeBend, minBend);
                }
                else
                {
                    var t = (droplet - 0.5f) / 0.5f;
                    position = GraphGUI.GetPointOnConnection(t, exitEdgeCenter, destinationEdgeCenter, exitEdge, destinationEdge, relativeBend, minBend);
                }

                var size = GetDropletSize();

                using (LudiqGUI.color.Override(Color.white))
                {
                    DrawDroplet(new Rect(position.x - size.x / 2, position.y - size.y / 2, size.x, size.y));
                }
            }
        }

        #endregion


        public static class Styles
        {
            static Styles()
            {
                label = new GUIStyle(BoltCore.Styles.nodeLabel);
                label.alignment = TextAnchor.MiddleCenter;
                label.imagePosition = ImagePosition.TextOnly;

                labelInverted = new GUIStyle(label);
                labelInverted.normal.textColor = ColorPalette.unityBackgroundDark;

                eventIcon = new GUIStyle();
                eventIcon.imagePosition = ImagePosition.ImageOnly;
                eventIcon.fixedHeight = 16;
                eventIcon.fixedWidth = 16;
            }

            public static readonly GUIStyle label;

            public static readonly GUIStyle labelInverted;

            public static readonly GUIStyle eventIcon;

            public static readonly float spaceAroundIcon = 5;

            public static readonly float revealSpeed = 15;
        }
    }
}