public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { IUriLoader loader = new BufferedStreamLoader( ctx.assetPath, Path.GetDirectoryName(ctx.assetPath)); ImportGltf.GltfImportResult result = ImportGltf.Import( ctx.assetPath, loader, null, kOptions); // The "identifier" param passed here is supposed to be: // - Unique to this asset // - Deterministic (if possible) foreach (var obj in result.textures) { if (!AssetDatabase.Contains(obj)) { ctx.AddObjectToAsset("Texture/" + obj.name, obj); } } foreach (var obj in result.materials) { ctx.AddObjectToAsset("Material/" + obj.name, obj); } foreach (var obj in result.meshes) { ctx.AddObjectToAsset("Mesh/" + obj.name, obj); } string objectName = Path.GetFileNameWithoutExtension(ctx.assetPath); result.root.name = objectName; ctx.AddObjectToAsset("ROOT", result.root); ctx.SetMainObject(result.root); }
public void AddToContext(UnityEditor.AssetImporters.AssetImportContext ctx) { ctx.AddObjectToAsset(_spritesheet.name, _spritesheet); foreach (var sprite in _sprites) { ctx.AddObjectToAsset(sprite.name, sprite); } foreach (var animation in _animations) { ctx.AddObjectToAsset(animation.name, animation); } ctx.SetMainObject(_spritesheet); }
private void GenerateAseAnimations(UnityEditor.AssetImporters.AssetImportContext ctx, AseFile aseFile, Sprite[] sprites) { if (animationSettings == null) { animationSettings = new AseFileAnimationSettings[0]; } var animSettings = new List <AseFileAnimationSettings>(animationSettings); var animations = aseFile.GetAnimations(); if (animations.Length <= 0) { return; } if (animationSettings != null) { RemoveUnusedAnimationSettings(animSettings, animations); } foreach (var animation in animations) { // AseAnim AseAnimation aseAnim = new AseAnimation(); aseAnim.name = aseAnim.Name = animation.TagName; AseFileAnimationSettings importSettings = GetAnimationSettingFor(animSettings, animation); importSettings.about = GetAnimationAbout(animation); int length = animation.FrameTo - animation.FrameFrom + 1; aseAnim.Points = new AseAnimation.KeyPoint[length]; aseAnim.LoopType = (AseAnimation.LoopAnimation)animation.Animation; aseAnim.Loop = length > 1; float time = 0; int from = (animation.Animation != LoopAnimation.Reverse) ? animation.FrameFrom : animation.FrameTo; int step = (animation.Animation != LoopAnimation.Reverse) ? 1 : -1; int keyIndex = from; for (int i = 0; i < length; i++) { if (i >= length) { keyIndex = from; } aseAnim.Points[i] = new AseAnimation.KeyPoint(sprites[keyIndex], aseFile.Frames[keyIndex].FrameDuration / 1000f); time += aseFile.Frames[keyIndex].FrameDuration / 1000f; keyIndex += step; } ctx.AddObjectToAsset(aseAnim.Name, aseAnim); } animationSettings = animSettings.ToArray(); }
private void ImportTileset(UnityEditor.AssetImporters.AssetImportContext ctx, Texture2D atlas) { int cols = atlas.width / textureSettings.tileSize.x; int rows = atlas.height / textureSettings.tileSize.y; int width = textureSettings.tileSize.x; int height = textureSettings.tileSize.y; int index = 0; for (int y = rows - 1; y >= 0; y--) { for (int x = 0; x < cols; x++) { Rect tileRect = new Rect(x * width, y * height, width, height); Sprite sprite = Sprite.Create(atlas, tileRect, textureSettings.spritePivot, textureSettings.pixelsPerUnit, textureSettings.extrudeEdges, textureSettings.meshType, Vector4.zero, textureSettings.generatePhysics); sprite.name = string.Format("{0}_{1}", name, index); ctx.AddObjectToAsset(sprite.name, sprite); index++; } } }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { TextAsset lua = new TextAsset(File.ReadAllText(ctx.assetPath)); ctx.AddObjectToAsset("main", lua); ctx.SetMainObject(lua); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { if (Application.isPlaying) { var path = ctx.assetPath.Substring(21, ctx.assetPath.Length - 21 - 4); var moduleName = path.Replace('/', '.'); lock ( modifiedModules ) { modifiedModules.Add(moduleName); } } ExecLuaCheck(ctx.assetPath); var text = File.ReadAllText(ctx.assetPath); var asset = new TextAsset(text); using (var reader = new StringReader(asset.text)) { var line = reader.ReadLine(); while (line != null) { if (line.StartsWith("---@class")) { var statements = line.Split(' '); var className = statements[1]; LuaClassEditorFactory.ReloadDescriptor(className); break; } line = reader.ReadLine(); } } ctx.AddObjectToAsset("main obj", asset); ctx.SetMainObject(asset); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext context) { TextAsset subAsset = new TextAsset(File.ReadAllText(context.assetPath)); context.AddObjectToAsset("text", subAsset); context.SetMainObject(subAsset); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var text = File.ReadAllText(ctx.assetPath); var asset = new TextAsset(text); ctx.AddObjectToAsset("main obj", asset); ctx.SetMainObject(asset); }
public static void AddAsset(this UnityEditor.AssetImporters.AssetImportContext ctx, string identifier, Object obj) { #if UNITY_2018_2_OR_NEWER ctx.AddObjectToAsset(identifier, obj); #else ctx.AddSubAsset(identifier, obj); #endif }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var name = Path.GetFileNameWithoutExtension(ctx.assetPath); var meshes = Importer.Import(ctx.assetPath, m_CoordinateSpace, m_UpAxis, m_Smooth).ToArray(); if (meshes.Length < 1) { return; } if (meshes.Length < 2) { var go = GameObject.CreatePrimitive(PrimitiveType.Cube); Object.DestroyImmediate(go.GetComponent <BoxCollider>()); go.name = name; meshes[0].name = "Mesh-" + name; go.GetComponent <MeshFilter>().sharedMesh = meshes[0]; ctx.AddObjectToAsset(go.name, go); ctx.AddObjectToAsset(meshes[0].name, meshes[0]); ctx.SetMainObject(go); } else { var parent = new GameObject(); parent.name = name; for (int i = 0, c = meshes.Length; i < c; i++) { var go = GameObject.CreatePrimitive(PrimitiveType.Cube); Object.DestroyImmediate(go.GetComponent <BoxCollider>()); go.transform.SetParent(parent.transform, false); go.name = name + "(" + i + ")"; var mesh = meshes[i]; mesh.name = "Mesh-" + name + "(" + i + ")"; go.GetComponent <MeshFilter>().sharedMesh = mesh; // ctx.AddObjectToAsset(go.name, go); ctx.AddObjectToAsset(mesh.name, mesh); } ctx.AddObjectToAsset(parent.name, parent); ctx.SetMainObject(parent); } }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { name = GetFileName(ctx.assetPath); AseFile aseFile = ReadAseFile(ctx.assetPath); int frameCount = aseFile.Header.Frames; SpriteAtlasBuilder atlasBuilder = new SpriteAtlasBuilder(textureSettings, aseFile.Header.Width, aseFile.Header.Height); Texture2D[] frames = null; if (importType != AseFileImportType.LayerToSprite) { frames = aseFile.GetFrames(); } else { frames = aseFile.GetLayersAsFrames(); } UnityEditor.AssetImporters.SpriteImportData[] spriteImportData = new UnityEditor.AssetImporters.SpriteImportData[0]; //if (textureSettings.transparentMask) //{ // atlas = atlasBuilder.GenerateAtlas(frames, out spriteImportData, textureSettings.transparentColor, false); //} //else //{ // atlas = atlasBuilder.GenerateAtlas(frames, out spriteImportData, false); //} atlas = atlasBuilder.GenerateAtlas(frames, out spriteImportData, textureSettings.transparentMask, false); atlas.filterMode = textureSettings.filterMode; atlas.alphaIsTransparency = false; atlas.wrapMode = TextureWrapMode.Clamp; atlas.name = "Texture"; ctx.AddObjectToAsset("Texture", atlas); ctx.SetMainObject(atlas); switch (importType) { case AseFileImportType.LayerToSprite: case AseFileImportType.Sprite: ImportSprites(ctx, aseFile, spriteImportData); break; case AseFileImportType.Tileset: ImportTileset(ctx, atlas); break; } ctx.SetMainObject(atlas); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var model = File.ReadAllBytes(ctx.assetPath); var asset = ScriptableObject.CreateInstance <NNModel>(); asset.Value = model; ctx.AddObjectToAsset("main obj", asset, LoadIconTexture()); ctx.SetMainObject(asset); }
public void BeginFileVisit(AseFile file) { SpriteAtlasUserAsset.RemoveSpritesFromAtlas(assetPath); m_AseFile = file; m_Pivot = null; // Start off with a an empty 256 palette m_Palette = Enumerable.Repeat(m_TransparentColor, 256).ToList(); // Create the array of clear pixels we'll use to begin each frame m_ClearPixels = Enumerable.Repeat(Color.clear, m_AseFile.Header.Width * m_AseFile.Header.Height).ToArray(); var icon = AssetDatabaseEx.LoadFirstAssetByFilter <Texture2D>("aseprite2unity-icon-0x1badd00d"); m_GameObject = new GameObject(Path.GetFileNameWithoutExtension(assetPath)); m_Context.AddObjectToAsset("_main", m_GameObject, icon); m_Context.SetMainObject(m_GameObject); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { string txt = File.ReadAllText(ctx.assetPath); var cartridge = ScriptableObject.CreateInstance <CartridgeP8>(); cartridge.ReadData(txt); ctx.AddObjectToAsset("cartridge", cartridge); ctx.SetMainObject(cartridge); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext context) { if (_containerType == ContainerType.Mesh) { // Mesh container // Create a prefab with MeshFilter/MeshRenderer. var gameObject = new GameObject(); var mesh = ImportAsMesh(context.assetPath); var meshFilter = gameObject.AddComponent <MeshFilter>(); meshFilter.sharedMesh = mesh; var meshRenderer = gameObject.AddComponent <MeshRenderer>(); meshRenderer.sharedMaterial = GetDefaultMaterial(); context.AddObjectToAsset("prefab", gameObject); if (mesh != null) { context.AddObjectToAsset("mesh", mesh); } context.SetMainObject(gameObject); } else if (_containerType == ContainerType.ComputeBuffer) { // ComputeBuffer container // Create a prefab with PointCloudRenderer. var gameObject = new GameObject(); var data = ImportAsPointCloudData(context.assetPath); var renderer = gameObject.AddComponent <PointCloudRenderer>(); renderer.sourceData = data; context.AddObjectToAsset("prefab", gameObject); if (data != null) { context.AddObjectToAsset("data", data); } context.SetMainObject(gameObject); } else // _containerType == ContainerType.Texture { // Texture container // No prefab is available for this type. var data = ImportAsBakedPointCloud(context.assetPath); if (data != null) { context.AddObjectToAsset("container", data); context.AddObjectToAsset("position", data.positionMap); context.AddObjectToAsset("color", data.colorMap); context.SetMainObject(data); } } }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext context) { var assetName = Path.GetFileNameWithoutExtension(assetPath); MidiFile midiFile; byte[] trackBytes; // Main MIDI file asset using (var stream = new FileStream(context.assetPath, FileMode.Open, FileAccess.Read)) { var deserializer = new MidiDeserializer(stream, _characterCodeName); (midiFile, trackBytes) = deserializer.LoadTrackBytes(); } var fileAsset = MidiFileAsset.Instantiate(midiFile, assetName, trackBytes); fileAsset.name = assetName; context.AddObjectToAsset("MidiFileAsset", fileAsset); context.SetMainObject(fileAsset); var trackCount = midiFile.Tracks.Count; var trackAssets = new MidiTrackAsset[trackCount]; for (var i = 0; i < trackCount; i++) { trackAssets[i] = MidiTrackAsset.Instantiate(fileAsset, i); trackAssets[i].name = $"{i}:{midiFile.Tracks[i].Name}"; } // Contained tracks foreach (var track in trackAssets) { context.AddObjectToAsset(track.name, track); } _midiFileAsset = fileAsset; AssetDatabase.ImportAsset(assetPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { Logger.Info("Importing VPX table at {0}...", ctx.assetPath); // create root object var rootGameObj = new GameObject(); // add lazy importer, will do a normal in memory import once the object ends up in a scene rootGameObj.AddComponent <VpxAssetLazyImporter>(); ctx.AddObjectToAsset("main obj", rootGameObj); ctx.SetMainObject(rootGameObj); }
public static void SaveToAsset(GameObject root, GLTFAnimation.ImportResult[] animations, UnityEditor.AssetImporters.AssetImportContext ctx) { #if UNITY_2018_2_OR_NEWER ctx.AddObjectToAsset("main", root); ctx.SetMainObject(root); #else ctx.SetMainAsset("main obj", root); #endif MeshRenderer[] renderers = root.GetComponentsInChildren <MeshRenderer>(true); SkinnedMeshRenderer[] skinnedRenderers = root.GetComponentsInChildren <SkinnedMeshRenderer>(true); MeshFilter[] filters = root.GetComponentsInChildren <MeshFilter>(true); AddMeshes(filters, skinnedRenderers, ctx); AddMaterials(renderers, skinnedRenderers, ctx); AddAnimations(animations, ctx); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var graphAsset = ScriptableObject.CreateInstance <SubGraphAsset>(); var subGraphPath = ctx.assetPath; var subGraphGuid = AssetDatabase.AssetPathToGUID(subGraphPath); graphAsset.assetGuid = subGraphGuid; var textGraph = File.ReadAllText(subGraphPath, Encoding.UTF8); var graphData = new GraphData { isSubGraph = true, assetGuid = subGraphGuid }; var messageManager = new MessageManager(); graphData.messageManager = messageManager; JsonUtility.FromJsonOverwrite(textGraph, graphData); try { ProcessSubGraph(graphAsset, graphData); } catch (Exception e) { graphAsset.isValid = false; Debug.LogException(e, graphAsset); } finally { if (messageManager.nodeMessagesChanged) { graphAsset.isValid = false; foreach (var pair in messageManager.GetNodeMessages()) { var node = graphData.GetNodeFromTempId(pair.Key); foreach (var message in pair.Value) { MessageManager.Log(node, subGraphPath, message, graphAsset); } } } messageManager.ClearAll(); } Texture2D texture = Resources.Load <Texture2D>("Icons/sg_subgraph_icon@64"); ctx.AddObjectToAsset("MainAsset", graphAsset, texture); ctx.SetMainObject(graphAsset); }
public static bool SetupSpinePrefabMesh(GameObject g, UnityEditor.AssetImporters.AssetImportContext context) { Dictionary <string, int> nameUsageCount = new Dictionary <string, int>(); bool wasModified = false; var skeletonRenderers = g.GetComponentsInChildren <SkeletonRenderer>(true); foreach (SkeletonRenderer renderer in skeletonRenderers) { wasModified = true; var meshFilter = renderer.GetComponent <MeshFilter>(); if (meshFilter == null) { meshFilter = renderer.gameObject.AddComponent <MeshFilter>(); } renderer.EditorUpdateMeshFilterHideFlags(); renderer.Initialize(true, true); renderer.LateUpdateMesh(); var mesh = meshFilter.sharedMesh; if (mesh == null) { continue; } string meshName = string.Format("Skeleton Prefab Mesh \"{0}\"", renderer.name); if (nameUsageCount.ContainsKey(meshName)) { nameUsageCount[meshName]++; meshName = string.Format("Skeleton Prefab Mesh \"{0} ({1})\"", renderer.name, nameUsageCount[meshName]); } else { nameUsageCount.Add(meshName, 0); } mesh.name = meshName; mesh.hideFlags = HideFlags.None; if (context != null) { context.AddObjectToAsset(meshFilter.sharedMesh.name, meshFilter.sharedMesh); } } return(wasModified); }
public override void OnImportAsset(ASSET_IMPORT_CONTEXT c) { var importer = new TemplateXImporter(); var context = new AssetImportContext(c.assetPath); importer.OnImportAsset(context); foreach (var obj in context.Objects) { c.AddObjectToAsset(obj.Identifier, obj.Object, obj.Icon); } c.SetMainObject(context.MainObject); foreach (var path in context.Dependencies) { c.DependsOnSourceAsset(path); } }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var inputType = Path.GetExtension(ctx.assetPath); if (inputType == null) { throw new Exception("Demonstration import error."); } try { // Read first two proto objects containing metadata and brain parameters. Stream reader = File.OpenRead(ctx.assetPath); var metaDataProto = DemonstrationMetaProto.Parser.ParseDelimitedFrom(reader); var metaData = new DemonstrationMetaData(metaDataProto); reader.Seek(DemonstrationStore.MetaDataBytes + 1, 0); var brainParamsProto = BrainParametersProto.Parser.ParseDelimitedFrom(reader); var brainParameters = new BrainParameters(brainParamsProto); reader.Close(); var demonstration = ScriptableObject.CreateInstance <Demonstration>(); demonstration.Initialize(brainParameters, metaData); userData = demonstration.ToString(); var texture = (Texture2D) AssetDatabase.LoadAssetAtPath(k_IconPath, typeof(Texture2D)); #if UNITY_2017_3_OR_NEWER ctx.AddObjectToAsset(ctx.assetPath, demonstration, texture); ctx.SetMainObject(demonstration); #else ctx.SetMainAsset(ctx.assetPath, demonstration); #endif } catch { // ignored } }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var text = File.ReadAllText(ctx.assetPath); var asset = new TextAsset(text); ctx.AddObjectToAsset("main obj", asset); ctx.SetMainObject(asset); if (!Application.isPlaying) { return; } var luaVm = CSharpServiceManager.Get <LuaVM>(CSharpServiceManager.ServiceType.LUA_SERVICE); var get = luaVm.Global.GetInPath <GetLuaService>("_ServiceManager.GetService"); var configService = get(1); var reloadFunc = configService.Get <LuaFunction>("Reload"); reloadFunc.Call(Path.GetFileNameWithoutExtension(ctx.assetPath)); }
private void ImportSprites(UnityEditor.AssetImporters.AssetImportContext ctx, AseFile aseFile, UnityEditor.AssetImporters.SpriteImportData[] spriteImportData) { int spriteCount = spriteImportData.Length; Sprite[] sprites = new Sprite[spriteCount]; for (int i = 0; i < spriteCount; i++) { Sprite sprite = Sprite.Create(atlas, spriteImportData[i].rect, spriteImportData[i].pivot, textureSettings.pixelsPerUnit, textureSettings.extrudeEdges, textureSettings.meshType, spriteImportData[i].border, textureSettings.generatePhysics); sprite.name = string.Format("{0}_{1}", name, spriteImportData[i].name); ctx.AddObjectToAsset(sprite.name, sprite); sprites[i] = sprite; } GenerateAnimations(ctx, aseFile, sprites); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath); if (oldShader != null) { ShaderUtil.ClearShaderMessages(oldShader); } List <PropertyCollector.TextureInfo> configuredTextures; string path = ctx.assetPath; var sourceAssetDependencyPaths = new List <string>(); UnityEngine.Object mainObject; var textGraph = File.ReadAllText(path, Encoding.UTF8); GraphData graph = JsonUtility.FromJson <GraphData>(textGraph); graph.messageManager = new MessageManager(); graph.assetGuid = AssetDatabase.AssetPathToGUID(path); graph.OnEnable(); graph.ValidateGraph(); if (graph.outputNode is VfxMasterNode vfxMasterNode) { var vfxAsset = GenerateVfxShaderGraphAsset(vfxMasterNode); mainObject = vfxAsset; } else { var text = GetShaderText(path, out configuredTextures, sourceAssetDependencyPaths, graph); var shader = ShaderUtil.CreateShaderAsset(text, false); if (graph != null && graph.messageManager.nodeMessagesChanged) { foreach (var pair in graph.messageManager.GetNodeMessages()) { var node = graph.GetNodeFromTempId(pair.Key); MessageManager.Log(node, path, pair.Value.First(), shader); } } EditorMaterialUtility.SetShaderDefaults( shader, configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(), configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray()); EditorMaterialUtility.SetShaderNonModifiableDefaults( shader, configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(), configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray()); mainObject = shader; } Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon@64"); ctx.AddObjectToAsset("MainAsset", mainObject, texture); ctx.SetMainObject(mainObject); var metadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>(); metadata.hideFlags = HideFlags.HideInHierarchy; if (graph != null) { metadata.outputNodeTypeName = graph.outputNode.GetType().FullName; } ctx.AddObjectToAsset("Metadata", metadata); foreach (var sourceAssetDependencyPath in sourceAssetDependencyPaths.Distinct()) { // Ensure that dependency path is relative to project if (!sourceAssetDependencyPath.StartsWith("Packages/") && !sourceAssetDependencyPath.StartsWith("Assets/")) { Debug.LogWarning($"Invalid dependency path: {sourceAssetDependencyPath}", mainObject); continue; } ctx.DependsOnSourceAsset(sourceAssetDependencyPath); } }
public void AddObjectToAsset(string identifier, UnityEngine.Object obj) { m_Context.AddObjectToAsset(identifier, obj); }
private void GenerateAnimations(UnityEditor.AssetImporters.AssetImportContext ctx, AseFile aseFile, Sprite[] sprites) { if (animationSettings == null) { animationSettings = new AseFileAnimationSettings[0]; } var animSettings = new List <AseFileAnimationSettings>(animationSettings); var animations = aseFile.GetAnimations(); if (animations.Length <= 0) { return; } if (animationSettings != null) { RemoveUnusedAnimationSettings(animSettings, animations); } int index = 0; foreach (var animation in animations) { AnimationClip animationClip = new AnimationClip(); animationClip.name = name + "_" + animation.TagName; animationClip.frameRate = 25; AseFileAnimationSettings importSettings = GetAnimationSettingFor(animSettings, animation); importSettings.about = GetAnimationAbout(animation); EditorCurveBinding editorBinding = new EditorCurveBinding(); editorBinding.path = ""; editorBinding.propertyName = "m_Sprite"; switch (bindType) { case AseEditorBindType.SpriteRenderer: editorBinding.type = typeof(SpriteRenderer); break; case AseEditorBindType.UIImage: editorBinding.type = typeof(Image); break; } int length = animation.FrameTo - animation.FrameFrom + 1; ObjectReferenceKeyframe[] spriteKeyFrames = new ObjectReferenceKeyframe[length + 1]; // plus last frame to keep the duration float time = 0; int from = (animation.Animation != LoopAnimation.Reverse) ? animation.FrameFrom : animation.FrameTo; int step = (animation.Animation != LoopAnimation.Reverse) ? 1 : -1; int keyIndex = from; for (int i = 0; i < length; i++) { if (i >= length) { keyIndex = from; } ObjectReferenceKeyframe frame = new ObjectReferenceKeyframe(); frame.time = time; frame.value = sprites[keyIndex]; time += aseFile.Frames[keyIndex].FrameDuration / 1000f; keyIndex += step; spriteKeyFrames[i] = frame; } float frameTime = 1f / animationClip.frameRate; ObjectReferenceKeyframe lastFrame = new ObjectReferenceKeyframe(); lastFrame.time = time - frameTime; lastFrame.value = sprites[keyIndex - step]; spriteKeyFrames[spriteKeyFrames.Length - 1] = lastFrame; AnimationUtility.SetObjectReferenceCurve(animationClip, editorBinding, spriteKeyFrames); AnimationClipSettings settings = AnimationUtility.GetAnimationClipSettings(animationClip); switch (animation.Animation) { case LoopAnimation.Forward: animationClip.wrapMode = WrapMode.Loop; settings.loopTime = true; break; case LoopAnimation.Reverse: animationClip.wrapMode = WrapMode.Loop; settings.loopTime = true; break; case LoopAnimation.PingPong: animationClip.wrapMode = WrapMode.PingPong; settings.loopTime = true; break; } if (!importSettings.loopTime) { animationClip.wrapMode = WrapMode.Once; settings.loopTime = false; } AnimationUtility.SetAnimationClipSettings(animationClip, settings); ctx.AddObjectToAsset(animation.TagName, animationClip); index++; } animationSettings = animSettings.ToArray(); }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { string sceneName = null; GameObject gltfScene = null; UnityEngine.Mesh[] meshes = null; try { sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath); gltfScene = CreateGLTFScene(ctx.assetPath); // Remove empty roots if (_removeEmptyRootObjects) { var t = gltfScene.transform; while ( gltfScene.transform.childCount == 1 && gltfScene.GetComponents <Component>().Length == 1) { var parent = gltfScene; gltfScene = gltfScene.transform.GetChild(0).gameObject; t = gltfScene.transform; t.parent = null; // To keep transform information in the new parent Object.DestroyImmediate(parent); // Get rid of the parent } } // Ensure there are no hide flags present (will cause problems when saving) gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave); foreach (Transform child in gltfScene.transform) { child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave); } // Zero position gltfScene.transform.position = Vector3.zero; // Get meshes var meshNames = new List <string>(); var meshHash = new HashSet <UnityEngine.Mesh>(); var meshFilters = gltfScene.GetComponentsInChildren <MeshFilter>(); var vertexBuffer = new List <Vector3>(); meshes = meshFilters.Select(mf => { var mesh = mf.sharedMesh; vertexBuffer.Clear(); mesh.GetVertices(vertexBuffer); for (var i = 0; i < vertexBuffer.Count; ++i) { vertexBuffer[i] *= _scaleFactor; } mesh.SetVertices(vertexBuffer); if (_swapUvs) { var uv = mesh.uv; var uv2 = mesh.uv2; mesh.uv = uv2; mesh.uv2 = uv2; } if (_importNormals == GLTFImporterNormals.None) { mesh.normals = new Vector3[0]; } if (_importNormals == GLTFImporterNormals.Calculate && mesh.GetTopology(0) == MeshTopology.Triangles) { mesh.RecalculateNormals(); } mesh.UploadMeshData(!_readWriteEnabled); if (_generateColliders) { var collider = mf.gameObject.AddComponent <MeshCollider>(); collider.sharedMesh = mesh; } if (meshHash.Add(mesh)) { var meshName = string.IsNullOrEmpty(mesh.name) ? mf.gameObject.name : mesh.name; mesh.name = ObjectNames.GetUniqueName(meshNames.ToArray(), meshName); meshNames.Add(mesh.name); } return(mesh); }).ToArray(); var renderers = gltfScene.GetComponentsInChildren <Renderer>(); if (_importMaterials) { // Get materials var materialNames = new List <string>(); var materialHash = new HashSet <UnityEngine.Material>(); var materials = renderers.SelectMany(r => { return(r.sharedMaterials.Select(mat => { if (materialHash.Add(mat)) { var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name; if (matName == mat.shader.name) { matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/") + 1, matName.Length - 1)); } // Ensure name is unique matName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(matName)); matName = ObjectNames.GetUniqueName(materialNames.ToArray(), matName); mat.name = matName; materialNames.Add(matName); } return mat; })); }).ToArray(); // Get textures var textureNames = new List <string>(); var textureHash = new HashSet <Texture2D>(); var texMaterialMap = new Dictionary <Texture2D, List <TexMaterialMap> >(); var textures = materials.SelectMany(mat => { var shader = mat.shader; if (!shader) { return(Enumerable.Empty <Texture2D>()); } var matTextures = new List <Texture2D>(); for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i) { if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) { var propertyName = ShaderUtil.GetPropertyName(shader, i); var tex = mat.GetTexture(propertyName) as Texture2D; if (tex) { if (textureHash.Add(tex)) { var texName = tex.name; if (string.IsNullOrEmpty(texName)) { if (propertyName.StartsWith("_")) { texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1)); } } // Ensure name is unique texName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(texName)); texName = ObjectNames.GetUniqueName(textureNames.ToArray(), texName); tex.name = texName; textureNames.Add(texName); matTextures.Add(tex); } List <TexMaterialMap> materialMaps; if (!texMaterialMap.TryGetValue(tex, out materialMaps)) { materialMaps = new List <TexMaterialMap>(); texMaterialMap.Add(tex, materialMaps); } materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap")); } } } return(matTextures); }).ToArray(); var folderName = Path.GetDirectoryName(ctx.assetPath); // Save textures as separate assets and rewrite refs // TODO: Support for other texture types if (textures.Length > 0) { var texturesRoot = string.Concat(folderName, "/", "Textures/"); Directory.CreateDirectory(texturesRoot); foreach (var tex in textures) { var ext = _useJpgTextures ? ".jpg" : ".png"; var texPath = string.Concat(texturesRoot, tex.name, ext); File.WriteAllBytes(texPath, _useJpgTextures ? tex.EncodeToJPG() : tex.EncodeToPNG()); AssetDatabase.ImportAsset(texPath); } } // Save materials as separate assets and rewrite refs if (materials.Length > 0) { var materialRoot = string.Concat(folderName, "/", "Materials/"); Directory.CreateDirectory(materialRoot); foreach (var mat in materials) { var materialPath = string.Concat(materialRoot, mat.name, ".mat"); var newMat = mat; CopyOrNew(mat, materialPath, m => { // Fix references newMat = m; foreach (var r in renderers) { var sharedMaterials = r.sharedMaterials; for (var i = 0; i < sharedMaterials.Length; ++i) { var sharedMaterial = sharedMaterials[i]; if (sharedMaterial.name == mat.name) { sharedMaterials[i] = m; } } sharedMaterials = sharedMaterials.Where(sm => sm).ToArray(); r.sharedMaterials = sharedMaterials; } }); // Fix textures // HACK: This needs to be a delayed call. // Unity needs a frame to kick off the texture import so we can rewrite the ref if (textures.Length > 0) { EditorApplication.delayCall += () => { for (var i = 0; i < textures.Length; ++i) { var tex = textures[i]; var texturesRoot = string.Concat(folderName, "/", "Textures/"); var ext = _useJpgTextures ? ".jpg" : ".png"; var texPath = string.Concat(texturesRoot, tex.name, ext); // Grab new imported texture var materialMaps = texMaterialMap[tex]; var importer = (TextureImporter)TextureImporter.GetAtPath(texPath); var importedTex = AssetDatabase.LoadAssetAtPath <Texture2D>(texPath); if (importer != null) { var isNormalMap = false; foreach (var materialMap in materialMaps) { if (materialMap.Material == mat) { isNormalMap |= materialMap.IsNormalMap; newMat.SetTexture(materialMap.Property, importedTex); } } ; if (isNormalMap) { // Try to auto-detect normal maps importer.textureType = TextureImporterType.NormalMap; } else if (importer.textureType == TextureImporterType.Sprite) { // Force disable sprite mode, even for 2D projects importer.textureType = TextureImporterType.Default; } importer.SaveAndReimport(); } else { Debug.LogWarning("GLTFImporter: Unable to import texture from path reference"); } } }; } } } } else { var temp = GameObject.CreatePrimitive(PrimitiveType.Plane); temp.SetActive(false); var defaultMat = new[] { temp.GetComponent <Renderer>().sharedMaterial }; DestroyImmediate(temp); foreach (var rend in renderers) { rend.sharedMaterials = defaultMat; } } } catch { if (gltfScene) { DestroyImmediate(gltfScene); } throw; } #if UNITY_2017_3_OR_NEWER // Set main asset ctx.AddObjectToAsset("main asset", gltfScene); // Add meshes foreach (var mesh in meshes) { ctx.AddObjectToAsset("mesh " + mesh.name, mesh); } ctx.SetMainObject(gltfScene); #else // Set main asset ctx.SetMainAsset("main asset", gltfScene); // Add meshes foreach (var mesh in meshes) { ctx.AddSubAsset("mesh " + mesh.name, mesh); } #endif }
public override void OnImportAsset(UnityEditor.AssetImporters.AssetImportContext ctx) { ctx.DependsOnCustomDependency("HLODSystemPlatform"); var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(ctx.selectedBuildTarget); try { UpdateProgress(ctx.assetPath, 0, 1); using (Stream stream = new FileStream(ctx.assetPath, FileMode.Open, FileAccess.Read)) { HLODData data = HLODDataSerializer.Read(stream); RootData rootData = RootData.CreateInstance <RootData>(); TextureFormat compressFormat = GetCompressFormat(data, buildTargetGroup); int currentProgress = 0; int maxProgress = 0; if (data.GetMaterials() != null) { maxProgress += data.GetMaterials().Count; } if (data.GetObjects() != null) { maxProgress += data.GetObjects().Count; } if (data.GetColliders() != null) { maxProgress += data.GetColliders().Count; } rootData.name = "Root"; var serializableMaterials = data.GetMaterials(); var loadedMaterials = new Dictionary <string, Material>(); if (serializableMaterials != null) { for (int mi = 0; mi < serializableMaterials.Count; ++mi) { UpdateProgress(ctx.assetPath, currentProgress++, maxProgress); var sm = serializableMaterials[mi]; if (loadedMaterials.ContainsKey(sm.ID)) { continue; } Material mat = sm.To(); loadedMaterials.Add(sm.ID, mat); if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(mat)) == false) { continue; } ctx.AddObjectToAsset(mat.name, mat); for (int ti = 0; ti < sm.GetTextureCount(); ++ti) { HLODData.SerializableTexture st = sm.GetTexture(ti); Texture2D texture = st.To(); EditorUtility.CompressTexture(texture, compressFormat, TextureCompressionQuality.Normal); mat.SetTexture(st.Name, texture); ctx.AddObjectToAsset(texture.name, texture); } mat.EnableKeyword("_NORMALMAP"); } } var serializableObjects = data.GetObjects(); var serializableColliders = data.GetColliders(); Dictionary <string, List <GameObject> > createdGameObjects = new Dictionary <string, List <GameObject> >(); Dictionary <string, GameObject> createdColliders = new Dictionary <string, GameObject>(); if (serializableObjects != null) { for (int oi = 0; oi < serializableObjects.Count; ++oi) { UpdateProgress(ctx.assetPath, currentProgress++, maxProgress); var so = serializableObjects[oi]; GameObject go = new GameObject(); go.name = so.Name; MeshFilter mf = go.AddComponent <MeshFilter>(); MeshRenderer mr = go.AddComponent <MeshRenderer>(); List <string> materialIds = so.GetMaterialIds(); List <Material> materials = new List <Material>(); for (int mi = 0; mi < materialIds.Count; ++mi) { string id = materialIds[mi]; if (loadedMaterials.ContainsKey(id)) { materials.Add(loadedMaterials[id]); } else { string path = AssetDatabase.GUIDToAssetPath(id); if (string.IsNullOrEmpty(path) == false) { materials.Add(AssetDatabase.LoadAssetAtPath <Material>(path)); } else { materials.Add(null); } } } Mesh mesh = so.GetMesh().To(); mf.sharedMesh = mesh; mr.sharedMaterials = materials.ToArray(); mr.lightProbeUsage = so.LightProbeUsage; ctx.AddObjectToAsset(mesh.name, mesh); if (createdGameObjects.ContainsKey(go.name) == false) { createdGameObjects.Add(go.name, new List <GameObject>()); } createdGameObjects[go.name].Add(go); } } if (serializableColliders != null) { for (int ci = 0; ci < serializableColliders.Count; ++ci) { UpdateProgress(ctx.assetPath, currentProgress++, maxProgress); var sc = serializableColliders[ci]; GameObject go; if (createdColliders.ContainsKey(sc.Name) == false) { createdColliders[sc.Name] = new GameObject("Collider"); } go = createdColliders[sc.Name]; var collider = sc.CreateGameObject(); if (collider != null) { collider.name = "Collider" + ci; collider.transform.SetParent(go.transform, true); } } } foreach (var objects in createdGameObjects.Values) { GameObject root; if (objects.Count > 1) { root = new GameObject(); root.name = objects[0].name; for (int i = 0; i < objects.Count; ++i) { objects[i].name = objects[i].name + "_" + i; objects[i].transform.SetParent(root.transform, true); } } else { root = objects[0]; } if (createdColliders.ContainsKey(root.name)) { createdColliders[root.name].transform.SetParent(root.transform, true); } rootData.SetRootObject(root.name, root); ctx.AddObjectToAsset(root.name, root); } ctx.AddObjectToAsset("Root", rootData); ctx.SetMainObject(rootData); } } finally { EditorUtility.ClearProgressBar(); } }