move all sources to ftsources

This commit is contained in:
2016-10-06 21:46:53 +07:00
parent 1e136a0490
commit e152d55bcf
58 changed files with 185 additions and 452 deletions

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 21aa39328267d446b943c01ecb384e13
folderAsset: yes
timeCreated: 1455736806
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: c649686f2102d4b03a8b167b86430eec
folderAsset: yes
timeCreated: 1455736963
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: a45d7db78d482494d8456892d9007d32
folderAsset: yes
timeCreated: 1455736975
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 518cad4150eaf4133881bf2a4bae81ed
folderAsset: yes
timeCreated: 1472790046
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,153 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace FlashTools.Internal {
[CustomEditor(typeof(SwfAsset)), CanEditMultipleObjects]
public class SwfAssetEditor : Editor {
List<SwfAsset> _assets = new List<SwfAsset>();
//
//
//
static SwfSettings _settingsHolder = null;
static SwfSettings GetSettingsHolder() {
if ( !_settingsHolder ) {
_settingsHolder = SwfEditorUtils.GetSettingsHolder();
}
return _settingsHolder;
}
//
//
//
static void RevertOverriddenSettings(SwfAsset asset) {
asset.Overridden = asset.Settings;
}
static void OverriddenSettingsToDefault(SwfAsset asset) {
asset.Overridden = GetSettingsHolder().Settings;
}
static void ApplyOverriddenSettings(SwfAsset asset) {
asset.Settings = asset.Overridden;
ReconvertAsset(asset);
}
static void ReconvertAsset(SwfAsset asset) {
asset.Converting = new SwfAsset.ConvertingState();
AssetDatabase.ImportAsset(
AssetDatabase.GetAssetPath(asset));
}
//
//
//
void AllAssetsForeach(System.Action<SwfAsset> act) {
foreach ( var asset in _assets ) {
act(asset);
}
}
void AllOverriddenSettingsToDefault() {
AllAssetsForeach(p => OverriddenSettingsToDefault(p));
}
void RevertAllOverriddenSettings() {
AllAssetsForeach(p => RevertOverriddenSettings(p));
}
void ApplyAllOverriddenSettings() {
AllAssetsForeach(p => ApplyOverriddenSettings(p));
}
void ReconvertAllAsset() {
AllAssetsForeach(p => ReconvertAsset(p));
}
//
//
//
void ShowUnappliedDialog() {
var unapplied = _assets
.Where(p => !p.Settings.CheckEquals(p.Overridden))
.ToArray();
if ( unapplied.Length > 0 ) {
var title =
"Unapplied swf asset settings";
var message = unapplied.Length == 1
? string.Format(
"Unapplied swf asset settings for '{0}'",
AssetDatabase.GetAssetPath(unapplied[0]))
: string.Format(
"Unapplied multiple({0}) swf asset settings",
unapplied.Length);
if ( EditorUtility.DisplayDialog(title, message, "Apply", "Revert") ) {
ApplyAllOverriddenSettings();
} else {
RevertAllOverriddenSettings();
}
}
}
void DrawGUISettingsControls() {
var prop = SwfEditorUtils.GetPropertyByName(serializedObject, "Overridden");
if ( prop.isExpanded ) {
GUILayout.BeginHorizontal();
{
if ( GUILayout.Button("Reconvert") ) {
ReconvertAllAsset();
}
GUILayout.FlexibleSpace();
var default_settings = GetSettingsHolder().Settings;
SwfEditorUtils.DoWithEnabledGUI(
_assets.Any(p => !p.Overridden.CheckEquals(default_settings)), () => {
if ( GUILayout.Button("Default") ) {
AllOverriddenSettingsToDefault();
}
});
SwfEditorUtils.DoWithEnabledGUI(
_assets.Any(p => !p.Overridden.CheckEquals(p.Settings)), () => {
if ( GUILayout.Button("Revert") ) {
RevertAllOverriddenSettings();
}
if ( GUILayout.Button("Apply") ) {
ApplyAllOverriddenSettings();
}
});
}
GUILayout.EndHorizontal();
}
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void OnEnable() {
_assets = targets.OfType<SwfAsset>().ToList();
}
void OnDisable() {
ShowUnappliedDialog();
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawDefaultInspector();
DrawGUISettingsControls();
if ( GUI.changed ) {
serializedObject.ApplyModifiedProperties();
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 68f7548b1be4a4629a59fd17ff62f1c2
timeCreated: 1458054584
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,158 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace FlashTools.Internal {
[CustomEditor(typeof(SwfClipAsset)), CanEditMultipleObjects]
public class SwfClipAssetEditor : Editor {
List<SwfClipAsset> _clips = new List<SwfClipAsset>();
static string GetClipPath(SwfClipAsset clip) {
return clip
? AssetDatabase.GetAssetPath(clip)
: string.Empty;
}
static string GetPrefabPath(SwfClipAsset clip) {
var clip_path = GetClipPath(clip);
return string.IsNullOrEmpty(clip_path)
? string.Empty
: Path.ChangeExtension(clip_path, ".prefab");
}
static int GetFrameCount(SwfClipAsset clip) {
return clip != null ? clip.Sequences.Aggregate(0, (acc, seq) => {
return seq.Frames.Count + acc;
}) : 0;
}
//
//
//
static GameObject CreateClipGO(SwfClipAsset clip) {
if ( clip ) {
var clip_go = new GameObject(clip.name);
clip_go.AddComponent<MeshFilter>();
clip_go.AddComponent<MeshRenderer>();
clip_go.AddComponent<SwfClip>().clip = clip;
clip_go.AddComponent<SwfClipController>();
return clip_go;
}
return null;
}
static GameObject CreateClipPrefab(SwfClipAsset clip) {
GameObject result = null;
var clip_go = CreateClipGO(clip);
if ( clip_go ) {
var prefab_path = GetPrefabPath(clip);
if ( !string.IsNullOrEmpty(prefab_path) ) {
var prefab = AssetDatabase.LoadMainAssetAtPath(prefab_path);
if ( !prefab ) {
prefab = PrefabUtility.CreateEmptyPrefab(prefab_path);
}
result = PrefabUtility.ReplacePrefab(
clip_go,
prefab,
ReplacePrefabOptions.ConnectToPrefab);
}
GameObject.DestroyImmediate(clip_go, true);
}
return result;
}
static GameObject CreateClipOnScene(SwfClipAsset clip) {
var clip_go = CreateClipGO(clip);
if ( clip_go ) {
Undo.RegisterCreatedObjectUndo(clip_go, "Instance SwfClip");
}
return clip_go;
}
//
//
//
void CreateAllClipsPrefabs() {
Selection.objects = _clips
.Select (p => CreateClipPrefab(p))
.Where (p => !!p)
.ToArray();
}
void CreateAllClipsOnScene() {
Selection.objects = _clips
.Select (p => CreateClipOnScene(p))
.Where (p => !!p)
.ToArray();
}
//
//
//
void DrawGUIFrameCount() {
var counts = _clips.Select(p => GetFrameCount(p));
var mixed_value = counts.GroupBy(p => p).Count() > 1;
SwfEditorUtils.DoWithEnabledGUI(false, () => {
SwfEditorUtils.DoWithMixedValue(
mixed_value, () => {
EditorGUILayout.IntField("Frame count", counts.First());
});
});
}
void DrawGUISequences() {
SwfEditorUtils.DoWithEnabledGUI(false, () => {
var sequences_prop = SwfEditorUtils.GetPropertyByName(
serializedObject, "Sequences");
if ( sequences_prop.isArray ) {
SwfEditorUtils.DoWithMixedValue(
sequences_prop.hasMultipleDifferentValues, () => {
EditorGUILayout.IntField("Sequence count", sequences_prop.arraySize);
});
}
});
}
void DrawGUIControls() {
SwfEditorUtils.DoHorizontalGUI(() => {
if ( GUILayout.Button("Create prefab") ) {
CreateAllClipsPrefabs();
}
if ( GUILayout.Button("Instance to scene") ) {
CreateAllClipsOnScene();
}
});
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void OnEnable() {
_clips = targets.OfType<SwfClipAsset>().ToList();
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawDefaultInspector();
DrawGUIFrameCount();
DrawGUISequences();
DrawGUIControls();
if ( GUI.changed ) {
serializedObject.ApplyModifiedProperties();
}
}
public override bool RequiresConstantRepaint() {
return true;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 1b6bb12f4dfcf4d34a6a027b679eacc8
timeCreated: 1472724849
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,179 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.Linq;
namespace FlashTools.Internal {
[CustomPreview(typeof(SwfClipAsset))]
public class SwfClipAssetPreview : ObjectPreview {
int _sequence = 0;
static MaterialPropertyBlock _matPropBlock = null;
static PreviewRenderUtility _previewUtils = null;
Texture2D targetAtlas {
get {
var clip = target as SwfClipAsset;
return clip.Atlas;
}
}
int targetSequenceCount {
get {
var clip = target as SwfClipAsset;
return clip && clip.Sequences != null
? clip.Sequences.Count
: 0;
}
}
SwfClipAsset.Frame targetFrame {
get {
var clip = target as SwfClipAsset;
return GetFrameForClip(clip, _sequence);
}
}
SwfClipAsset.Sequence targetSequence {
get {
var clip = target as SwfClipAsset;
return GetSequenceForClip(clip, _sequence);
}
}
bool isTargetValidForPreview {
get {
var atlas = targetAtlas;
var frame = targetFrame;
var sequence = targetSequence;
return
atlas &&
frame != null &&
sequence != null &&
frame.CachedMesh && frame.CachedMesh.vertexCount > 0;
}
}
static SwfClipAsset.Frame GetFrameForClip(SwfClipAsset clip, int sequence_index) {
var sequence = GetSequenceForClip(clip, sequence_index);
var frames = sequence != null && sequence.Frames != null && sequence.Frames.Count > 0
? sequence.Frames
: null;
var frame_time = (float)(EditorApplication.timeSinceStartup * clip.FrameRate);
return frames != null
? frames[Mathf.FloorToInt(frame_time) % frames.Count]
: null;
}
static SwfClipAsset.Sequence GetSequenceForClip(SwfClipAsset clip, int sequence_index) {
return clip && clip.Sequences != null && clip.Sequences.Count > 0
? clip.Sequences[Mathf.Abs(sequence_index) % clip.Sequences.Count]
: null;
}
static Bounds CalculateBoundsForSequence(SwfClipAsset.Sequence sequence) {
var bounds = sequence != null && sequence.Frames != null && sequence.Frames.Count > 0
? sequence.Frames
.Where (p => !!p.CachedMesh)
.Select(p => p.CachedMesh.bounds)
: new Bounds[0];
var result = bounds.Any() ? bounds.First() : new Bounds();
foreach ( var bound in bounds ) {
result.Encapsulate(bound);
}
return result;
}
static void ConfigureCameraForSequence(Camera camera, SwfClipAsset.Sequence sequence) {
var bounds = CalculateBoundsForSequence(sequence);
camera.orthographic = true;
camera.orthographicSize = Mathf.Max(
Mathf.Abs(bounds.extents.x),
Mathf.Abs(bounds.extents.y));
camera.transform.position = new Vector3(
bounds.center.x,
bounds.center.y,
-10.0f);
}
// ---------------------------------------------------------------------
//
// Functions
//
// ---------------------------------------------------------------------
public void SetCurrentSequence(string sequence_name) {
var clip = target as SwfClipAsset;
_sequence = clip && clip.Sequences != null
? Mathf.Max(0, clip.Sequences.FindIndex(p => p.Name == sequence_name))
: 0;
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
public override void Initialize(Object[] targets) {
base.Initialize(targets);
if ( _matPropBlock == null ) {
_matPropBlock = new MaterialPropertyBlock();
}
if ( _previewUtils == null ) {
_previewUtils = new PreviewRenderUtility();
}
}
public override bool HasPreviewGUI() {
return true;
}
public override void OnPreviewSettings() {
var any_multi_sequences = m_Targets
.OfType<SwfClipAsset>()
.Any(p => p.Sequences != null && p.Sequences.Count > 1);
if ( any_multi_sequences && GUILayout.Button("<", EditorStyles.miniButton) ) {
--_sequence;
}
var sequence_names = m_Targets
.OfType<SwfClipAsset>()
.Select (p => GetSequenceForClip(p, _sequence))
.Where (p => p != null && !string.IsNullOrEmpty(p.Name))
.Select (p => p.Name)
.ToArray();
var label_text = string.Empty;
for ( int i = 0, e = sequence_names.Length; i < e; ++i ) {
label_text += string.Format(
i < e - 1 ? "{0}, " : "{0}",
sequence_names[i]);
}
GUILayout.Label(label_text, EditorStyles.whiteLabel);
if ( any_multi_sequences && GUILayout.Button(">", EditorStyles.miniButton) ) {
++_sequence;
}
}
public override void OnPreviewGUI(Rect r, GUIStyle background) {
if ( Event.current.type == EventType.Repaint ) {
if ( isTargetValidForPreview ) {
_previewUtils.BeginPreview(r, background);
{
_matPropBlock.SetTexture("_MainTex", targetAtlas);
ConfigureCameraForSequence(_previewUtils.m_Camera, targetSequence);
var frame = targetFrame;
for ( var i = 0; i < frame.Materials.Length; ++i ) {
_previewUtils.DrawMesh(
frame.CachedMesh,
Matrix4x4.identity,
frame.Materials[i],
i,
_matPropBlock);
}
_previewUtils.m_Camera.Render();
}
_previewUtils.EndAndDrawPreview(r);
}
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 61493c5b6491d4432a831d25914ed92a
timeCreated: 1473360782
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,50 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.Generic;
namespace FlashTools.Internal {
[CustomEditor(typeof(SwfClipController)), CanEditMultipleObjects]
public class SwfClipControllerEditor : Editor {
List<SwfClipController> _controllers = new List<SwfClipController>();
void AllControllersForeach(System.Action<SwfClipController> act) {
foreach ( var controller in _controllers ) {
act(controller);
}
}
void DrawClipControls() {
SwfEditorUtils.DoRightHorizontalGUI(() => {
if ( GUILayout.Button("Stop") ) {
AllControllersForeach(ctrl => ctrl.Stop(ctrl.isStopped));
}
if ( GUILayout.Button("Play") ) {
AllControllersForeach(ctrl => ctrl.Play(ctrl.isPlaying));
}
});
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void OnEnable() {
_controllers = targets.OfType<SwfClipController>().ToList();
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawDefaultInspector();
if ( Application.isPlaying ) {
DrawClipControls();
}
if ( GUI.changed ) {
serializedObject.ApplyModifiedProperties();
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 7973baab2bb7c4b2a8701d1abf799d4e
timeCreated: 1472192166
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,181 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.Generic;
namespace FlashTools.Internal {
[CustomEditor(typeof(SwfClip)), CanEditMultipleObjects]
public class SwfClipEditor : Editor {
List<SwfClip> _clips = new List<SwfClip>();
Dictionary<SwfClip, SwfClipAssetPreview> _previews = new Dictionary<SwfClip, SwfClipAssetPreview>();
void AllClipsForeachWithUndo(System.Action<SwfClip> act) {
Undo.RecordObjects(_clips.ToArray(), "Inspector");
foreach ( var clip in _clips ) {
act(clip);
EditorUtility.SetDirty(clip);
}
}
int GetMinClipsFrameCount() {
return _clips.Count > 0
? _clips.Min(clip => clip.frameCount)
: 0;
}
string GetClipsFrameCountStr() {
return _clips.Aggregate(string.Empty, (acc, clip) => {
var frame_count = clip.frameCount > 0 ? clip.frameCount - 1 : 0;
var frame_count_str = frame_count.ToString();
return string.IsNullOrEmpty(acc)
? frame_count_str
: (acc != frame_count_str ? "--" : acc);
});
}
string GetClipsCurrentFrameStr() {
return _clips.Aggregate(string.Empty, (acc, clip) => {
var current_frame = clip.currentFrame;
var current_frame_str = current_frame.ToString();
return string.IsNullOrEmpty(acc)
? current_frame_str
: (acc != current_frame_str ? "--" : acc);
});
}
List<string> GetAllSequences(bool include_empty) {
var result = new List<string>();
var result_clips = _clips
.Where (p => p.clip && p.clip.Sequences.Count > 0)
.Select(p => p.clip.Sequences)
.Where (p => p.All(s => !string.IsNullOrEmpty(s.Name)))
.ToList();
if ( result_clips.Count > 0 ) {
result = result_clips.First()
.Select(p => p.Name)
.ToList();
var sequences_enum = result_clips
.Select(p => p.Select(s => s.Name));
foreach ( var sequences in sequences_enum ) {
result = result
.Where(p => sequences.Contains(p))
.ToList();
}
if ( include_empty ) {
result.Add(string.Empty);
}
}
return result;
}
void DrawSequence() {
var all_sequences = GetAllSequences(true);
if ( all_sequences.Count > 0 ) {
var sequence_prop = SwfEditorUtils.GetPropertyByName(serializedObject, "_sequence");
SwfEditorUtils.DoWithMixedValue(
sequence_prop.hasMultipleDifferentValues, () => {
var sequence_index = EditorGUILayout.Popup(
"Sequence",
sequence_prop.hasMultipleDifferentValues
? all_sequences.FindIndex(p => string.IsNullOrEmpty(p))
: all_sequences.FindIndex(p => p == sequence_prop.stringValue),
all_sequences.ToArray());
if ( sequence_index >= 0 && sequence_index < all_sequences.Count ) {
var new_sequence = all_sequences[sequence_index];
if ( !string.IsNullOrEmpty(new_sequence) ) {
if ( sequence_prop.hasMultipleDifferentValues ) {
sequence_prop.stringValue = string.Empty;
}
sequence_prop.stringValue = new_sequence;
sequence_prop.serializedObject.ApplyModifiedProperties();
}
}
});
}
}
void DrawCurrentFrame() {
var min_frame_count = GetMinClipsFrameCount();
if ( min_frame_count > 1 ) {
EditorGUILayout.IntSlider(
SwfEditorUtils.GetPropertyByName(serializedObject, "_currentFrame"),
0,
min_frame_count - 1,
"Current frame");
DrawClipControls();
}
}
void DrawClipControls() {
EditorGUILayout.Space();
SwfEditorUtils.DoCenterHorizontalGUI(() => {
if ( GUILayout.Button(new GUIContent("<<", "to begin frame")) ) {
AllClipsForeachWithUndo(p => p.ToBeginFrame());
}
if ( GUILayout.Button(new GUIContent("<", "to prev frame")) ) {
AllClipsForeachWithUndo(p => p.ToPrevFrame());
}
GUILayout.Label(string.Format(
"{0}/{1}",
GetClipsCurrentFrameStr(), GetClipsFrameCountStr()));
if ( GUILayout.Button(new GUIContent(">", "to next frame")) ) {
AllClipsForeachWithUndo(p => p.ToNextFrame());
}
if ( GUILayout.Button(new GUIContent(">>", "to end frame")) ) {
AllClipsForeachWithUndo(p => p.ToEndFrame());
}
});
}
void SetupPreviews() {
_previews.Clear();
foreach ( var clip in _clips.Where(p => !!p.clip) ) {
var preview = new SwfClipAssetPreview();
preview.Initialize(new Object[]{clip.clip});
_previews.Add(clip, preview);
}
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void OnEnable() {
_clips = targets.OfType<SwfClip>().ToList();
SetupPreviews();
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawDefaultInspector();
DrawSequence();
DrawCurrentFrame();
if ( GUI.changed ) {
serializedObject.ApplyModifiedProperties();
SetupPreviews();
}
}
public override bool RequiresConstantRepaint() {
return _previews.Count > 0;
}
public override bool HasPreviewGUI() {
return _previews.Count > 0;
}
public override void OnPreviewGUI(Rect r, GUIStyle background) {
if ( Event.current.type == EventType.Repaint ) {
SwfClipAssetPreview preview;
var clip = target as SwfClip;
if ( _previews.TryGetValue(clip, out preview) ) {
preview.SetCurrentSequence(clip.sequence);
preview.DrawPreview(r);
}
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 7de32773fb5894d2a8e5b1f15f3b6549
timeCreated: 1472043063
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,98 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace FlashTools.Internal {
[CustomEditor(typeof(SwfManager))]
public class SwfManagerEditor : Editor {
SwfManager _manager = null;
SwfList<SwfClipController> _controllers = new SwfList<SwfClipController>();
bool _groupsFoldout = true;
void DrawCounts() {
SwfEditorUtils.DoWithEnabledGUI(false, () => {
EditorGUILayout.IntField(
"Clip count",
_manager.clipCount);
EditorGUILayout.IntField(
"Controller count",
_manager.controllerCount);
});
}
void DrawControls() {
SwfEditorUtils.DoRightHorizontalGUI(() => {
if ( _manager.isPaused && GUILayout.Button("Resume") ) {
_manager.Resume();
}
if ( _manager.isPlaying && GUILayout.Button("Pause") ) {
_manager.Pause();
}
});
}
void DrawGroupControls() {
var group_names = GetAllGroupNames();
if ( group_names.Count > 0 ) {
_groupsFoldout = EditorGUILayout.Foldout(_groupsFoldout, "Groups");
if ( _groupsFoldout ) {
foreach ( var group_name in group_names ) {
SwfEditorUtils.DoWithEnabledGUI(false, () => {
EditorGUILayout.TextField("Name", group_name);
});
EditorGUI.BeginChangeCheck();
var new_rate_scale = EditorGUILayout.FloatField(
"Rate Scale", _manager.GetGroupRateScale(group_name));
if ( EditorGUI.EndChangeCheck() ) {
_manager.SetGroupRateScale(group_name, new_rate_scale);
}
SwfEditorUtils.DoRightHorizontalGUI(() => {
if ( _manager.IsGroupPaused(group_name) && GUILayout.Button("Resume") ) {
_manager.ResumeGroup(group_name);
}
if ( _manager.IsGroupPlaying(group_name) && GUILayout.Button("Pause") ) {
_manager.PauseGroup(group_name);
}
});
}
}
}
}
HashSet<string> GetAllGroupNames() {
var result = new HashSet<string>();
for ( int i = 0, e = _controllers.Count; i < e; ++i ) {
var ctrl = _controllers[i];
if ( !string.IsNullOrEmpty(ctrl.groupName) ) {
result.Add(ctrl.groupName);
}
}
return result;
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void OnEnable() {
_manager = target as SwfManager;
_manager.GetAllControllers(_controllers);
}
public override void OnInspectorGUI() {
serializedObject.Update();
DrawDefaultInspector();
DrawCounts();
if ( Application.isPlaying ) {
DrawControls();
DrawGroupControls();
}
if ( GUI.changed ) {
serializedObject.ApplyModifiedProperties();
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 9a0802fa57f064e7590d56a471759ed9
timeCreated: 1472188711
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 6f6448c4e793c4081bce4ef3bea5dc30
folderAsset: yes
timeCreated: 1472790065
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,469 +0,0 @@
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace FlashTools.Internal {
public class SwfAssetPostprocessor : AssetPostprocessor {
static void OnPostprocessAllAssets(
string[] imported_assets,
string[] deleted_assets,
string[] moved_assets,
string[] moved_from_asset_paths)
{
var asset_paths = imported_assets
.Where(p => Path.GetExtension(p).ToLower().Equals(".asset"));
foreach ( var asset_path in asset_paths ) {
var asset = AssetDatabase.LoadAssetAtPath<SwfAsset>(asset_path);
if ( asset ) {
SwfAssetProcess(asset);
}
}
}
static void SwfAssetProcess(SwfAsset asset) {
try {
if ( asset.Converting.Stage == 0 ) {
var new_data = ConfigureBitmaps(
asset,
SwfEditorUtils.DecompressAsset<SwfAssetData>(asset.Data));
asset.Data = SwfEditorUtils.CompressAsset(new_data);
++asset.Converting.Stage;
EditorUtility.SetDirty(asset);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(asset));
} else if ( asset.Converting.Stage == 1 ) {
asset.Atlas = LoadAssetAtlas(asset);
if ( asset.Atlas ) {
ConfigureAtlas(asset);
ConfigureClips(
asset,
SwfEditorUtils.DecompressAsset<SwfAssetData>(asset.Data));
}
++asset.Converting.Stage;
EditorUtility.SetDirty(asset);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(asset));
}
} catch ( Exception e ) {
Debug.LogErrorFormat(
"<b>[FlashTools]</b> Postprocess swf asset error: {0}",
e.Message);
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(asset));
} finally {
if ( asset ) {
UpdateAssetClips(asset);
}
}
}
static Texture2D LoadAssetAtlas(SwfAsset asset) {
return AssetDatabase.LoadAssetAtPath<Texture2D>(
GetAtlasPath(asset));
}
static string GetAtlasPath(SwfAsset asset) {
if ( asset.Atlas ) {
return AssetDatabase.GetAssetPath(asset.Atlas);
} else {
var asset_path = AssetDatabase.GetAssetPath(asset);
return Path.ChangeExtension(asset_path, "._Atlas_.png");
}
}
// ---------------------------------------------------------------------
//
// ConfigureBitmaps
//
// ---------------------------------------------------------------------
static SwfAssetData ConfigureBitmaps(SwfAsset asset, SwfAssetData data) {
var textures = data.Bitmaps
.Where (p => p.Redirect == 0)
.Select (p => new KeyValuePair<ushort, Texture2D>(
p.Id,
LoadTextureFromData(p)))
.ToList();
var rects = PackAndSaveBitmapsAtlas(
GetAtlasPath(asset),
textures.Select(p => p.Value).ToArray(),
asset.Settings);
for ( var i = 0; i < data.Bitmaps.Count; ++i ) {
var bitmap = data.Bitmaps[i];
var texture_key = bitmap.Redirect > 0 ? bitmap.Redirect : bitmap.Id;
bitmap.SourceRect = SwfRectData.FromURect(
rects[textures.FindIndex(p => p.Key == texture_key)]);
}
return data;
}
static Texture2D LoadTextureFromData(SwfBitmapData bitmap) {
var texture = new Texture2D(
bitmap.RealWidth, bitmap.RealHeight,
TextureFormat.ARGB32, false);
texture.LoadRawTextureData(bitmap.ARGB32);
return texture;
}
struct BitmapsAtlasInfo {
public Texture2D Atlas;
public Rect[] Rects;
}
static Rect[] PackAndSaveBitmapsAtlas(
string atlas_path, Texture2D[] textures, SwfSettingsData settings)
{
var atlas_info = PackBitmapsAtlas(textures, settings);
RevertTexturePremultipliedAlpha(atlas_info.Atlas);
File.WriteAllBytes(atlas_path, atlas_info.Atlas.EncodeToPNG());
GameObject.DestroyImmediate(atlas_info.Atlas, true);
AssetDatabase.ImportAsset(atlas_path);
return atlas_info.Rects;
}
static BitmapsAtlasInfo PackBitmapsAtlas(
Texture2D[] textures, SwfSettingsData settings)
{
var atlas_padding = Mathf.Max(0, settings.AtlasPadding);
var max_atlas_size = Mathf.Max(32, settings.AtlasPowerOfTwo
? Mathf.ClosestPowerOfTwo(settings.MaxAtlasSize)
: settings.MaxAtlasSize);
var atlas = new Texture2D(0, 0);
var rects = atlas.PackTextures(textures, atlas_padding, max_atlas_size);
while ( rects == null ) {
max_atlas_size = Mathf.NextPowerOfTwo(max_atlas_size + 1);
rects = atlas.PackTextures(textures, atlas_padding, max_atlas_size);
}
return settings.AtlasForceSquare && atlas.width != atlas.height
? BitmapsAtlasToSquare(atlas, rects)
: new BitmapsAtlasInfo{Atlas = atlas, Rects = rects};
}
static BitmapsAtlasInfo BitmapsAtlasToSquare(Texture2D atlas, Rect[] rects) {
var atlas_size = Mathf.Max(atlas.width, atlas.height);
var atlas_scale = new Vector2(atlas.width, atlas.height) / atlas_size;
var new_atlas = new Texture2D(atlas_size, atlas_size, TextureFormat.ARGB32, false);
for ( var i = 0; i < rects.Length; ++i ) {
var new_position = rects[i].position;
new_position.Scale(atlas_scale);
var new_size = rects[i].size;
new_size.Scale(atlas_scale);
rects[i] = new Rect(new_position, new_size);
}
var fill_pixels = new Color32[atlas_size * atlas_size];
for ( var i = 0; i < atlas_size * atlas_size; ++i ) {
fill_pixels[i] = new Color(1,1,1,0);
}
new_atlas.SetPixels32(fill_pixels);
new_atlas.SetPixels32(0, 0, atlas.width, atlas.height, atlas.GetPixels32());
new_atlas.Apply();
GameObject.DestroyImmediate(atlas, true);
return new BitmapsAtlasInfo{
Atlas = new_atlas,
Rects = rects};
}
static void RevertTexturePremultipliedAlpha(Texture2D texture) {
var pixels = texture.GetPixels();
for ( var i = 0; i < pixels.Length; ++i ) {
var c = pixels[i];
if ( c.a > 0 ) {
c.r /= c.a;
c.g /= c.a;
c.b /= c.a;
}
pixels[i] = c;
}
texture.SetPixels(pixels);
texture.Apply();
}
// ---------------------------------------------------------------------
//
// ConfigureAtlas
//
// ---------------------------------------------------------------------
static void ConfigureAtlas(SwfAsset asset) {
var atlas_path = AssetDatabase.GetAssetPath(asset.Atlas);
var atlas_importer = GetBitmapsAtlasImporter(asset);
atlas_importer.spritesheet = new SpriteMetaData[0];
atlas_importer.textureType = TextureImporterType.Sprite;
atlas_importer.spriteImportMode = SpriteImportMode.Multiple;
atlas_importer.spritePixelsPerUnit = asset.Settings.PixelsPerUnit;
atlas_importer.mipmapEnabled = asset.Settings.GenerateMipMaps;
atlas_importer.filterMode = SwfAtlasFilterToImporterFilter(asset.Settings.AtlasTextureFilter);
atlas_importer.textureFormat = SwfAtlasFormatToImporterFormat(asset.Settings.AtlasTextureFormat);
AssetDatabase.WriteImportSettingsIfDirty(atlas_path);
AssetDatabase.ImportAsset(atlas_path);
}
static TextureImporter GetBitmapsAtlasImporter(SwfAsset asset) {
var atlas_path = AssetDatabase.GetAssetPath(asset.Atlas);
var atlas_importer = AssetImporter.GetAtPath(atlas_path) as TextureImporter;
if ( !atlas_importer ) {
throw new UnityException(string.Format(
"atlas texture importer not found ({0})",
atlas_path));
}
return atlas_importer;
}
static FilterMode SwfAtlasFilterToImporterFilter(
SwfSettingsData.AtlasFilter filter)
{
switch ( filter ) {
case SwfSettingsData.AtlasFilter.Point:
return FilterMode.Point;
case SwfSettingsData.AtlasFilter.Bilinear:
return FilterMode.Bilinear;
case SwfSettingsData.AtlasFilter.Trilinear:
return FilterMode.Trilinear;
default:
throw new UnityException(string.Format(
"incorrect swf atlas filter ({0})",
filter));
}
}
static TextureImporterFormat SwfAtlasFormatToImporterFormat(
SwfSettingsData.AtlasFormat format)
{
switch ( format ) {
case SwfSettingsData.AtlasFormat.AutomaticCompressed:
return TextureImporterFormat.AutomaticCompressed;
case SwfSettingsData.AtlasFormat.Automatic16bit:
return TextureImporterFormat.Automatic16bit;
case SwfSettingsData.AtlasFormat.AutomaticTruecolor:
return TextureImporterFormat.AutomaticTruecolor;
case SwfSettingsData.AtlasFormat.AutomaticCrunched:
return TextureImporterFormat.AutomaticCrunched;
default:
throw new UnityException(string.Format(
"incorrect swf atlas format ({0})",
format));
}
}
// ---------------------------------------------------------------------
//
// ConfigureClips
//
// ---------------------------------------------------------------------
static SwfAssetData ConfigureClips(SwfAsset asset, SwfAssetData data) {
asset.Clips = asset.Clips.Where(p => !!p).Distinct().ToList();
foreach ( var symbol in data.Symbols ) {
ConfigureClip(asset, data, symbol);
}
return data;
}
static void ConfigureClip(SwfAsset asset, SwfAssetData data, SwfSymbolData symbol) {
var clip_asset = asset.Clips.FirstOrDefault(p => p.Name == symbol.Name);
if ( clip_asset ) {
ConfigureClipAsset(clip_asset, asset, data, symbol);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(clip_asset));
} else {
var asset_path = AssetDatabase.GetAssetPath(asset);
var clip_asset_path = Path.ChangeExtension(asset_path, symbol.Name + ".asset");
SwfEditorUtils.LoadOrCreateAsset<SwfClipAsset>(clip_asset_path, (new_clip_asset, created) => {
ConfigureClipAsset(new_clip_asset, asset, data, symbol);
asset.Clips.Add(new_clip_asset);
});
}
}
static void ConfigureClipAsset(
SwfClipAsset clip_asset, SwfAsset asset, SwfAssetData data, SwfSymbolData symbol)
{
clip_asset.Name = symbol.Name;
clip_asset.Atlas = asset.Atlas;
clip_asset.FrameRate = data.FrameRate;
clip_asset.Sequences = LoadClipSequences(asset, data, symbol);
}
static List<SwfClipAsset.Sequence> LoadClipSequences(
SwfAsset asset, SwfAssetData data, SwfSymbolData symbol)
{
var sequences = new List<SwfClipAsset.Sequence>();
if ( IsValidAssetsForFrame(asset, symbol) ) {
foreach ( var frame in symbol.Frames ) {
var baked_frame = BakeClipFrame(asset, data, frame);
if ( !string.IsNullOrEmpty(frame.Name) &&
(sequences.Count < 1 || sequences.Last().Name != frame.Name) )
{
sequences.Add(new SwfClipAsset.Sequence{Name = frame.Name});
} else if ( sequences.Count < 1 ) {
sequences.Add(new SwfClipAsset.Sequence{Name = "Default"});
}
sequences.Last().Frames.Add(baked_frame);
}
}
return sequences;
}
static bool IsValidAssetsForFrame(
SwfAsset asset, SwfSymbolData symbol)
{
return
asset && asset.Atlas && asset.Data != null &&
symbol != null && symbol.Frames != null;
}
class BakedGroup {
public SwfInstanceData.Types Type;
public SwfBlendModeData.Types BlendMode;
public int ClipDepth;
public int StartVertex;
public int TriangleCount;
public Material Material;
}
static SwfClipAsset.Frame BakeClipFrame(
SwfAsset asset, SwfAssetData data, SwfFrameData frame)
{
List<uint> baked_uvs = new List<uint>();
List<uint> baked_mulcolors = new List<uint>();
List<uint> baked_addcolors = new List<uint>();
List<Vector2> baked_vertices = new List<Vector2>();
List<BakedGroup> baked_groups = new List<BakedGroup>();
List<Material> baked_materials = new List<Material>();
foreach ( var inst in frame.Instances ) {
var bitmap = inst != null
? FindBitmapFromAssetData(data, inst.Bitmap)
: null;
if ( bitmap != null && IsVisibleInstance(inst) ) {
var width = bitmap.RealWidth / 20.0f;
var height = bitmap.RealHeight / 20.0f;
var v0 = new Vector2( 0, 0);
var v1 = new Vector2(width, 0);
var v2 = new Vector2(width, height);
var v3 = new Vector2( 0, height);
var matrix =
Matrix4x4.Scale(
new Vector3(1.0f, -1.0f, 1.0f) /
asset.Settings.PixelsPerUnit) *
inst.Matrix.ToUMatrix();
baked_vertices.Add(matrix.MultiplyPoint3x4(v0));
baked_vertices.Add(matrix.MultiplyPoint3x4(v1));
baked_vertices.Add(matrix.MultiplyPoint3x4(v2));
baked_vertices.Add(matrix.MultiplyPoint3x4(v3));
var source_rect = bitmap.SourceRect;
baked_uvs.Add(SwfUtils.PackUV(source_rect.xMin, source_rect.yMin));
baked_uvs.Add(SwfUtils.PackUV(source_rect.xMax, source_rect.yMax));
uint mul_pack0, mul_pack1;
SwfUtils.PackFColorToUInts(
inst.ColorTrans.mulColor,
out mul_pack0, out mul_pack1);
baked_mulcolors.Add(mul_pack0);
baked_mulcolors.Add(mul_pack1);
uint add_pack0, add_pack1;
SwfUtils.PackFColorToUInts(
inst.ColorTrans.addColor,
out add_pack0, out add_pack1);
baked_addcolors.Add(add_pack0);
baked_addcolors.Add(add_pack1);
if ( baked_groups.Count == 0 ||
baked_groups[baked_groups.Count - 1].Type != inst.Type ||
baked_groups[baked_groups.Count - 1].BlendMode != inst.BlendMode.type ||
baked_groups[baked_groups.Count - 1].ClipDepth != inst.ClipDepth )
{
baked_groups.Add(new BakedGroup{
Type = inst.Type,
BlendMode = inst.BlendMode.type,
ClipDepth = inst.ClipDepth,
StartVertex = baked_vertices.Count - 4,
TriangleCount = 0,
Material = null
});
}
baked_groups.Last().TriangleCount += 6;
}
}
for ( var i = 0; i < baked_groups.Count; ++i ) {
var group = baked_groups[i];
switch ( group.Type ) {
case SwfInstanceData.Types.Mask:
group.Material = SwfMaterialCache.GetIncrMaskMaterial();
break;
case SwfInstanceData.Types.Group:
group.Material = SwfMaterialCache.GetSimpleMaterial(group.BlendMode);
break;
case SwfInstanceData.Types.Masked:
group.Material = SwfMaterialCache.GetMaskedMaterial(group.BlendMode, group.ClipDepth);
break;
case SwfInstanceData.Types.MaskReset:
group.Material = SwfMaterialCache.GetDecrMaskMaterial();
break;
default:
throw new UnityException(string.Format(
"SwfAssetPostprocessor. Incorrect instance type: {0}",
group.Type));
}
if ( group.Material ) {
baked_materials.Add(group.Material);
} else {
throw new UnityException(string.Format(
"SwfAssetPostprocessor. Material for baked group ({0}) not found",
group.Type));
}
}
var mesh_data = new SwfClipAsset.MeshData{
SubMeshes = baked_groups
.Select(p => new SwfClipAsset.SubMeshData{
StartVertex = p.StartVertex,
IndexCount = p.TriangleCount})
.ToArray(),
Vertices = baked_vertices .ToArray(),
UVs = baked_uvs .ToArray(),
AddColors = baked_addcolors.ToArray(),
MulColors = baked_mulcolors.ToArray()};
return new SwfClipAsset.Frame(
mesh_data,
baked_materials.ToArray());
}
static SwfBitmapData FindBitmapFromAssetData(SwfAssetData data, int bitmap_id) {
for ( var i = 0; i < data.Bitmaps.Count; ++i ) {
var bitmap = data.Bitmaps[i];
if ( bitmap.Id == bitmap_id ) {
return bitmap;
}
}
return null;
}
static bool IsVisibleInstance(SwfInstanceData inst) {
var result_color = inst.ColorTrans.ApplyToColor(Color.white);
return result_color.a >= 0.01f;
}
// ---------------------------------------------------------------------
//
// UpdateAssetClips
//
// ---------------------------------------------------------------------
static void UpdateAssetClips(SwfAsset asset) {
var clips = GameObject.FindObjectsOfType<SwfClip>();
foreach ( var clip in clips ) {
if ( clip && clip.clip && asset.Clips.Contains(clip.clip) ) {
clip.UpdateAllProperties();
}
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 91866390a580d4f728f84d5fab9202b8
timeCreated: 1458057686
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,367 +0,0 @@
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using SwfTools;
using SwfTools.SwfTags;
using SwfTools.SwfTypes;
namespace FlashTools.Internal {
public class SwfPostprocessor : AssetPostprocessor {
static void OnPostprocessAllAssets(
string[] imported_assets,
string[] deleted_assets,
string[] moved_assets,
string[] moved_from_asset_paths)
{
var swf_paths = imported_assets
.Where(p => Path.GetExtension(p).ToLower().Equals(".swf"));
foreach ( var swf_path in swf_paths ) {
SwfFileProcess(swf_path);
}
}
static void SwfFileProcess(string swf_path) {
var swf_asset_path = Path.ChangeExtension(swf_path, ".asset");
SwfEditorUtils.LoadOrCreateAsset<SwfAsset>(swf_asset_path, (swf_asset, created) => {
if ( created ) {
var default_settings = SwfEditorUtils.GetSettingsHolder().Settings;
swf_asset.Settings = default_settings;
swf_asset.Overridden = default_settings;
}
SafeLoadSwfAsset(swf_path, swf_asset);
});
}
static void SafeLoadSwfAsset(string swf_path, SwfAsset swf_asset) {
try {
var new_data = LoadSwfAssetData(swf_path);
swf_asset.Data = SwfEditorUtils.CompressAsset(new_data);
swf_asset.Converting = new SwfAsset.ConvertingState();
} catch ( Exception e ) {
Debug.LogErrorFormat(
"<b>[FlashTools]</b> Parsing swf error: {0}",
e.Message);
}
}
static SwfAssetData LoadSwfAssetData(string swf_path) {
var library = new SwfLibrary();
var decoder = new SwfDecoder(swf_path);
return new SwfAssetData{
FrameRate = decoder.UncompressedHeader.FrameRate,
Symbols = LoadSymbols(library, decoder),
Bitmaps = LoadBitmaps(library)};
}
// ---------------------------------------------------------------------
//
// LoadSymbols
//
// ---------------------------------------------------------------------
static List<SwfSymbolData> LoadSymbols(
SwfLibrary library, SwfDecoder decoder)
{
var symbols = new List<SwfSymbolData>();
symbols.Add(LoadSymbol("_Stage_", library, decoder.Tags));
var sprite_defs = library.Defines.Values
.OfType<SwfLibrarySpriteDefine>()
.Where(p => !string.IsNullOrEmpty(p.ExportName));
foreach ( var sprite_def in sprite_defs ) {
var name = sprite_def.ExportName;
var tags = sprite_def.ControlTags.Tags;
symbols.Add(LoadSymbol(name, library, tags));
}
return symbols;
}
static SwfSymbolData LoadSymbol(
string symbol_name, SwfLibrary library, List<SwfTagBase> tags)
{
var disp_lst = new SwfDisplayList();
var executer = new SwfContextExecuter(library, 0);
var symbol_frames = new List<SwfFrameData>();
while ( executer.NextFrame(tags, disp_lst) ) {
symbol_frames.Add(LoadSymbolFrameData(library, disp_lst));
}
return new SwfSymbolData{
Name = symbol_name,
Frames = symbol_frames};
}
static SwfFrameData LoadSymbolFrameData(
SwfLibrary library, SwfDisplayList display_list)
{
var frame = new SwfFrameData();
frame.Name = display_list.FrameName;
return AddDisplayListToFrame(
library,
display_list,
Matrix4x4.identity,
SwfBlendModeData.identity,
SwfColorTransData.identity,
0,
0,
null,
frame);
}
static SwfFrameData AddDisplayListToFrame(
SwfLibrary library,
SwfDisplayList display_list,
Matrix4x4 parent_matrix,
SwfBlendModeData parent_blend_mode,
SwfColorTransData parent_color_transform,
ushort parent_masked,
ushort parent_mask,
List<SwfInstanceData> parent_masks,
SwfFrameData frame)
{
var inst_filter_types = display_list.Instances.Values
.Where(p => p.Visible && p.FilterList.Filters.Count > 0)
.SelectMany(p => p.FilterList.Filters)
.Select(p => p.Type)
.Distinct();
foreach ( var filter_type in inst_filter_types ) {
Debug.LogWarningFormat(
"<b>[FlashTools]</b> SwfSurfaceFilters. Unsupported filter type '{0}'",
filter_type);
}
var self_masks = new List<SwfInstanceData>();
foreach ( var inst in display_list.Instances.Values.Where(p => p.Visible) ) {
CheckSelfMasks(self_masks, inst.Depth, frame);
var child_matrix = parent_matrix * inst.Matrix .ToUMatrix();
var child_blend_mode = parent_blend_mode * inst.BlendMode .ToBlendModeData();
var child_color_transform = parent_color_transform * inst.ColorTransform.ToColorTransData();
switch ( inst.Type ) {
case SwfDisplayInstanceType.Shape:
AddShapeInstanceToFrame(
library,
inst as SwfDisplayShapeInstance,
child_matrix,
child_blend_mode,
child_color_transform,
parent_masked,
parent_mask,
parent_masks,
self_masks,
frame);
break;
case SwfDisplayInstanceType.Sprite:
AddSpriteInstanceToFrame(
library,
inst as SwfDisplaySpriteInstance,
child_matrix,
child_blend_mode,
child_color_transform,
parent_masked,
parent_mask,
parent_masks,
self_masks,
frame);
break;
default:
throw new UnityException(string.Format(
"unsupported SwfDisplayInstanceType: {0}", inst.Type));
}
}
CheckSelfMasks(self_masks, ushort.MaxValue, frame);
return frame;
}
static void AddShapeInstanceToFrame(
SwfLibrary library,
SwfDisplayShapeInstance inst,
Matrix4x4 inst_matrix,
SwfBlendModeData inst_blend_mode,
SwfColorTransData inst_color_transform,
ushort parent_masked,
ushort parent_mask,
List<SwfInstanceData> parent_masks,
List<SwfInstanceData> self_masks,
SwfFrameData frame)
{
var shape_def = library.FindDefine<SwfLibraryShapeDefine>(inst.Id);
if ( shape_def != null ) {
for ( var i = 0; i < shape_def.Bitmaps.Length; ++i ) {
var bitmap_id = shape_def.Bitmaps[i];
var bitmap_matrix = i < shape_def.Matrices.Length ? shape_def.Matrices[i] : SwfMatrix.identity;
var bitmap_def = library.FindDefine<SwfLibraryBitmapDefine>(bitmap_id);
if ( bitmap_def != null ) {
var frame_inst_type =
(parent_mask > 0 || inst.ClipDepth > 0)
? SwfInstanceData.Types.Mask
: (parent_masked > 0 || self_masks.Count > 0)
? SwfInstanceData.Types.Masked
: SwfInstanceData.Types.Group;
var frame_inst_clip_depth =
(parent_mask > 0)
? parent_mask
: (inst.ClipDepth > 0)
? inst.ClipDepth
: parent_masked + self_masks.Count;
frame.Instances.Add(new SwfInstanceData{
Type = frame_inst_type,
ClipDepth = (ushort)frame_inst_clip_depth,
Bitmap = bitmap_id,
Matrix = SwfMatrixData.FromUMatrix(inst_matrix * bitmap_matrix.ToUMatrix()),
BlendMode = inst_blend_mode,
ColorTrans = inst_color_transform});
if ( parent_mask > 0 ) {
parent_masks.Add(frame.Instances[frame.Instances.Count - 1]);
} else if ( inst.ClipDepth > 0 ) {
self_masks.Add(frame.Instances[frame.Instances.Count - 1]);
}
}
}
}
}
static void AddSpriteInstanceToFrame(
SwfLibrary library,
SwfDisplaySpriteInstance inst,
Matrix4x4 inst_matrix,
SwfBlendModeData inst_blend_mode,
SwfColorTransData inst_color_transform,
ushort parent_masked,
ushort parent_mask,
List<SwfInstanceData> parent_masks,
List<SwfInstanceData> self_masks,
SwfFrameData frame)
{
var sprite_def = library.FindDefine<SwfLibrarySpriteDefine>(inst.Id);
if ( sprite_def != null ) {
AddDisplayListToFrame(
library,
inst.DisplayList,
inst_matrix,
inst_blend_mode,
inst_color_transform,
(ushort)(parent_masked + self_masks.Count),
(ushort)(parent_mask > 0
? parent_mask
: (inst.ClipDepth > 0
? inst.ClipDepth
: (ushort)0)),
parent_mask > 0
? parent_masks
: (inst.ClipDepth > 0
? self_masks
: null),
frame);
}
}
static void CheckSelfMasks(
List<SwfInstanceData> masks,
ushort depth,
SwfFrameData frame)
{
foreach ( var mask in masks ) {
if ( mask.ClipDepth < depth ) {
frame.Instances.Add(new SwfInstanceData{
Type = SwfInstanceData.Types.MaskReset,
ClipDepth = 0,
Bitmap = mask.Bitmap,
Matrix = mask.Matrix,
BlendMode = mask.BlendMode,
ColorTrans = mask.ColorTrans});
}
}
masks.RemoveAll(p => p.ClipDepth < depth);
}
// ---------------------------------------------------------------------
//
// LoadBitmaps
//
// ---------------------------------------------------------------------
static List<SwfBitmapData> LoadBitmaps(SwfLibrary library) {
return library.Defines
.Where (p => p.Value.Type == SwfLibraryDefineType.Bitmap)
.ToDictionary(p => p.Key, p => p.Value as SwfLibraryBitmapDefine)
.Select (p => new SwfBitmapData{
Id = p.Key,
ARGB32 = p.Value.ARGB32,
Redirect = p.Value.Redirect,
RealWidth = p.Value.Width,
RealHeight = p.Value.Height})
.ToList();
}
}
// ---------------------------------------------------------------------
//
// Extensions
//
// ---------------------------------------------------------------------
static class SwfExtensions {
public static Matrix4x4 ToUMatrix(this SwfMatrix self) {
var mat = Matrix4x4.identity;
mat.m00 = self.ScaleX;
mat.m10 = self.RotateSkew0;
mat.m01 = self.RotateSkew1;
mat.m11 = self.ScaleY;
mat.m03 = self.TranslateX;
mat.m13 = self.TranslateY;
return mat;
}
public static SwfBlendModeData ToBlendModeData(this SwfBlendMode self) {
switch ( self.Value ) {
case SwfBlendMode.Mode.Normal:
return new SwfBlendModeData(SwfBlendModeData.Types.Normal);
case SwfBlendMode.Mode.Layer:
return new SwfBlendModeData(SwfBlendModeData.Types.Layer);
case SwfBlendMode.Mode.Multiply:
return new SwfBlendModeData(SwfBlendModeData.Types.Multiply);
case SwfBlendMode.Mode.Screen:
return new SwfBlendModeData(SwfBlendModeData.Types.Screen);
case SwfBlendMode.Mode.Lighten:
return new SwfBlendModeData(SwfBlendModeData.Types.Lighten);
case SwfBlendMode.Mode.Darken:
return new SwfBlendModeData(SwfBlendModeData.Types.Darken);
case SwfBlendMode.Mode.Difference:
return new SwfBlendModeData(SwfBlendModeData.Types.Difference);
case SwfBlendMode.Mode.Add:
return new SwfBlendModeData(SwfBlendModeData.Types.Add);
case SwfBlendMode.Mode.Subtract:
return new SwfBlendModeData(SwfBlendModeData.Types.Subtract);
case SwfBlendMode.Mode.Invert:
return new SwfBlendModeData(SwfBlendModeData.Types.Invert);
case SwfBlendMode.Mode.Hardlight:
return new SwfBlendModeData(SwfBlendModeData.Types.Hardlight);
default:
Debug.LogWarningFormat(
"<b>[FlashTools]</b> SwfBlendMode. Unsupported blend mode '{0}'",
self.Value);
return new SwfBlendModeData(SwfBlendModeData.Types.Normal);
}
}
public static SwfColorTransData ToColorTransData(this SwfColorTransform self) {
var trans = SwfColorTransData.identity;
if ( self.HasAdd ) {
trans.addColor = new SwfVec4Data(
self.RAdd / 256.0f,
self.GAdd / 256.0f,
self.BAdd / 256.0f,
self.AAdd / 256.0f);
}
if ( self.HasMul ) {
trans.mulColor = new SwfVec4Data(
self.RMul / 256.0f,
self.GMul / 256.0f,
self.BMul / 256.0f,
self.AMul / 256.0f);
}
return trans;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 27c44c175a74f4707bafa0bb1a8d47f7
timeCreated: 1457365970
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,186 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using Ionic.Zlib;
namespace FlashTools.Internal {
public static class SwfEditorUtils {
// ---------------------------------------------------------------------
//
// Functions
//
// ---------------------------------------------------------------------
public static void DoWithMixedValue(bool mixed, System.Action act) {
var last_show_mixed_value = EditorGUI.showMixedValue;
EditorGUI.showMixedValue = mixed;
try {
act();
} finally {
EditorGUI.showMixedValue = last_show_mixed_value;
}
}
public static void DoWithEnabledGUI(bool enabled, System.Action act) {
EditorGUI.BeginDisabledGroup(!enabled);
try {
act();
} finally {
EditorGUI.EndDisabledGroup();
}
}
public static void DoHorizontalGUI(System.Action act) {
GUILayout.BeginHorizontal();
try {
act();
} finally {
GUILayout.EndHorizontal();
}
}
public static void DoRightHorizontalGUI(System.Action act) {
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
try {
act();
} finally {
GUILayout.EndHorizontal();
}
}
public static void DoCenterHorizontalGUI(System.Action act) {
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
try {
act();
} finally {
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
}
public static SerializedProperty GetPropertyByName(SerializedObject obj, string name) {
var prop = obj.FindProperty(name);
if ( prop == null ) {
throw new UnityException(string.Format(
"SwfEditorUtils. Not found property: {0}",
name));
}
return prop;
}
public static SwfSettings GetSettingsHolder() {
var holder = LoadFirstAssetByFilter<SwfSettings>("t:SwfSettings");
if ( !holder ) {
throw new UnityException(
"SwfEditorUtils. SwfSettings asset not found");
}
return holder;
}
public static T LoadOrCreateAsset<T>(string asset_path, System.Action<T, bool> act) where T : ScriptableObject {
var asset = AssetDatabase.LoadAssetAtPath<T>(asset_path);
if ( asset ) {
act(asset, false);
EditorUtility.SetDirty(asset);
} else {
asset = ScriptableObject.CreateInstance<T>();
act(asset, true);
AssetDatabase.CreateAsset(asset, asset_path);
}
AssetDatabase.ImportAsset(asset_path);
return asset;
}
public static T LoadFirstAssetByFilter<T>(string filter) where T : UnityEngine.Object {
var guids = AssetDatabase.FindAssets(filter);
foreach ( var guid in guids ) {
var path = AssetDatabase.GUIDToAssetPath(guid);
var asset = AssetDatabase.LoadAssetAtPath<T>(path);
if ( asset ) {
return asset;
}
}
return null;
}
public static byte[] CompressAsset<T>(T asset) {
var bytes = AssetToBytes(asset);
var result = ZlibStream.CompressBuffer(bytes);
return result;
}
public static T DecompressAsset<T>(byte[] data) {
var bytes = ZlibStream.UncompressBuffer(data);
var result = BytesToAsset<T>(bytes);
return result;
}
static byte[] AssetToBytes<T>(T asset) {
var formatter = new BinaryFormatter();
using ( var stream = new MemoryStream() ) {
formatter.Serialize(stream, asset);
return stream.ToArray();
}
}
static T BytesToAsset<T>(byte[] bytes) {
var formatter = new BinaryFormatter();
using ( var stream = new MemoryStream(bytes) ) {
return (T)formatter.Deserialize(stream);
}
}
// ---------------------------------------------------------------------
//
// Internal
//
// ---------------------------------------------------------------------
[MenuItem("Tools/FlashTools/Open settings...")]
static void Tools_FlashTools_OpenSettings() {
var settings_holder = SwfEditorUtils.GetSettingsHolder();
Selection.objects = new Object[]{settings_holder};
}
[MenuItem("Tools/FlashTools/Reimport all swf files")]
static void Tools_FlashTools_ReimportAllSwfFiles() {
var swf_paths = GetAllSwfFilePaths();
var title = "Reimport";
var message = string.Format(
"Do you really want to reimport all ({0}) swf files?",
swf_paths.Length);
if ( EditorUtility.DisplayDialog(title, message, "Ok", "Cancel") ) {
foreach ( var swf_path in swf_paths ) {
AssetDatabase.ImportAsset(swf_path);
}
}
}
[MenuItem("Tools/FlashTools/Pregenerate all materials")]
static void PregenerateAllMaterials() {
var blend_modes = System.Enum.GetValues(typeof(SwfBlendModeData.Types));
foreach ( SwfBlendModeData.Types blend_mode in blend_modes ) {
SwfMaterialCache.GetSimpleMaterial(blend_mode);
for ( var i = 0; i < 10; ++i ) {
SwfMaterialCache.GetMaskedMaterial(blend_mode, i);
}
}
SwfMaterialCache.GetIncrMaskMaterial();
SwfMaterialCache.GetDecrMaskMaterial();
}
static string[] GetAllSwfFilePaths() {
return AssetDatabase.GetAllAssetPaths()
.Where(p => Path.GetExtension(p).ToLower().Equals(".swf"))
.ToArray();
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 80bbe5b795df64829b002ddb92fb7a37
timeCreated: 1472455940
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,250 +0,0 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
namespace FlashTools.Internal {
public class SwfMaterialCache {
const string SwfSimpleShaderName = "SwfSimpleShader";
const string SwfMaskedShaderName = "SwfMaskedShader";
const string SwfSimpleGrabShaderName = "SwfSimpleGrabShader";
const string SwfMaskedGrabShaderName = "SwfMaskedGrabShader";
const string SwfIncrMaskShaderName = "SwfIncrMaskShader";
const string SwfDecrMaskShaderName = "SwfDecrMaskShader";
static Dictionary<string, Shader> ShaderCache = new Dictionary<string, Shader>();
static Shader GetShaderByName(string shader_name) {
Shader shader;
if ( !ShaderCache.TryGetValue(shader_name, out shader) || !shader ) {
shader = SafeLoadShader(shader_name);
ShaderCache.Add(shader_name, shader);
}
shader.hideFlags = HideFlags.HideInInspector;
return shader;
}
static Dictionary<string, Material> MaterialCache = new Dictionary<string, Material>();
static Material GetMaterialByPath(
string material_path,
Shader material_shader,
System.Func<Material, Material> fill_material)
{
Material material;
if ( !MaterialCache.TryGetValue(material_path, out material) || !material ) {
material = SafeLoadMaterial(material_path, material_shader, fill_material);
MaterialCache.Add(material_path, material);
}
material.hideFlags = HideFlags.HideInInspector;
return material;
}
// ---------------------------------------------------------------------
//
// Functions
//
// ---------------------------------------------------------------------
public static Material GetSimpleMaterial(
SwfBlendModeData.Types blend_mode)
{
return LoadOrCreateMaterial(
SelectShader(false, blend_mode),
(dir_path, filename) => {
return string.Format(
"{0}/{1}_{2}.mat",
dir_path, filename, blend_mode);
},
material => FillMaterial(material, blend_mode, 0));
}
public static Material GetMaskedMaterial(
SwfBlendModeData.Types blend_mode,
int stencil_id)
{
return LoadOrCreateMaterial(
SelectShader(true, blend_mode),
(dir_path, filename) => {
return string.Format(
"{0}/{1}_{2}_{3}.mat",
dir_path, filename, blend_mode, stencil_id);
},
material => FillMaterial(material, blend_mode, stencil_id));
}
public static Material GetIncrMaskMaterial() {
return LoadOrCreateMaterial(
GetShaderByName(SwfIncrMaskShaderName),
(dir_path, filename) => {
return string.Format(
"{0}/{1}.mat",
dir_path, filename);
},
material => material);
}
public static Material GetDecrMaskMaterial() {
return LoadOrCreateMaterial(
GetShaderByName(SwfDecrMaskShaderName),
(dir_path, filename) => {
return string.Format(
"{0}/{1}.mat",
dir_path, filename);
},
material => material);
}
// ---------------------------------------------------------------------
//
// Private
//
// ---------------------------------------------------------------------
static Shader SafeLoadShader(string shader_name) {
var filter = string.Format("t:Shader {0}", shader_name);
var shader = SwfEditorUtils.LoadFirstAssetByFilter<Shader>(filter);
if ( !shader ) {
throw new UnityException(string.Format(
"SwfMaterialCache. Shader not found: {0}",
shader_name));
}
return shader;
}
static Material SafeLoadMaterial(
string material_path,
Shader material_shader,
System.Func<Material, Material> fill_material)
{
var material = AssetDatabase.LoadAssetAtPath<Material>(material_path);
if ( !material ) {
material = fill_material(new Material(material_shader));
material.hideFlags = HideFlags.HideInInspector;
AssetDatabase.CreateAsset(material, material_path);
}
return material;
}
static Material LoadOrCreateMaterial(
Shader shader,
System.Func<string, string, string> path_factory,
System.Func<Material, Material> fill_material)
{
var shader_path = AssetDatabase.GetAssetPath(shader);
var shader_dir = Path.GetDirectoryName(shader_path);
var generated_dir = Path.Combine(shader_dir, "Generated");
if ( !AssetDatabase.IsValidFolder(generated_dir) ) {
AssetDatabase.CreateFolder(shader_dir, "Generated");
}
var material_path = path_factory(
generated_dir,
Path.GetFileNameWithoutExtension(shader_path));
return GetMaterialByPath(material_path, shader, fill_material);
}
static Shader SelectShader(bool masked, SwfBlendModeData.Types blend_mode) {
switch ( blend_mode ) {
case SwfBlendModeData.Types.Normal:
case SwfBlendModeData.Types.Layer:
case SwfBlendModeData.Types.Multiply:
case SwfBlendModeData.Types.Screen:
case SwfBlendModeData.Types.Lighten:
case SwfBlendModeData.Types.Add:
case SwfBlendModeData.Types.Subtract:
return GetShaderByName(masked ? SwfMaskedShaderName : SwfSimpleShaderName);
case SwfBlendModeData.Types.Darken:
case SwfBlendModeData.Types.Difference:
case SwfBlendModeData.Types.Invert:
case SwfBlendModeData.Types.Overlay:
case SwfBlendModeData.Types.Hardlight:
return GetShaderByName(masked ? SwfMaskedGrabShaderName : SwfSimpleGrabShaderName);
default:
throw new UnityException(string.Format(
"SwfMaterialCache. Incorrect blend mode: {0}",
blend_mode));
}
}
static Material FillMaterial(
Material material,
SwfBlendModeData.Types blend_mode,
int stencil_id)
{
switch ( blend_mode ) {
case SwfBlendModeData.Types.Normal:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
break;
case SwfBlendModeData.Types.Layer:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
break;
case SwfBlendModeData.Types.Multiply:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.DstColor);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
break;
case SwfBlendModeData.Types.Screen:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.OneMinusDstColor);
material.SetInt("_DstBlend", (int)BlendMode.One);
break;
case SwfBlendModeData.Types.Lighten:
material.SetInt("_BlendOp" , (int)BlendOp.Max);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
break;
case SwfBlendModeData.Types.Darken:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
material.EnableKeyword("SWF_DARKEN_BLEND");
break;
case SwfBlendModeData.Types.Difference:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
material.EnableKeyword("SWF_DIFFERENCE_BLEND");
break;
case SwfBlendModeData.Types.Add:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.One);
break;
case SwfBlendModeData.Types.Subtract:
material.SetInt("_BlendOp" , (int)BlendOp.ReverseSubtract);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.One);
break;
case SwfBlendModeData.Types.Invert:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
material.EnableKeyword("SWF_INVERT_BLEND");
break;
case SwfBlendModeData.Types.Overlay:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
material.EnableKeyword("SWF_OVERLAY_BLEND");
break;
case SwfBlendModeData.Types.Hardlight:
material.SetInt("_BlendOp" , (int)BlendOp.Add);
material.SetInt("_SrcBlend", (int)BlendMode.One);
material.SetInt("_DstBlend", (int)BlendMode.OneMinusSrcAlpha);
material.EnableKeyword("SWF_HARDLIGHT_BLEND");
break;
default:
throw new UnityException(string.Format(
"SwfMaterialCache. Incorrect blend mode: {0}",
blend_mode));
}
material.SetInt("_StencilID", stencil_id);
return material;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6ff1e135d8add4573a0b31491f93e994
timeCreated: 1475700802
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,293 +0,0 @@
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections.Generic;
namespace FlashTools.Internal {
//
// SwfIntRange
//
[CustomPropertyDrawer(typeof(SwfIntRangeAttribute))]
public class SwfIntRangeDrawer : PropertyDrawer {
static void ValidateProperty(SerializedProperty property, int min, int max) {
if ( !property.hasMultipleDifferentValues ) {
if ( property.propertyType == SerializedPropertyType.Integer ) {
var clamp = Mathf.Clamp(property.intValue, min, max);
if ( clamp != property.intValue ) {
property.intValue = clamp;
property.serializedObject.ApplyModifiedProperties();
}
}
}
}
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
var attr = attribute as SwfIntRangeAttribute;
ValidateProperty(property, attr.Min, attr.Max);
EditorGUI.PropertyField(position, property, label, true);
}
}
//
// SwfFloatRange
//
[CustomPropertyDrawer(typeof(SwfFloatRangeAttribute))]
public class SwfFloatRangeDrawer : PropertyDrawer {
static void ValidateProperty(SerializedProperty property, float min, float max) {
if ( !property.hasMultipleDifferentValues ) {
if ( property.propertyType == SerializedPropertyType.Float ) {
var clamp = Mathf.Clamp(property.floatValue, min, max);
if ( clamp != property.floatValue ) {
property.floatValue = clamp;
property.serializedObject.ApplyModifiedProperties();
}
}
}
}
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
var attr = attribute as SwfFloatRangeAttribute;
ValidateProperty(property, attr.Min, attr.Max);
EditorGUI.PropertyField(position, property, label, true);
}
}
//
// SwfSortingLayerDrawer
//
[CustomPropertyDrawer(typeof(SwfSortingLayerAttribute))]
public class SwfSortingLayerDrawer : PropertyDrawer {
const string DefaultLayerName = "Default";
static List<string> GetAllSortingLayers(bool include_empty) {
var result = new List<string>();
var tag_assets = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset");
if ( tag_assets.Length > 0 ) {
var layers = SwfEditorUtils.GetPropertyByName(
new SerializedObject(tag_assets[0]),
"m_SortingLayers");
if ( layers.isArray ) {
for ( var i = 0; i < layers.arraySize; ++i ) {
var layer_prop = layers.GetArrayElementAtIndex(i);
var layer_prop_name = layer_prop != null
? layer_prop.FindPropertyRelative("name")
: null;
var layer_name = layer_prop_name != null && layer_prop_name.propertyType == SerializedPropertyType.String
? layer_prop_name.stringValue
: string.Empty;
if ( !string.IsNullOrEmpty(layer_name) ) {
result.Add(layer_name);
}
}
}
}
if ( !result.Contains(DefaultLayerName) ) {
result.Add(DefaultLayerName);
}
if ( include_empty ) {
result.Add(string.Empty);
}
return result;
}
static void ValidateProperty(SerializedProperty property) {
if ( !property.hasMultipleDifferentValues ) {
if ( property.propertyType == SerializedPropertyType.String ) {
var all_sorting_layers = GetAllSortingLayers(false);
if ( !all_sorting_layers.Contains(property.stringValue) ) {
property.stringValue = string.Empty;
property.stringValue = DefaultLayerName;
property.serializedObject.ApplyModifiedProperties();
}
}
}
}
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
if ( property.propertyType == SerializedPropertyType.String ) {
ValidateProperty(property);
SwfEditorUtils.DoWithMixedValue(
property.hasMultipleDifferentValues, () => {
label = EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
var all_sorting_layers = GetAllSortingLayers(true);
var sorting_layer_index = EditorGUI.Popup(
position,
label,
property.hasMultipleDifferentValues
? all_sorting_layers.FindIndex(p => string.IsNullOrEmpty(p))
: all_sorting_layers.FindIndex(p => p == property.stringValue),
all_sorting_layers.Select(p => new GUIContent(p)).ToArray());
if ( EditorGUI.EndChangeCheck() ) {
if ( sorting_layer_index >= 0 && sorting_layer_index < all_sorting_layers.Count ) {
var new_value = all_sorting_layers[sorting_layer_index];
if ( !string.IsNullOrEmpty(new_value) ) {
if ( property.hasMultipleDifferentValues ) {
property.stringValue = string.Empty;
}
property.stringValue = new_value;
property.serializedObject.ApplyModifiedProperties();
}
}
}
EditorGUI.EndProperty();
});
} else {
EditorGUI.LabelField(position, label.text, "Use SwfSortingLayer with string attribute.");
}
}
}
//
// SwfPowerOfTwoIfDrawer
//
[CustomPropertyDrawer(typeof(SwfPowerOfTwoIfAttribute))]
public class SwfPowerOfTwoIfDrawer : PropertyDrawer {
static SerializedProperty FindNextBoolProperty(SerializedProperty property, string next_prop) {
var prop = property.Copy();
while ( prop.Next(false) ) {
if ( prop.name == next_prop && prop.propertyType == SerializedPropertyType.Boolean ) {
return prop;
}
}
return null;
}
static int GetPowerOfTwo(int value) {
return Mathf.RoundToInt(Mathf.Pow(2, value));
}
static int[] GenPowerOfTwoValues(int min_pow2, int max_pow2) {
var values = new List<int>();
while ( min_pow2 <= max_pow2 ) {
values.Add(GetPowerOfTwo(min_pow2));
++min_pow2;
}
return values.ToArray();
}
static void ValidateProperty(SerializedProperty property, bool need_pow2, int min_pow2, int max_pow2) {
if ( !property.hasMultipleDifferentValues ) {
if ( property.propertyType == SerializedPropertyType.Integer ) {
var last_value = property.intValue;
if ( need_pow2 && !Mathf.IsPowerOfTwo(property.intValue) ) {
property.intValue = Mathf.ClosestPowerOfTwo(property.intValue);
}
property.intValue = Mathf.Clamp(
property.intValue,
GetPowerOfTwo(min_pow2),
GetPowerOfTwo(max_pow2));
if ( last_value != property.intValue ) {
property.serializedObject.ApplyModifiedProperties();
}
}
}
}
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
if ( property.propertyType == SerializedPropertyType.Integer ) {
var attr = attribute as SwfPowerOfTwoIfAttribute;
var bool_prop = FindNextBoolProperty(property, attr.BoolProp);
var need_pow2 = (bool_prop != null && (bool_prop.boolValue || bool_prop.hasMultipleDifferentValues));
ValidateProperty(property, need_pow2, attr.MinPow2, attr.MaxPow2);
SwfEditorUtils.DoWithMixedValue(
property.hasMultipleDifferentValues, () => {
if ( need_pow2 ) {
var values = GenPowerOfTwoValues(attr.MinPow2, attr.MaxPow2);
var vnames = values.Select(p => new GUIContent(p.ToString())).ToArray();
EditorGUI.IntPopup(position, property, vnames, values, label);
} else {
EditorGUI.PropertyField(position, property, label, true);
}
});
} else {
EditorGUI.LabelField(position, label.text, "Use SwfPowerOfTwoIf with integer attribute.");
}
}
}
//
// SwfReadOnlyDrawer
//
[CustomPropertyDrawer(typeof(SwfReadOnlyAttribute))]
public class SwfReadOnlyDrawer : PropertyDrawer {
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
SwfEditorUtils.DoWithEnabledGUI(false, () => {
EditorGUI.PropertyField(position, property, label, true);
});
}
}
//
// SwfAssetGUIDDrawer
//
[CustomPropertyDrawer(typeof(SwfAssetGUIDAttribute))]
public class SwfAssetGUIDDrawer : PropertyDrawer {
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
if ( property.propertyType == SerializedPropertyType.String ) {
var attr = attribute as SwfAssetGUIDAttribute;
SwfEditorUtils.DoWithEnabledGUI(!attr.ReadOnly, () => {
SwfEditorUtils.DoWithMixedValue(
property.hasMultipleDifferentValues, () => {
label = EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
var asset_path = AssetDatabase.GUIDToAssetPath(property.stringValue);
var asset = AssetDatabase.LoadMainAssetAtPath(asset_path);
var new_asset = EditorGUI.ObjectField(
position, property.displayName, asset, typeof(UnityEngine.Object), false);
if ( EditorGUI.EndChangeCheck() ) {
if ( property.hasMultipleDifferentValues ) {
property.stringValue = "--";
}
var new_asset_path = AssetDatabase.GetAssetPath(new_asset);
property.stringValue = AssetDatabase.AssetPathToGUID(new_asset_path);
property.serializedObject.ApplyModifiedProperties();
}
EditorGUI.EndProperty();
});
});
} else {
EditorGUI.LabelField(position, label.text, "Use SwfAssetGUID with string attribute.");
}
}
}
//
// SwfDisplayNameDrawer
//
[CustomPropertyDrawer(typeof(SwfDisplayNameAttribute))]
public class SwfDisplayNameDrawer : PropertyDrawer {
public override void OnGUI(
Rect position, SerializedProperty property, GUIContent label)
{
var new_label = new GUIContent(label);
new_label.text = (attribute as SwfDisplayNameAttribute).DisplayName;
if ( EditorGUI.PropertyField(position, property, new_label) ) {
foreach ( SerializedProperty child in property ) {
EditorGUILayout.PropertyField(child);
}
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 115975934e0df4b05a62c112248e8964
timeCreated: 1472013429
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 8e21e87290a7a4488ac2343d6defe08f
folderAsset: yes
timeCreated: 1473785847
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,102 +0,0 @@
using UnityEngine;
using NUnit.Framework;
namespace FlashTools.Internal.Tests {
public static class SwfUtilsTests {
static void AssertAreEqualVectors(Vector2 v0, Vector2 v1, float delta) {
Assert.AreEqual(v0.x, v1.x, delta);
Assert.AreEqual(v0.y, v1.y, delta);
}
static void AssertAreEqualVectors(Vector4 v0, Vector4 v1, float delta) {
Assert.AreEqual(v0.x, v1.x, delta);
Assert.AreEqual(v0.y, v1.y, delta);
Assert.AreEqual(v0.z, v1.z, delta);
Assert.AreEqual(v0.w, v1.w, delta);
}
//
//
//
[Test]
public static void PackUShortsToUIntTests() {
ushort v0 = 11, v1 = 99;
ushort o0, o1;
SwfUtils.UnpackUShortsFromUInt(
SwfUtils.PackUShortsToUInt(v0, v1), out o0, out o1);
Assert.AreEqual(v0, o0);
Assert.AreEqual(v1, o1);
ushort v2 = 16789, v3 = 31234;
ushort o2, o3;
SwfUtils.UnpackUShortsFromUInt(
SwfUtils.PackUShortsToUInt(v2, v3), out o2, out o3);
Assert.AreEqual(v2, o2);
Assert.AreEqual(v3, o3);
}
[Test]
public static void PackUVTests() {
var v0 = new Vector2(0.9999f, 0.1111f);
float u0, u1;
SwfUtils.UnpackUV(SwfUtils.PackUV(v0.x, v0.y), out u0, out u1);
AssertAreEqualVectors(v0, new Vector2(u0, u1), SwfUtils.UVPrecision);
var v1 = new Vector2(0.0987f, 0.0123f);
float u2, u3;
SwfUtils.UnpackUV(SwfUtils.PackUV(v1.x, v1.y), out u2, out u3);
AssertAreEqualVectors(v1, new Vector2(u2, u3), SwfUtils.UVPrecision);
var v2 = new Vector2(1.0f, 0.0f);
float u4, u5;
SwfUtils.UnpackUV(SwfUtils.PackUV(v2.x, v2.y), out u4, out u5);
AssertAreEqualVectors(v2, new Vector2(u4, u5), SwfUtils.UVPrecision);
}
[Test]
public static void PackFloatColorToUShortTests() {
float v0 = -5.678f;
Assert.AreEqual(
v0,
SwfUtils.UnpackFloatColorFromUShort(SwfUtils.PackFloatColorToUShort(v0)),
SwfUtils.FColorPrecision);
float v1 = 60.678f;
Assert.AreEqual(
v1,
SwfUtils.UnpackFloatColorFromUShort(SwfUtils.PackFloatColorToUShort(v1)),
SwfUtils.FColorPrecision);
float v2 = 0.678f;
Assert.AreEqual(
v2,
SwfUtils.UnpackFloatColorFromUShort(SwfUtils.PackFloatColorToUShort(v2)),
SwfUtils.FColorPrecision);
}
[Test]
public static void PackColorToUIntsTests() {
var v0 = new Color(0.01f, 0.02f, 0.33f, 1.0f);
uint u0, u1;
SwfUtils.PackFColorToUInts(v0, out u0, out u1);
Color c0;
SwfUtils.UnpackFColorFromUInts(
u0, u1,
out c0.r, out c0.g, out c0.b, out c0.a);
AssertAreEqualVectors(
v0, c0, SwfUtils.FColorPrecision);
var v1 = new Vector4(0.01f, 0.02f, 0.33f, 1.0f);
uint u2, u3;
SwfUtils.PackFColorToUInts(v1, out u2, out u3);
Vector4 c1;
SwfUtils.UnpackFColorFromUInts(
u2, u3,
out c1.x, out c1.y, out c1.z, out c1.w);
AssertAreEqualVectors(
v1, c1, SwfUtils.FColorPrecision);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 56c243ac3822b44ffa1520cfc5471e75
timeCreated: 1473785856
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,70 +0,0 @@
using System.Collections.Generic;
namespace FlashTools.Internal {
public class SwfAssocList<T> {
SwfList<T> _list;
Dictionary<T, int> _dict;
IEqualityComparer<T> _comp;
public SwfAssocList() {
_list = new SwfList<T>();
_dict = new Dictionary<T, int>();
_comp = EqualityComparer<T>.Default;
}
public SwfAssocList(int capacity) {
_list = new SwfList<T>(capacity);
_dict = new Dictionary<T, int>(capacity);
_comp = EqualityComparer<T>.Default;
}
public T this[int index] {
get {
return _list[index];
}
}
public int this[T item] {
get {
return _dict[item];
}
}
public int Count {
get {
return _list.Count;
}
}
public bool Contains(T value) {
return _dict.ContainsKey(value);
}
public void Add(T item) {
if ( !_dict.ContainsKey(item) ) {
_dict.Add(item, _list.Count);
_list.Push(item);
}
}
public void Remove(T item) {
int index;
if ( _dict.TryGetValue(item, out index) ) {
_dict.Remove(item);
var reordered =_list.UnorderedRemoveAt(index);
if ( !_comp.Equals(reordered, item) ) {
_dict[reordered] = index;
}
}
}
public void Clear() {
_list.Clear();
_dict.Clear();
}
public void AssignTo(SwfList<T> list) {
_list.AssignTo(list);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: dbb6cc9af87db40aaa429b450fec1de9
timeCreated: 1472813600
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,52 +0,0 @@
using UnityEngine;
namespace FlashTools.Internal {
public class SwfIntRangeAttribute : PropertyAttribute {
public int Min;
public int Max;
public SwfIntRangeAttribute(int min, int max) {
Min = min;
Max = max;
}
}
public class SwfFloatRangeAttribute : PropertyAttribute {
public float Min;
public float Max;
public SwfFloatRangeAttribute(float min, float max) {
Min = min;
Max = max;
}
}
public class SwfSortingLayerAttribute : PropertyAttribute {
}
public class SwfPowerOfTwoIfAttribute : PropertyAttribute {
public int MinPow2;
public int MaxPow2;
public string BoolProp;
public SwfPowerOfTwoIfAttribute(int min_pow2, int max_pow2, string bool_prop) {
MinPow2 = min_pow2;
MaxPow2 = max_pow2;
BoolProp = bool_prop;
}
}
public class SwfReadOnlyAttribute : PropertyAttribute {
}
public class SwfAssetGUIDAttribute : PropertyAttribute {
public bool ReadOnly;
public SwfAssetGUIDAttribute(bool read_only) {
ReadOnly = read_only;
}
}
public class SwfDisplayNameAttribute : PropertyAttribute {
public string DisplayName;
public SwfDisplayNameAttribute(string display_name) {
DisplayName = display_name;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: d267119f922984b8b812889fd05d0c86
timeCreated: 1472013332
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,127 +0,0 @@
using System;
namespace FlashTools.Internal {
public class SwfList<T> {
T[] _data;
int _size;
static readonly T[] _emptyData = new T[0];
const int _defaultCapacity = 4;
public SwfList() {
_data = _emptyData;
_size = 0;
}
public SwfList(int capacity) {
if ( capacity < 0 ) {
throw new ArgumentOutOfRangeException(
"capacity", "capacity must be >= 0");
} else if ( capacity == 0 ) {
_data = _emptyData;
_size = 0;
} else {
_data = new T[capacity];
_size = 0;
}
}
public void Push(T value) {
if ( _size == _data.Length ) {
var new_capacity = _size == 0
? _defaultCapacity : _size * 2;
var new_data = new T[new_capacity];
Array.Copy(_data, new_data, _size);
_data = new_data;
}
_data[_size++] = value;
}
public T Pop() {
if ( _size == 0 ) {
throw new InvalidOperationException("empty list");
}
var last = _data[--_size];
_data[_size] = default(T);
return last;
}
public T Peek() {
if ( _size == 0 ) {
throw new InvalidOperationException("empty list");
}
return _data[_size - 1];
}
public void Clear() {
Array.Clear(_data, 0, _size);
_size = 0;
}
public T UnorderedRemoveAt(int index) {
if ( (uint)index >= (uint)_size ) {
throw new IndexOutOfRangeException();
}
var last = _data[_size - 1];
_data[index] = last;
_data[--_size] = default(T);
return last;
}
public T this[int index] {
get {
if ( (uint)index >= (uint)_size ) {
throw new IndexOutOfRangeException();
}
return _data[index];
}
set {
if ( (uint)index >= (uint)_size ) {
throw new IndexOutOfRangeException();
}
_data[index] = value;
}
}
public int Count {
get { return _size; }
}
public int Capacity {
get { return _data.Length; }
set {
if ( value < _size ) {
throw new ArgumentOutOfRangeException("capacity");
}
if ( value != _data.Length ) {
if ( value > 0 ) {
var new_data = new T[value];
if ( _size > 0 ) {
Array.Copy(_data, new_data, _size);
}
_data = new_data;
} else {
_data = _emptyData;
}
}
}
}
public void AssignTo(SwfList<T> list) {
if ( list._data.Length < _size ) {
var new_data = new T[_size * 2];
Array.Copy(_data, new_data, _size);
list._data = new_data;
list._size = _size;
} else {
if ( _size < list._size ) {
Array.Clear(list._data, _size, list._size - _size);
}
if ( _size > 0 ) {
Array.Copy(_data, list._data, _size);
}
list._size = _size;
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: c73b0d62df5ee4a9cb8babe2dbf4a004
timeCreated: 1472813804
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,64 +0,0 @@
using UnityEngine;
namespace FlashTools.Internal {
[System.Serializable]
public struct SwfSettingsData {
public enum AtlasFilter {
Point,
Bilinear,
Trilinear
}
public enum AtlasFormat {
AutomaticCompressed,
Automatic16bit,
AutomaticTruecolor,
AutomaticCrunched
}
[SwfPowerOfTwoIfAttribute(5, 13, "AtlasPowerOfTwo")]
public int MaxAtlasSize;
[SwfIntRange(0, int.MaxValue)]
public int AtlasPadding;
[SwfFloatRange(float.Epsilon, float.MaxValue)]
public float PixelsPerUnit;
public bool GenerateMipMaps;
public bool AtlasPowerOfTwo;
public bool AtlasForceSquare;
public AtlasFilter AtlasTextureFilter;
public AtlasFormat AtlasTextureFormat;
public static SwfSettingsData identity {
get {
return new SwfSettingsData{
MaxAtlasSize = 1024,
AtlasPadding = 1,
PixelsPerUnit = 100.0f,
GenerateMipMaps = false,
AtlasPowerOfTwo = true,
AtlasForceSquare = true,
AtlasTextureFilter = AtlasFilter.Bilinear,
AtlasTextureFormat = AtlasFormat.AutomaticCompressed};
}
}
public bool CheckEquals(SwfSettingsData other) {
return
MaxAtlasSize == other.MaxAtlasSize &&
AtlasPadding == other.AtlasPadding &&
Mathf.Approximately(PixelsPerUnit, other.PixelsPerUnit) &&
GenerateMipMaps == other.GenerateMipMaps &&
AtlasPowerOfTwo == other.AtlasPowerOfTwo &&
AtlasForceSquare == other.AtlasForceSquare &&
AtlasTextureFilter == other.AtlasTextureFilter &&
AtlasTextureFormat == other.AtlasTextureFormat;
}
}
public class SwfSettings : ScriptableObject {
public SwfSettingsData Settings;
void Reset() {
Settings = SwfSettingsData.identity;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6da591d87f967451298a275621e1fd5d
timeCreated: 1471761453
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,100 +0,0 @@
using UnityEngine;
namespace FlashTools.Internal {
public static class SwfUtils {
public const float UVPrecision = 1.0f / 16384.0f;
public const float FColorPrecision = 1.0f / 512.0f;
const ushort UShortMax = ushort.MaxValue;
const float InvFColorPrecision = 1.0f / FColorPrecision;
//
//
//
public static uint PackUShortsToUInt(ushort x, ushort y) {
var xx = (uint)x;
var yy = (uint)y;
return (xx << 16) + yy;
}
public static void UnpackUShortsFromUInt(
uint pack,
out ushort x, out ushort y)
{
x = (ushort)((pack >> 16) & 0xFFFF);
y = (ushort)((pack ) & 0xFFFF);
}
//
//
//
public static uint PackUV(float u, float v) {
var uu = (uint)(Mathf.Clamp01(u) * UShortMax);
var vv = (uint)(Mathf.Clamp01(v) * UShortMax);
return (uu << 16) + vv;
}
public static void UnpackUV(uint pack, out float u, out float v) {
u = (float)((pack >> 16) & 0xFFFF) / UShortMax;
v = (float)((pack ) & 0xFFFF) / UShortMax;
}
//
//
//
public static ushort PackFloatColorToUShort(float v) {
return (ushort)Mathf.Clamp(
v * (1.0f / FColorPrecision),
short.MinValue,
short.MaxValue);
}
public static float UnpackFloatColorFromUShort(ushort pack) {
return (short)pack / InvFColorPrecision;
}
//
//
//
public static void PackFColorToUInts(
Color v,
out uint pack0, out uint pack1)
{
PackFColorToUInts(v.r, v.g, v.b, v.a, out pack0, out pack1);
}
public static void PackFColorToUInts(
SwfVec4Data v,
out uint pack0, out uint pack1)
{
PackFColorToUInts(v.x, v.y, v.z, v.w, out pack0, out pack1);
}
public static void PackFColorToUInts(
float v0, float v1, float v2, float v3,
out uint pack0, out uint pack1)
{
pack0 = PackUShortsToUInt(
PackFloatColorToUShort(v0),
PackFloatColorToUShort(v1));
pack1 = PackUShortsToUInt(
PackFloatColorToUShort(v2),
PackFloatColorToUShort(v3));
}
public static void UnpackFColorFromUInts(
uint pack0, uint pack1,
out float c0, out float c1, out float c2, out float c3)
{
c0 = (short)((pack0 >> 16) & 0xFFFF) / InvFColorPrecision;
c1 = (short)((pack0 ) & 0xFFFF) / InvFColorPrecision;
c2 = (short)((pack1 >> 16) & 0xFFFF) / InvFColorPrecision;
c3 = (short)((pack1 ) & 0xFFFF) / InvFColorPrecision;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 7403812bd90474c01b689738c58fd8dc
timeCreated: 1473684950
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,254 +0,0 @@
using UnityEngine;
using FlashTools.Internal;
using System.Collections.Generic;
namespace FlashTools {
[System.Serializable]
public struct SwfVec2Data {
public float x;
public float y;
public SwfVec2Data(float x, float y) {
this.x = x;
this.y = y;
}
public static SwfVec2Data one {
get { return new SwfVec2Data(1.0f, 1.0f); }
}
public static SwfVec2Data zero {
get { return new SwfVec2Data(0.0f, 0.0f); }
}
}
[System.Serializable]
public struct SwfVec4Data {
public float x;
public float y;
public float z;
public float w;
public SwfVec4Data(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public static SwfVec4Data one {
get { return new SwfVec4Data(1.0f, 1.0f, 1.0f, 1.0f); }
}
public static SwfVec4Data zero {
get { return new SwfVec4Data(0.0f, 0.0f, 0.0f, 0.0f); }
}
}
[System.Serializable]
public struct SwfRectData {
public float xMin;
public float xMax;
public float yMin;
public float yMax;
public static SwfRectData identity {
get {
return new SwfRectData{
xMin = 0.0f,
xMax = 0.0f,
yMin = 0.0f,
yMax = 0.0f};
}
}
public static SwfRectData FromURect(Rect rect) {
return new SwfRectData{
xMin = rect.xMin,
xMax = rect.xMax,
yMin = rect.yMin,
yMax = rect.yMax};
}
}
[System.Serializable]
public struct SwfMatrixData {
public SwfVec2Data sc;
public SwfVec2Data sk;
public SwfVec2Data tr;
public static SwfMatrixData identity {
get {
return new SwfMatrixData{
sc = SwfVec2Data.one,
sk = SwfVec2Data.zero,
tr = SwfVec2Data.zero};
}
}
public Matrix4x4 ToUMatrix() {
var mat = Matrix4x4.identity;
mat.m00 = sc.x;
mat.m11 = sc.y;
mat.m10 = sk.x;
mat.m01 = sk.y;
mat.m03 = tr.x;
mat.m13 = tr.y;
return mat;
}
public static SwfMatrixData FromUMatrix(Matrix4x4 mat) {
return new SwfMatrixData{
sc = new SwfVec2Data(mat.m00, mat.m11),
sk = new SwfVec2Data(mat.m10, mat.m01),
tr = new SwfVec2Data(mat.m03, mat.m13)};
}
}
[System.Serializable]
public struct SwfBlendModeData {
public enum Types : byte {
Normal,
Layer,
Multiply,
Screen,
Lighten,
Darken, // GrabPass
Difference, // GrabPass
Add,
Subtract,
Invert, // GrabPass
Overlay, // GrabPass
Hardlight // GrabPass
}
public Types type;
public SwfBlendModeData(Types type) {
this.type = type;
}
public static SwfBlendModeData identity {
get {
return new SwfBlendModeData{
type = Types.Normal};
}
}
public static SwfBlendModeData operator*(
SwfBlendModeData a, SwfBlendModeData b)
{
return (a.type == Types.Normal || a.type == Types.Layer) ? b : a;
}
}
[System.Serializable]
public struct SwfColorTransData {
public SwfVec4Data mulColor;
public SwfVec4Data addColor;
public Color ApplyToColor(Color color) {
return new Color(
Mathf.Clamp01(color.r * mulColor.x + addColor.x),
Mathf.Clamp01(color.g * mulColor.y + addColor.y),
Mathf.Clamp01(color.b * mulColor.z + addColor.z),
Mathf.Clamp01(color.a * mulColor.w + addColor.w));
}
public static SwfColorTransData identity {
get {
return new SwfColorTransData{
mulColor = SwfVec4Data.one,
addColor = SwfVec4Data.zero};
}
}
public static SwfColorTransData operator*(
SwfColorTransData a, SwfColorTransData b)
{
return new SwfColorTransData{
mulColor = new SwfVec4Data(
b.mulColor.x * a.mulColor.x,
b.mulColor.y * a.mulColor.y,
b.mulColor.z * a.mulColor.z,
b.mulColor.w * a.mulColor.w),
addColor = new SwfVec4Data(
b.addColor.x * a.mulColor.x + a.addColor.x,
b.addColor.y * a.mulColor.y + a.addColor.y,
b.addColor.z * a.mulColor.z + a.addColor.z,
b.addColor.w * a.mulColor.w + a.addColor.w)};
}
}
[System.Serializable]
public class SwfInstanceData {
public enum Types {
Mask,
Group,
Masked,
MaskReset
}
public Types Type = Types.Group;
public ushort ClipDepth = 0;
public ushort Bitmap = 0;
public SwfMatrixData Matrix = SwfMatrixData.identity;
public SwfBlendModeData BlendMode = SwfBlendModeData.identity;
public SwfColorTransData ColorTrans = SwfColorTransData.identity;
}
[System.Serializable]
public class SwfFrameData {
public string Name = string.Empty;
public List<SwfInstanceData> Instances = new List<SwfInstanceData>();
}
[System.Serializable]
public class SwfSymbolData {
public string Name = string.Empty;
public List<SwfFrameData> Frames = new List<SwfFrameData>();
}
[System.Serializable]
public class SwfBitmapData {
public ushort Id = 0;
public byte[] ARGB32 = new byte[0];
public ushort Redirect = 0;
public int RealWidth = 0;
public int RealHeight = 0;
public SwfRectData SourceRect = SwfRectData.identity;
}
[System.Serializable]
public class SwfAssetData {
public float FrameRate = 0.0f;
public List<SwfSymbolData> Symbols = new List<SwfSymbolData>();
public List<SwfBitmapData> Bitmaps = new List<SwfBitmapData>();
}
public class SwfAsset : ScriptableObject {
[System.Serializable]
public struct ConvertingState {
public int Stage;
}
[HideInInspector]
public byte[] Data;
[SwfReadOnly]
public Texture2D Atlas;
[HideInInspector]
public List<SwfClipAsset> Clips;
[HideInInspector]
public SwfSettingsData Settings;
[SwfDisplayName("Settings")]
public SwfSettingsData Overridden;
[HideInInspector]
public ConvertingState Converting;
void Reset() {
Data = new byte[0];
Atlas = null;
Clips = new List<SwfClipAsset>();
Settings = SwfSettingsData.identity;
Overridden = SwfSettingsData.identity;
Converting = new ConvertingState();
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: f76a446beb44b46088888ed3f078b2a0
timeCreated: 1458054544
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,284 +0,0 @@
using UnityEngine;
using FlashTools.Internal;
namespace FlashTools {
[ExecuteInEditMode, DisallowMultipleComponent]
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class SwfClip : MonoBehaviour {
MeshFilter _meshFilter = null;
MeshRenderer _meshRenderer = null;
bool _dirtyMesh = true;
SwfClipAsset.Sequence _curSequence = null;
MaterialPropertyBlock _curPropBlock = null;
// ---------------------------------------------------------------------
//
// Properties
//
// ---------------------------------------------------------------------
[Header("Sorting")]
[SerializeField][SwfSortingLayer]
public string _sortingLayer = string.Empty;
public string sortingLayer {
get { return _sortingLayer; }
set {
_sortingLayer = value;
ChangeSortingProperties();
}
}
[SerializeField]
public int _sortingOrder = 0;
public int sortingOrder {
get { return _sortingOrder; }
set {
_sortingOrder = value;
ChangeSortingProperties();
}
}
[Header("Animation")]
[SerializeField]
Color _tint = Color.white;
public Color tint {
get { return _tint; }
set {
_tint = value;
ChangeTint();
}
}
[SerializeField]
SwfClipAsset _clip = null;
public SwfClipAsset clip {
get { return _clip; }
set {
_clip = value;
_sequence = string.Empty;
_currentFrame = 0;
ChangeClip();
}
}
[SerializeField][HideInInspector]
string _sequence = string.Empty;
public string sequence {
get { return _sequence; }
set {
_sequence = value;
_currentFrame = 0;
ChangeSequence();
}
}
[SerializeField][HideInInspector]
int _currentFrame = 0;
public int currentFrame {
get { return _currentFrame; }
set {
_currentFrame = value;
ChangeCurrentFrame();
}
}
public int frameCount {
get {
return _curSequence != null && _curSequence.Frames != null
? _curSequence.Frames.Count
: 0;
}
}
public float frameRate {
get {
return clip
? clip.FrameRate
: 1.0f;
}
}
// ---------------------------------------------------------------------
//
// Functions
//
// ---------------------------------------------------------------------
public void ToBeginFrame() {
currentFrame = 0;
}
public void ToEndFrame() {
currentFrame = frameCount > 0
? frameCount - 1
: 0;
}
public bool ToPrevFrame() {
if ( currentFrame > 0 ) {
--currentFrame;
return true;
}
return false;
}
public bool ToNextFrame() {
if ( currentFrame < frameCount - 1 ) {
++currentFrame;
return true;
}
return false;
}
// ---------------------------------------------------------------------
//
// Internal
//
// ---------------------------------------------------------------------
public void InternalLateUpdate() {
if ( _meshFilter && _meshRenderer && _dirtyMesh ) {
var baked_frame = GetCurrentBakedFrame();
if ( baked_frame != null ) {
_meshFilter .sharedMesh = baked_frame.CachedMesh;
_meshRenderer.sharedMaterials = baked_frame.Materials;
} else {
_meshFilter .sharedMesh = null;
_meshRenderer.sharedMaterials = new Material[0];
}
_dirtyMesh = false;
}
}
public void UpdateAllProperties() {
ClearCache();
ChangeTint();
ChangeClip();
ChangeSequence();
ChangeCurrentFrame();
ChangeSortingProperties();
}
void ClearCache() {
_meshFilter = GetComponent<MeshFilter>();
_meshRenderer = GetComponent<MeshRenderer>();
_dirtyMesh = true;
_curSequence = null;
_curPropBlock = null;
}
void ChangeTint() {
UpdatePropBlock();
}
void ChangeClip() {
if ( _meshRenderer ) {
_meshRenderer.enabled = !!clip;
}
ChangeSequence();
UpdatePropBlock();
}
void ChangeSequence() {
_curSequence = null;
if ( clip && clip.Sequences != null ) {
if ( !string.IsNullOrEmpty(sequence) ) {
for ( int i = 0, e = clip.Sequences.Count; i < e; ++i ) {
var clip_sequence = clip.Sequences[i];
if ( clip_sequence != null && clip_sequence.Name == sequence ) {
_curSequence = clip_sequence;
break;
}
}
if ( _curSequence == null ) {
Debug.LogWarningFormat(this,
"<b>[FlashTools]</b> Sequence '{0}' not found",
sequence);
}
}
if ( _curSequence == null ) {
for ( int i = 0, e = clip.Sequences.Count; i < e; ++i ) {
var clip_sequence = clip.Sequences[i];
if ( clip_sequence != null ) {
_sequence = clip_sequence.Name;
_curSequence = clip_sequence;
break;
}
}
}
}
ChangeCurrentFrame();
}
void ChangeCurrentFrame() {
_dirtyMesh = true;
_currentFrame = frameCount > 0
? Mathf.Clamp(currentFrame, 0, frameCount - 1)
: 0;
}
void ChangeSortingProperties() {
if ( _meshRenderer ) {
_meshRenderer.sortingOrder = sortingOrder;
_meshRenderer.sortingLayerName = sortingLayer;
}
}
void UpdatePropBlock() {
if ( _meshRenderer ) {
if ( _curPropBlock == null ) {
_curPropBlock = new MaterialPropertyBlock();
}
_meshRenderer.GetPropertyBlock(_curPropBlock);
_curPropBlock.SetColor(
"_Tint",
tint);
_curPropBlock.SetTexture(
"_MainTex",
clip && clip.Atlas ? clip.Atlas : Texture2D.whiteTexture);
_meshRenderer.SetPropertyBlock(_curPropBlock);
}
}
SwfClipAsset.Frame GetCurrentBakedFrame() {
var frames = _curSequence != null ? _curSequence.Frames : null;
return frames != null && currentFrame >= 0 && currentFrame < frames.Count
? frames[currentFrame]
: null;
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void Awake() {
UpdateAllProperties();
}
void OnEnable() {
var swf_manager = SwfManager.GetInstance(true);
if ( swf_manager ) {
swf_manager.AddClip(this);
}
}
void OnDisable() {
var swf_manager = SwfManager.GetInstance(false);
if ( swf_manager ) {
swf_manager.RemoveClip(this);
}
}
void Reset() {
UpdateAllProperties();
}
void OnValidate() {
UpdateAllProperties();
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 950d548c7e22f4e25a47de474b49e86e
timeCreated: 1472040299
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,203 +0,0 @@
using UnityEngine;
using FlashTools.Internal;
using System.Collections.Generic;
namespace FlashTools {
public class SwfClipAsset : ScriptableObject {
[System.Serializable]
public class SubMeshData {
public int StartVertex;
public int IndexCount;
}
[System.Serializable]
public class MeshData {
public SubMeshData[] SubMeshes = new SubMeshData[0];
public Vector2[] Vertices = new Vector2[0];
public uint[] UVs = new uint[0];
public uint[] AddColors = new uint[0];
public uint[] MulColors = new uint[0];
public void FillMesh(Mesh mesh) {
if ( SubMeshes.Length > 0 ) {
mesh.subMeshCount = SubMeshes.Length;
SwfClipAssetCache.FillVertices(Vertices);
mesh.SetVertices(SwfClipAssetCache.Vertices);
for ( int i = 0, e = SubMeshes.Length; i < e; ++i ) {
SwfClipAssetCache.FillTriangles(
SubMeshes[i].StartVertex,
SubMeshes[i].IndexCount);
mesh.SetTriangles(SwfClipAssetCache.Indices, i);
}
SwfClipAssetCache.FillUVs(UVs);
mesh.SetUVs(0, SwfClipAssetCache.UVs);
SwfClipAssetCache.FillAddColors(AddColors);
mesh.SetUVs(1, SwfClipAssetCache.AddColors);
SwfClipAssetCache.FillMulColors(MulColors);
mesh.SetColors(SwfClipAssetCache.MulColors);
}
}
}
[System.Serializable]
public class Frame {
public MeshData MeshData = new MeshData();
public Material[] Materials = new Material[0];
public Frame() {
MeshData = new MeshData();
Materials = new Material[0];
}
public Frame(MeshData mesh_data, Material[] materials) {
MeshData = mesh_data;
Materials = materials;
}
Mesh _cachedMesh = null;
public Mesh CachedMesh {
get {
if ( !_cachedMesh ) {
_cachedMesh = new Mesh();
MeshData.FillMesh(_cachedMesh);
}
return _cachedMesh;
}
}
}
[System.Serializable]
public class Sequence {
public string Name = string.Empty;
public List<Frame> Frames = new List<Frame>();
}
[SwfReadOnly]
public string Name;
[SwfReadOnly]
public Texture2D Atlas;
[SwfReadOnly]
public float FrameRate;
[HideInInspector]
public List<Sequence> Sequences;
void Reset() {
Name = string.Empty;
Atlas = null;
FrameRate = 1.0f;
Sequences = new List<Sequence>();
}
}
// ---------------------------------------------------------------------
//
// SwfClipAssetCache
//
// ---------------------------------------------------------------------
static class SwfClipAssetCache {
const int PreallocatedVertices = 500;
public static List<int> Indices = new List<int>(PreallocatedVertices * 6 / 4);
public static void FillTriangles(int start_vertex, int index_count) {
Indices.Clear();
if ( Indices.Capacity < index_count ) {
Indices.Capacity = index_count * 2;
}
for ( var i = 0; i < index_count; i += 6 ) {
Indices.Add(start_vertex + 2);
Indices.Add(start_vertex + 1);
Indices.Add(start_vertex + 0);
Indices.Add(start_vertex + 0);
Indices.Add(start_vertex + 3);
Indices.Add(start_vertex + 2);
start_vertex += 4;
}
}
static Vector3 Vertex = Vector3.zero;
public static List<Vector3> Vertices = new List<Vector3>(PreallocatedVertices);
public static void FillVertices(Vector2[] vertices) {
Vertices.Clear();
if ( Vertices.Capacity < vertices.Length ) {
Vertices.Capacity = vertices.Length * 2;
}
for ( int i = 0, e = vertices.Length; i < e; ++i ) {
var vert = vertices[i];
Vertex.x = vert.x;
Vertex.y = vert.y;
Vertices.Add(Vertex);
}
}
static Vector2 UV0 = Vector2.zero;
static Vector2 UV1 = Vector2.zero;
static Vector2 UV2 = Vector2.zero;
static Vector2 UV3 = Vector2.zero;
public static List<Vector2> UVs = new List<Vector2>(PreallocatedVertices);
public static void FillUVs(uint[] uvs) {
UVs.Clear();
if ( UVs.Capacity < uvs.Length * 2 ) {
UVs.Capacity = uvs.Length * 2 * 2;
}
for ( int i = 0, e = uvs.Length; i < e; i += 2 ) {
float min_x, min_y, max_x, max_y;
SwfUtils.UnpackUV(uvs[i+0], out min_x, out min_y);
SwfUtils.UnpackUV(uvs[i+1], out max_x, out max_y);
UV0.x = min_x; UV0.y = min_y;
UV1.x = max_x; UV1.y = min_y;
UV2.x = max_x; UV2.y = max_y;
UV3.x = min_x; UV3.y = max_y;
UVs.Add(UV0);
UVs.Add(UV1);
UVs.Add(UV2);
UVs.Add(UV3);
}
}
static Vector4 AddColor = Vector4.one;
public static List<Vector4> AddColors = new List<Vector4>(PreallocatedVertices);
public static void FillAddColors(uint[] colors) {
AddColors.Clear();
if ( AddColors.Capacity < colors.Length * 2 ) {
AddColors.Capacity = colors.Length * 2 * 2;
}
for ( int i = 0, e = colors.Length; i < e; i += 2 ) {
SwfUtils.UnpackFColorFromUInts(
colors[i+0], colors[i+1],
out AddColor.x, out AddColor.y,
out AddColor.z, out AddColor.w);
AddColors.Add(AddColor);
AddColors.Add(AddColor);
AddColors.Add(AddColor);
AddColors.Add(AddColor);
}
}
static Color MulColor = Color.white;
public static List<Color> MulColors = new List<Color>(PreallocatedVertices);
public static void FillMulColors(uint[] colors) {
MulColors.Clear();
if ( MulColors.Capacity < colors.Length * 2 ) {
MulColors.Capacity = colors.Length * 2 * 2;
}
for ( int i = 0, e = colors.Length; i < e; i += 2 ) {
SwfUtils.UnpackFColorFromUInts(
colors[i+0], colors[i+1],
out MulColor.r, out MulColor.g,
out MulColor.b, out MulColor.a);
MulColors.Add(MulColor);
MulColors.Add(MulColor);
MulColors.Add(MulColor);
MulColors.Add(MulColor);
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 2c8c473f52d644fc783452f78f8f015f
timeCreated: 1472673248
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,279 +0,0 @@
using UnityEngine;
using FlashTools.Internal;
namespace FlashTools {
[ExecuteInEditMode, DisallowMultipleComponent]
[RequireComponent(typeof(SwfClip))]
public class SwfClipController : MonoBehaviour {
SwfClip _clip = null;
bool _isPlaying = false;
float _tickTimer = 0.0f;
// ---------------------------------------------------------------------
//
// Events
//
// ---------------------------------------------------------------------
public event System.Action<SwfClipController> OnStopPlayingEvent;
public event System.Action<SwfClipController> OnPlayStoppedEvent;
public event System.Action<SwfClipController> OnRewindPlayingEvent;
// ---------------------------------------------------------------------
//
// Properties
//
// ---------------------------------------------------------------------
public enum PlayModes {
Forward,
Backward
}
public enum LoopModes {
Once,
Loop
}
[SerializeField]
bool _autoPlay = false;
public bool autoPlay {
get { return _autoPlay; }
set { _autoPlay = value; }
}
[SerializeField]
[SwfFloatRange(0.0f, float.MaxValue)]
float _rateScale = 1.0f;
public float rateScale {
get { return _rateScale; }
set { _rateScale = Mathf.Clamp(value, 0.0f, float.MaxValue); }
}
[SerializeField]
string _groupName = string.Empty;
public string groupName {
get { return _groupName; }
set { _groupName = value; }
}
[SerializeField]
PlayModes _playMode = PlayModes.Forward;
public PlayModes playMode {
get { return _playMode; }
set { _playMode = value; }
}
[SerializeField]
LoopModes _loopMode = LoopModes.Once;
public LoopModes loopMode {
get { return _loopMode; }
set { _loopMode = value; }
}
public SwfClip clip {
get { return _clip; }
}
public bool isPlaying {
get { return _isPlaying; }
}
public bool isStopped {
get { return !_isPlaying; }
}
// ---------------------------------------------------------------------
//
// Functions
//
// ---------------------------------------------------------------------
public void GotoAndStop(int frame) {
if ( clip ) {
clip.currentFrame = frame;
}
Stop(false);
}
public void GotoAndStop(string sequence, int frame) {
if ( clip ) {
clip.sequence = sequence;
}
GotoAndStop(frame);
}
//
//
//
public void GotoAndPlay(int frame) {
if ( clip ) {
clip.currentFrame = frame;
}
Play(false);
}
public void GotoAndPlay(string sequence, int frame) {
if ( clip ) {
clip.sequence = sequence;
}
GotoAndPlay(frame);
}
//
//
//
public void Stop(bool rewind) {
var is_playing = isPlaying;
if ( is_playing ) {
_isPlaying = false;
_tickTimer = 0.0f;
}
if ( rewind ) {
Rewind();
}
if ( is_playing && OnStopPlayingEvent != null ) {
OnStopPlayingEvent(this);
}
}
public void Stop(string sequence) {
if ( clip ) {
clip.sequence = sequence;
}
Stop(true);
}
//
//
//
public void Play(bool rewind) {
var is_stopped = isStopped;
if ( is_stopped ) {
_isPlaying = true;
_tickTimer = 0.0f;
}
if ( rewind ) {
Rewind();
}
if ( is_stopped && OnPlayStoppedEvent != null ) {
OnPlayStoppedEvent(this);
}
}
public void Play(string sequence) {
if ( clip ) {
clip.sequence = sequence;
}
Play(true);
}
//
//
//
public void Rewind() {
switch ( playMode ) {
case PlayModes.Forward:
if ( clip ) {
clip.ToBeginFrame();
}
break;
case PlayModes.Backward:
if ( clip ) {
clip.ToEndFrame();
}
break;
default:
throw new UnityException(string.Format(
"SwfClipController. Incorrect play mode: {0}",
playMode));
}
if ( isPlaying && OnRewindPlayingEvent != null ) {
OnRewindPlayingEvent(this);
}
}
// ---------------------------------------------------------------------
//
// Internal
//
// ---------------------------------------------------------------------
public void InternalUpdate(float dt) {
if ( isPlaying ) {
UpdateTimer(dt);
}
}
void UpdateTimer(float dt) {
var frame_rate = clip ? clip.frameRate : 1.0f;
_tickTimer += frame_rate * rateScale * dt;
while ( _tickTimer > 1.0f ) {
_tickTimer -= 1.0f;
TimerTick();
}
}
void TimerTick() {
if ( !NextClipFrame() ) {
switch ( loopMode ) {
case LoopModes.Once:
Stop(false);
break;
case LoopModes.Loop:
Rewind();
break;
default:
throw new UnityException(string.Format(
"SwfClipController. Incorrect loop mode: {0}",
loopMode));
}
}
}
bool NextClipFrame() {
switch ( playMode ) {
case PlayModes.Forward:
return clip ? clip.ToNextFrame() : false;
case PlayModes.Backward:
return clip ? clip.ToPrevFrame() : false;
default:
throw new UnityException(string.Format(
"SwfClipController. Incorrect play mode: {0}",
playMode));
}
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void Awake() {
_clip = GetComponent<SwfClip>();
if ( autoPlay && Application.isPlaying ) {
Play(false);
}
}
void OnEnable() {
var swf_manager = SwfManager.GetInstance(true);
if ( swf_manager ) {
swf_manager.AddController(this);
}
}
void OnDisable() {
var swf_manager = SwfManager.GetInstance(false);
if ( swf_manager ) {
swf_manager.RemoveController(this);
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: aedb1b4cb4ec34540952f7e8624fea8e
timeCreated: 1472188170
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,222 +0,0 @@
using UnityEngine;
using FlashTools.Internal;
using System.Collections.Generic;
namespace FlashTools {
[ExecuteInEditMode, DisallowMultipleComponent]
public class SwfManager : MonoBehaviour {
SwfAssocList<SwfClip> _clips = new SwfAssocList<SwfClip>();
SwfAssocList<SwfClipController> _controllers = new SwfAssocList<SwfClipController>();
SwfList<SwfClipController> _safeUpdates = new SwfList<SwfClipController>();
bool _isPaused = false;
float _rateScale = 1.0f;
HashSet<string> _groupPauses = new HashSet<string>();
Dictionary<string, float> _groupRateScales = new Dictionary<string, float>();
// ---------------------------------------------------------------------
//
// Instance
//
// ---------------------------------------------------------------------
static SwfManager _instance;
public static SwfManager GetInstance(bool allow_create) {
if ( !_instance ) {
_instance = FindObjectOfType<SwfManager>();
if ( allow_create && !_instance ) {
var go = new GameObject("[SwfManager]");
_instance = go.AddComponent<SwfManager>();
}
}
return _instance;
}
// ---------------------------------------------------------------------
//
// Properties
//
// ---------------------------------------------------------------------
public int clipCount {
get { return _clips.Count; }
}
public int controllerCount {
get { return _controllers.Count; }
}
public bool isPaused {
get { return _isPaused; }
set { _isPaused = value; }
}
public bool isPlaying {
get { return !_isPaused; }
set { _isPaused = !value; }
}
public float rateScale {
get { return _rateScale; }
set { _rateScale = Mathf.Clamp(value, 0.0f, float.MaxValue); }
}
// ---------------------------------------------------------------------
//
// Functions
//
// ---------------------------------------------------------------------
public void Pause() {
isPaused = true;
}
public void Resume() {
isPlaying = true;
}
public void PauseGroup(string group_name) {
if ( !string.IsNullOrEmpty(group_name) ) {
_groupPauses.Add(group_name);
}
}
public void ResumeGroup(string group_name) {
if ( !string.IsNullOrEmpty(group_name) ) {
_groupPauses.Remove(group_name);
}
}
public bool IsGroupPaused(string group_name) {
return _groupPauses.Contains(group_name);
}
public bool IsGroupPlaying(string group_name) {
return !IsGroupPaused(group_name);
}
public void SetGroupRateScale(string group_name, float rate_scale) {
if ( !string.IsNullOrEmpty(group_name) ) {
_groupRateScales[group_name] = Mathf.Clamp(rate_scale, 0.0f, float.MaxValue);
}
}
public float GetGroupRateScale(string group_name) {
float rate_scale;
return _groupRateScales.TryGetValue(group_name, out rate_scale)
? rate_scale
: 1.0f;
}
// ---------------------------------------------------------------------
//
// Internal
//
// ---------------------------------------------------------------------
public void AddClip(SwfClip clip) {
_clips.Add(clip);
}
public void RemoveClip(SwfClip clip) {
_clips.Remove(clip);
}
public void GetAllClips(SwfList<SwfClip> clips) {
_clips.AssignTo(clips);
}
public void AddController(SwfClipController controller) {
_controllers.Add(controller);
}
public void RemoveController(SwfClipController controller) {
_controllers.Remove(controller);
}
public void GetAllControllers(SwfList<SwfClipController> controllers) {
_controllers.AssignTo(controllers);
}
void GrabEnabledClips() {
var clips = FindObjectsOfType<SwfClip>();
for ( int i = 0, e = clips.Length; i < e; ++i ) {
var clip = clips[i];
if ( clip.enabled ) {
_clips.Add(clip);
}
}
}
void GrabEnabledControllers() {
var controllers = FindObjectsOfType<SwfClipController>();
for ( int i = 0, e = controllers.Length; i < e; ++i ) {
var controller = controllers[i];
if ( controller.enabled ) {
_controllers.Add(controller);
}
}
}
void DropClips() {
_clips.Clear();
}
void DropControllers() {
_controllers.Clear();
}
void UpdateControllers(float dt) {
_controllers.AssignTo(_safeUpdates);
for ( int i = 0, e = _safeUpdates.Count; i < e; ++i ) {
var ctrl = _safeUpdates[i];
if ( ctrl ) {
var group_name = ctrl.groupName;
if ( string.IsNullOrEmpty(group_name) ) {
ctrl.InternalUpdate(dt);
} else if ( IsGroupPlaying(group_name) ) {
var group_rate_scale = GetGroupRateScale(group_name);
ctrl.InternalUpdate(group_rate_scale * dt);
}
}
}
_safeUpdates.Clear();
}
void LateUpdateClips() {
for ( int i = 0, e = _clips.Count; i < e; ++i ) {
var clip = _clips[i];
if ( clip ) {
clip.InternalLateUpdate();
}
}
}
// ---------------------------------------------------------------------
//
// Messages
//
// ---------------------------------------------------------------------
void OnEnable() {
GrabEnabledClips();
GrabEnabledControllers();
}
void OnDisable() {
DropClips();
DropControllers();
}
void Update() {
if ( isPlaying ) {
var dt = Time.deltaTime;
UpdateControllers(rateScale * dt);
}
}
void LateUpdate() {
LateUpdateClips();
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 1b5299a7bd0194a5a8490da9b3d1501e
timeCreated: 1472049641
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: