forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpriteUtility.cs
More file actions
637 lines (535 loc) · 25.7 KB
/
Copy pathSpriteUtility.cs
File metadata and controls
637 lines (535 loc) · 25.7 KB
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.IO;
using System.Linq;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using System.Collections.Generic;
using UnityEditor.Experimental.U2D;
using UnityEditor.U2D.Interface;
using UnityEngine.SceneManagement;
using UnityEngine.U2D.Interface;
using Object = UnityEngine.Object;
using UnityTexture2D = UnityEngine.Texture2D;
namespace UnityEditor
{
internal static class SpriteUtility
{
static class SpriteUtilityStrings
{
public static readonly GUIContent saveAnimDialogMessage = EditorGUIUtility.TrTextContent("Create a new animation for the game object '{0}':");
public static readonly GUIContent saveAnimDialogTitle = EditorGUIUtility.TrTextContent("Create New Animation");
public static readonly GUIContent saveAnimDialogName = EditorGUIUtility.TrTextContent("New Animation");
public static readonly GUIContent unableToFindSpriteRendererWarning = EditorGUIUtility.TrTextContent("There should be a SpriteRenderer in dragged object");
public static readonly GUIContent unableToAddSpriteRendererWarning = EditorGUIUtility.TrTextContent("Unable to add SpriteRenderer into Gameobject.");
public static readonly GUIContent failedToCreateAnimationError = EditorGUIUtility.TrTextContent("Failed to create animation for dragged object");
}
private static Material s_PreviewSpriteDefaultMaterial;
internal static Material previewSpriteDefaultMaterial
{
get
{
if (s_PreviewSpriteDefaultMaterial == null)
{
Shader shader = Shader.Find("Sprites/Default");
s_PreviewSpriteDefaultMaterial = new Material(shader);
}
return s_PreviewSpriteDefaultMaterial;
}
}
static List<Object> s_SceneDragObjects;
static DragType s_DragType;
enum DragType { NotInitialized, SpriteAnimation, CreateMultiple }
public delegate string ShowFileDialogDelegate(string title, string defaultName, string extension, string message, string defaultPath);
public static void OnSceneDrag(SceneView sceneView)
{
HandleSpriteSceneDrag(sceneView, new UnityEngine.U2D.Interface.Event(), DragAndDrop.objectReferences, DragAndDrop.paths, EditorUtility.SaveFilePanelInProject);
}
public static void HandleSpriteSceneDrag(SceneView sceneView, IEvent evt, Object[] objectReferences, string[] paths, ShowFileDialogDelegate saveFileDialog)
{
if (evt.type != EventType.DragUpdated && evt.type != EventType.DragPerform && evt.type != EventType.DragExited)
return;
// Return if any of the dragged objects are null, e.g. a MonoBehaviour without a managed instance
if (objectReferences.Any(obj => obj == null))
return;
// Regardless of EditorBehaviorMode or SceneView mode we don't handle if texture is dragged over a GO with renderer
if (objectReferences.Length == 1 && objectReferences[0] as UnityTexture2D != null)
{
GameObject go = HandleUtility.PickGameObject(evt.mousePosition, true);
if (go != null)
{
var renderer = go.GetComponent<Renderer>();
if (renderer != null && !(renderer is SpriteRenderer))
{
// There is an object where the cursor is
// and we are dragging a texture. Most likely user wants to
// assign texture to the GO
// Case 730444: Proceed only if the go has a renderer
CleanUp(true);
return;
}
}
}
switch (evt.type)
{
case (EventType.DragUpdated):
DragType newDragType = evt.alt ? DragType.CreateMultiple : DragType.SpriteAnimation;
if (s_DragType != newDragType || s_SceneDragObjects == null) // Either this is first time we are here OR evt.alt changed during drag
{
if (!ExistingAssets(objectReferences) && PathsAreValidTextures(paths)) // External drag with images that are not in the project
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
s_SceneDragObjects = new List<Object>();
s_DragType = newDragType;
}
else // Internal drag with assets from project
{
List<Sprite> assets = GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type);
if (assets.Count == 0)
return;
if (s_DragType != DragType.NotInitialized) // evt.alt changed during drag, so we need to cleanup and start over
CleanUp(true);
s_DragType = newDragType;
CreateSceneDragObjects(assets, sceneView);
IgnoreForRaycasts(s_SceneDragObjects);
}
}
PositionSceneDragObjects(s_SceneDragObjects, sceneView, evt.mousePosition);
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
evt.Use();
break;
case (EventType.DragPerform):
List<Sprite> sprites = GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type);
if (sprites.Count > 0 && s_SceneDragObjects != null)
{
// Store current undoIndex to undo all operations done if any part of sprite creation fails
int undoIndex = Undo.GetCurrentGroup();
// For external drags, we have delayed all creation to DragPerform because only now we have the imported sprite assets
if (s_SceneDragObjects.Count == 0)
{
CreateSceneDragObjects(sprites, sceneView);
PositionSceneDragObjects(s_SceneDragObjects, sceneView, evt.mousePosition);
}
foreach (GameObject dragGO in s_SceneDragObjects)
{
dragGO.hideFlags = HideFlags.None;
// When in e.g Prefab Mode ensure to reparent dragged objects under the prefab root
if (sceneView.customParentForDraggedObjects != null)
dragGO.transform.SetParent(sceneView.customParentForDraggedObjects, true);
Undo.RegisterCreatedObjectUndo(dragGO, "Create Sprite");
EditorUtility.SetDirty(dragGO);
}
bool createGameObject = true;
if (s_DragType == DragType.SpriteAnimation && sprites.Count > 1)
{
createGameObject = AddAnimationToGO((GameObject)s_SceneDragObjects[0], sprites.ToArray(), saveFileDialog);
}
if (createGameObject)
{
Selection.objects = s_SceneDragObjects.ToArray();
}
else
{
// Revert all Create Sprite actions if animation failed to be created or was cancelled
Undo.RevertAllDownToGroup(undoIndex);
}
CleanUp(!createGameObject);
evt.Use();
}
break;
case EventType.DragExited:
if (s_SceneDragObjects != null)
{
CleanUp(true);
evt.Use();
}
break;
}
}
private static void IgnoreForRaycasts(List<Object> objects)
{
List<Transform> ignoredTransforms = new List<Transform>();
foreach (GameObject gameObject in objects)
ignoredTransforms.AddRange(gameObject.GetComponentsInChildren<Transform>());
HandleUtility.ignoreRaySnapObjects = ignoredTransforms.ToArray();
}
private static void PositionSceneDragObjects(List<Object> objects, SceneView sceneView, Vector2 mousePosition)
{
Vector3 position = Vector3.zero;
position = HandleUtility.GUIPointToWorldRay(mousePosition).GetPoint(10);
if (sceneView.in2DMode)
{
position.z = 0f;
}
else
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
object hit = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(mousePosition));
if (hit != null)
{
RaycastHit rh = (RaycastHit)hit;
position = rh.point;
}
}
if (Selection.activeGameObject != null)
{
Grid grid = Selection.activeGameObject.GetComponentInParent<Grid>();
if (grid != null)
{
Vector3Int cell = grid.WorldToCell(position);
position = grid.GetCellCenterWorld(cell);
}
}
foreach (GameObject gameObject in objects)
{
gameObject.transform.position = position;
}
}
private static void CreateSceneDragObjects(List<Sprite> sprites, SceneView sceneView)
{
if (s_SceneDragObjects == null)
s_SceneDragObjects = new List<Object>();
if (s_DragType == DragType.CreateMultiple)
{
foreach (Sprite sprite in sprites)
s_SceneDragObjects.Add(CreateDragGO(sprite, Vector3.zero, sceneView));
}
else
{
s_SceneDragObjects.Add(CreateDragGO(sprites[0], Vector3.zero, sceneView));
}
}
private static void CleanUp(bool deleteTempSceneObject)
{
if (s_SceneDragObjects != null)
{
if (deleteTempSceneObject)
{
foreach (GameObject gameObject in s_SceneDragObjects)
Object.DestroyImmediate(gameObject, false);
}
s_SceneDragObjects.Clear();
s_SceneDragObjects = null;
}
HandleUtility.ignoreRaySnapObjects = null;
s_DragType = DragType.NotInitialized;
}
static bool CreateAnimation(GameObject gameObject, Object[] frames, ShowFileDialogDelegate saveFileDialog)
{
saveFileDialog = saveFileDialog ?? EditorUtility.SaveFilePanelInProject;
// Use same name compare as when we sort in the backend: See AssetDatabase.cpp: SortChildren
System.Array.Sort(frames, (a, b) => EditorUtility.NaturalCompare(a.name, b.name));
Animator animator = AnimationWindowUtility.EnsureActiveAnimationPlayer(gameObject)
? AnimationWindowUtility.GetClosestAnimatorInParents(gameObject.transform)
: null;
bool createSuccess = animator != null;
if (animator != null)
{
// Go forward with presenting user a save clip dialog
string message = string.Format(SpriteUtilityStrings.saveAnimDialogMessage.text, gameObject.name);
string newClipDirectory = ProjectWindowUtil.GetActiveFolderPath();
string newClipPath = saveFileDialog(SpriteUtilityStrings.saveAnimDialogTitle.text, SpriteUtilityStrings.saveAnimDialogName.text, "anim", message, newClipDirectory);
if (string.IsNullOrEmpty(newClipPath))
{
Undo.ClearUndo(animator);
Object.DestroyImmediate(animator);
return false;
}
else
{
AnimationClip newClip = AnimationWindowUtility.CreateNewClipAtPath(newClipPath);
if (newClip != null)
{
AddSpriteAnimationToClip(newClip, frames);
createSuccess = AnimationWindowUtility.AddClipToAnimatorComponent(animator, newClip);
}
}
}
if (createSuccess == false)
Debug.LogError(SpriteUtilityStrings.failedToCreateAnimationError.text);
return createSuccess;
}
static void AddSpriteAnimationToClip(AnimationClip newClip, Object[] frames)
{
// TODO Default framerate be exposed to user?
newClip.frameRate = 12;
// Add keyframes
ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frames.Length];
for (int i = 0; i < keyframes.Length; i++)
{
keyframes[i] = new ObjectReferenceKeyframe();
keyframes[i].value = RemapObjectToSprite(frames[i]);
keyframes[i].time = i / newClip.frameRate;
}
// Create binding
EditorCurveBinding curveBinding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite");
// Save curve to clip
AnimationUtility.SetObjectReferenceCurve(newClip, (EditorCurveBinding)curveBinding, keyframes);
}
public static List<Sprite> GetSpriteFromPathsOrObjects(Object[] objects, string[] paths, EventType currentEventType)
{
List<Sprite> result = new List<Sprite>();
foreach (Object obj in objects)
{
if (AssetDatabase.Contains(obj))
{
if (obj is Sprite)
result.Add(obj as Sprite);
else if (obj is UnityTexture2D)
result.AddRange(TextureToSprites(obj as UnityTexture2D));
}
}
// Fix case 742896. If any of the drag objects is already in the AssetDatabase, means we don't have to handle external drags.
// Fix case 857231. We only handle external drag if default behaviour mode is 2D
if (!ExistingAssets(objects) && currentEventType == EventType.DragPerform && EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D)
{
HandleExternalDrag(paths, true, ref result);
}
return result;
}
public static bool ExistingAssets(Object[] objects)
{
foreach (Object obj in objects)
{
if (AssetDatabase.Contains(obj))
return true;
}
return false;
}
private static void HandleExternalDrag(string[] paths, bool perform, ref List<Sprite> result)
{
foreach (var path in paths)
{
if (!ValidPathForTextureAsset(path))
continue;
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (!perform)
continue;
var newPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine("Assets", FileUtil.GetLastPathNameComponent(path)));
if (newPath.Length <= 0)
continue;
FileUtil.CopyFileOrDirectory(path, newPath);
ForcedImportFor(newPath);
Sprite defaultSprite = GenerateDefaultSprite(AssetDatabase.LoadMainAssetAtPath(newPath) as UnityTexture2D);
if (defaultSprite != null)
result.Add(defaultSprite);
}
}
private static bool PathsAreValidTextures(string[] paths)
{
if (paths == null || paths.Length == 0)
return false;
foreach (var path in paths)
{
if (!ValidPathForTextureAsset(path))
return false;
}
return true;
}
private static void ForcedImportFor(string newPath)
{
try
{
AssetDatabase.StartAssetEditing();
AssetDatabase.ImportAsset(newPath);
}
finally
{
AssetDatabase.StopAssetEditing();
}
}
private static Sprite GenerateDefaultSprite(UnityTexture2D texture)
{
string assetPath = AssetDatabase.GetAssetPath(texture);
TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
if (textureImporter == null) // could be DDS importer or other non-TextureImporter type
return null;
if (textureImporter.textureType != TextureImporterType.Sprite)
return null;
if (textureImporter.spriteImportMode == SpriteImportMode.None)
{
textureImporter.spriteImportMode = SpriteImportMode.Single;
AssetDatabase.WriteImportSettingsIfDirty(assetPath);
ForcedImportFor(assetPath);
}
Object firstSprite = null;
firstSprite = AssetDatabase.LoadAllAssetsAtPath(assetPath).FirstOrDefault(t => t is Sprite);
return firstSprite as Sprite;
}
public static GameObject CreateDragGO(Sprite frame, Vector3 position, SceneView sceneView)
{
string name = string.IsNullOrEmpty(frame.name) ? "Sprite" : frame.name;
name = GameObjectUtility.GetUniqueNameForSibling(null, name);
GameObject go = new GameObject(name);
SpriteRenderer spriteRenderer = go.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = frame;
go.transform.position = position;
go.hideFlags = HideFlags.HideAndDontSave;
// Ensure that the dragged gameobjects gets the correct scene culling mask so it can be rendered in the SceneView (when the SceneView camera is culling on a custom scene)
if (sceneView.customScene.IsValid())
SceneManager.MoveGameObjectToScene(go, sceneView.customScene);
return go;
}
public static bool AddAnimationToGO(GameObject go, Sprite[] frames, ShowFileDialogDelegate saveFileDialog)
{
SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>();
if (spriteRenderer == null)
{
Debug.LogWarning(SpriteUtilityStrings.unableToFindSpriteRendererWarning.text);
spriteRenderer = go.AddComponent<SpriteRenderer>();
if (spriteRenderer == null)
{
Debug.LogWarning(SpriteUtilityStrings.unableToAddSpriteRendererWarning.text);
return false;
}
}
spriteRenderer.sprite = frames[0];
return CreateAnimation(go, frames, saveFileDialog);
}
public static GameObject DropSpriteToSceneToCreateGO(Sprite sprite, Vector3 position)
{
GameObject go = new GameObject(string.IsNullOrEmpty(sprite.name) ? "Sprite" : sprite.name);
SpriteRenderer spriteRenderer = go.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = sprite;
go.transform.position = position;
Selection.activeObject = go;
return go;
}
public static Sprite RemapObjectToSprite(Object obj)
{
if (obj is Sprite)
return (Sprite)obj;
if (obj is UnityTexture2D)
{
Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(obj));
for (int i = 0; i < assets.Length; i++)
{
if (assets[i].GetType() == typeof(Sprite))
return assets[i] as Sprite;
}
}
return null;
}
public static List<Sprite> TextureToSprites(UnityTexture2D tex)
{
Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex));
List<Sprite> result = new List<Sprite>();
for (int i = 0; i < assets.Length; i++)
{
if (assets[i].GetType() == typeof(Sprite))
result.Add(assets[i] as Sprite);
}
if (result.Count > 0)
return result;
Sprite defaultSprite = GenerateDefaultSprite(tex);
if (defaultSprite != null)
result.Add(defaultSprite);
return result;
}
public static Sprite TextureToSprite(UnityTexture2D tex)
{
List<Sprite> sprites = TextureToSprites(tex);
if (sprites.Count > 0)
return sprites[0];
return null;
}
private static bool ValidPathForTextureAsset(string path)
{
string ext = FileUtil.GetPathExtension(path).ToLower();
return
ext == "jpg" ||
ext == "jpeg" ||
ext == "tif" ||
ext == "tiff" ||
ext == "tga" ||
ext == "gif" ||
ext == "png" ||
ext == "psd" ||
ext == "bmp" ||
ext == "iff" ||
ext == "pict" ||
ext == "pic" ||
ext == "pct" ||
ext == "exr" ||
ext == "hdr";
}
public static UnityTexture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height)
{
return RenderStaticPreview(sprite, color, width, height, Matrix4x4.identity);
}
public static UnityTexture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height, Matrix4x4 transform)
{
if (sprite == null)
return null;
PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)sprite.rect.width, (int)sprite.rect.height, ref width, ref height);
SavedRenderTargetState savedRTState = new SavedRenderTargetState();
RenderTexture tmp = RenderTexture.GetTemporary(width, height, 0, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR));
RenderTexture.active = tmp;
GL.Clear(true, true, new Color(0f, 0f, 0f, 0.1f));
previewSpriteDefaultMaterial.mainTexture = sprite.texture;
previewSpriteDefaultMaterial.SetPass(0);
RenderSpriteImmediate(sprite, color, transform);
UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.ARGB32, false);
copy.hideFlags = HideFlags.HideAndDontSave;
copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
copy.Apply();
RenderTexture.ReleaseTemporary(tmp);
savedRTState.Restore();
return copy;
}
internal static void RenderSpriteImmediate(Sprite sprite, Color color, Matrix4x4 transform)
{
float spriteWidth = sprite.rect.width;
float spriteHeight = sprite.rect.height;
float pixelsToUnits = sprite.rect.width / sprite.bounds.size.x;
Vector2[] vertices = sprite.vertices;
Vector2[] uvs = sprite.uv;
ushort[] triangles = sprite.triangles;
Vector2 pivot = sprite.pivot;
GL.PushMatrix();
GL.LoadOrtho();
GL.Begin(GL.TRIANGLES);
for (int i = 0; i < sprite.triangles.Length; ++i)
{
ushort index = triangles[i];
Vector2 spriteVertex = vertices[index];
Vector2 uv = uvs[index];
Vector3 vertex = new Vector3(spriteVertex.x, spriteVertex.y, 0);
vertex = transform.MultiplyPoint(vertex);
vertex.x = (vertex.x * pixelsToUnits + pivot.x) / spriteWidth;
vertex.y = (vertex.y * pixelsToUnits + pivot.y) / spriteHeight;
GL.Color(color);
GL.TexCoord(new Vector3(uv.x, uv.y, 0));
GL.Vertex3(vertex.x, vertex.y, vertex.z);
}
GL.End();
GL.PopMatrix();
}
public static UnityTexture2D CreateTemporaryDuplicate(UnityTexture2D original, int width, int height)
{
if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original)
return null;
RenderTexture save = RenderTexture.active;
var savedViewport = ShaderUtil.rawViewportRect;
RenderTexture tmp = RenderTexture.GetTemporary(
width,
height,
0,
SystemInfo.GetGraphicsFormat(DefaultFormat.LDR));
Graphics.Blit(original, tmp);
RenderTexture.active = tmp;
// If the user system doesn't support this texture size, force it to use mipmap
bool forceUseMipMap = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize;
UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || forceUseMipMap);
copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
copy.Apply();
RenderTexture.ReleaseTemporary(tmp);
EditorGUIUtility.SetRenderTextureNoViewport(save);
ShaderUtil.rawViewportRect = savedViewport;
copy.alphaIsTransparency = original.alphaIsTransparency;
return copy;
}
}
}