public override void OnImportAsset(AssetImportContext ctx)
        {
            if (ctx == null)
            {
                return;
            }

            var path = ctx.assetPath;

            AlembicStream.DisconnectStreamsWithPath(path);

            var fileName = Path.GetFileNameWithoutExtension(path);
            var go       = new GameObject(fileName);

            var streamDescriptor = ScriptableObject.CreateInstance <AlembicStreamDescriptor>();

            streamDescriptor.name      = go.name + "_ABCDesc";
            streamDescriptor.PathToAbc = path;
            streamDescriptor.Settings  = StreamSettings;

            using (var abcStream = new AlembicStream(go, streamDescriptor))
            {
                abcStream.AbcLoad(true, true);

                abcStream.GetTimeRange(ref abcStartTime, ref abcEndTime);
                if (firstImport)
                {
                    startTime = abcStartTime;
                    endTime   = abcEndTime;
                }
                streamDescriptor.abcStartTime = abcStartTime;
                streamDescriptor.abcEndTime   = abcEndTime;

                var streamPlayer = go.AddComponent <AlembicStreamPlayer>();
                streamPlayer.StreamDescriptor = streamDescriptor;
                streamPlayer.StartTime        = StartTime;
                streamPlayer.EndTime          = EndTime;

                var subassets = new Subassets(ctx);
                subassets.Add(streamDescriptor.name, streamDescriptor);
                GenerateSubAssets(subassets, abcStream.abcTreeRoot, streamDescriptor);

                AlembicStream.ReconnectStreamsWithPath(path);

                if (string.IsNullOrEmpty(rootGameObjectId))
                {
                    rootGameObjectId = fileName;
                    EditorUtility.SetDirty(this);
                }

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(rootGameObjectId, go);
                ctx.SetMainObject(go);
#else
                ctx.SetMainAsset(rootGameObjectId, go);
#endif
            }

            firstImport = false;
        }
        public override void OnImportAsset(AssetImportContext context)
        {
            var song = MidiFileLoader.Load(File.ReadAllBytes(context.assetPath));
            var seq  = new MidiTrackSequencer(song.tracks[0], song.division, _bpm);

            var clip = new MidiClip(_bpm);

            if (_gateEasing)
            {
                clip.EnableEasing(_attackTime, _releaseTime);
            }

            clip.WriteBeat(0);
            clip.WriteEvents(0, seq.Start());

            const float dt = 1.0f / 60;

            for (var t = dt; seq.Playing; t += dt)
            {
                clip.WriteBeat(t);
                clip.WriteEvents(t, seq.Advance(dt));
            }

            context.SetMainAsset("MIDI", clip.ConvertToAnimationClip());
        }
Beispiel #3
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var fileName = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

            var go        = new GameObject(fileName);
            var usdStream = go.AddComponent <UsdStream>();

            usdStream.importSettings = new usdi.ImportSettings()
            {
                interpolation      = m_importSettings.interpolation,
                normalCalculation  = m_importSettings.normalCalculation,
                tangentCalculation = m_importSettings.tangentCalculation,
                maxBoneWeights     = m_importSettings.maxBoneWeights,
                scale           = m_importSettings.scale,
                loadAllPayloads = true,
                triangulate     = true,
                swapHandedness  = m_importSettings.swapHandedness,
                swapFaces       = m_importSettings.swapFaces,
                splitMesh       = true,
                doubleBuffering = true,
            };
            usdStream.directVBUpdate    = m_directVBUpdate;
            usdStream.forceSingleThread = m_forceSingleThread;
            usdStream.timeUnit          = m_timeUnit;
            usdStream.playTime          = m_time;

            usdStream.LoadImmediate(ctx.assetPath);

            var material = new Material(Shader.Find("Standard"))
            {
            };

            material.name = "Material_0";
            ctx.AddSubAsset("Default Material", material);
            _subObjects = new SortedDictionary <int, UnityEngine.Object>();
            CollectSubAssets(go.transform, material);

            int i = 0;

            foreach (var m in _subObjects)
            {
                if (String.IsNullOrEmpty(m.Value.name) || m.Value.name.IndexOf("<dyn>") == 0)
                {
                    m.Value.name = fileName + "_" + m.Value.GetType().Name + "_" + (++i);
                }
                ctx.AddSubAsset(m.Value.name, m.Value);
            }

            if (m_importMode == UsdImportMode.StripUSD)
            {
                usdStream.usdiDetachUsdComponents();
            }

            ctx.SetMainAsset(fileName, go);
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var shortAssetPath = MakeShortAssetPath(ctx.assetPath);

            AlembicStream.DisconnectStreamsWithPath(shortAssetPath);
            var sourcePath    = Application.dataPath + shortAssetPath;
            var destPath      = Application.streamingAssetsPath + shortAssetPath;
            var directoryPath = Path.GetDirectoryName(destPath);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            if (File.Exists(destPath))
            {
                File.SetAttributes(destPath, FileAttributes.Normal);
            }
            File.Copy(sourcePath, destPath, true);

            var fileName = Path.GetFileNameWithoutExtension(destPath);
            var go       = new GameObject(fileName);

            var streamDescriptor = ScriptableObject.CreateInstance <AlembicStreamDescriptor>();

            streamDescriptor.name      = go.name + "_ABCDesc";
            streamDescriptor.pathToAbc = shortAssetPath;
            streamDescriptor.settings  = streamSettings;

            using (var abcStream = new AlembicStream(go, streamDescriptor))
            {
                abcStream.AbcLoad(true);

                abcStream.GetTimeRange(ref startTime, ref endTime);
                streamDescriptor.abcStartTime = abcStartTime = startTime;
                streamDescriptor.abcEndTime   = abcEndTime = endTime;

                var streamPlayer = go.AddComponent <AlembicStreamPlayer>();
                streamPlayer.streamDescriptor = streamDescriptor;
                streamPlayer.startTime        = startTime;
                streamPlayer.endTime          = endTime;

                var subassets = new Subassets(ctx);
                subassets.Add(streamDescriptor.name, streamDescriptor);
                GenerateSubAssets(subassets, abcStream.abcTreeRoot, streamDescriptor);

                AlembicStream.ReconnectStreamsWithPath(shortAssetPath);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(go.name, go);
                ctx.SetMainObject(go);
#else
                ctx.SetMainAsset(go.name, go);
#endif
            }
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            m_ImportSettings.m_pathToAbc = new DataPath(ctx.assetPath);
            var mainObject = AlembicImportTasker.Import(m_importMode, m_ImportSettings, m_diagSettings, (stream, mainGO, streamDescr) =>
            {
                GenerateSubAssets(ctx, mainGO, stream);
                if (streamDescr != null)
                {
                    ctx.AddSubAsset(mainGO.name, streamDescr);
                }
            });

            ctx.SetMainAsset(mainObject.name, mainObject);
        }
        public static void SaveToAsset(GameObject root, AnimationClip[] animations, 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 void SaveToAsset(AssetImportContext ctx, GameObject[] roots)
        {
#if UNITY_2018_2_OR_NEWER
            // Add GameObjects
            if (roots.Length == 1)
            {
                ctx.AddObjectToAsset("main", roots[0]);
                ctx.SetMainObject(roots[0]);
            }
            else
            {
                GameObject root = new GameObject("Main");
                for (int i = 0; i < roots.Length; i++)
                {
                    roots[i].transform.parent = root.transform;
                }
                ctx.AddObjectToAsset("main", root);
                ctx.SetMainObject(root);
            }
#else
            // Add GameObjects
            if (roots.Length == 1)
            {
                ctx.SetMainAsset("main obj", roots[0]);
            }
            else
            {
                GameObject root = new GameObject("Main");
                for (int i = 0; i < roots.Length; i++)
                {
                    roots[i].transform.parent = root.transform;
                }
                ctx.SetMainAsset("main obj", root);
            }
#endif
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var shortAssetPath = MakeShortAssetPath(ctx.assetPath);
            var sourcePath     = SourcePath(shortAssetPath);
            var destPath       = Path.Combine(Application.streamingAssetsPath, shortAssetPath);
            var directoryPath  = Path.GetDirectoryName(destPath);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            if (File.Exists(destPath))
            {
                File.SetAttributes(destPath, FileAttributes.Normal);
            }
            File.Copy(sourcePath, destPath, true);

            var fileName = Path.GetFileNameWithoutExtension(destPath);
            var go       = new GameObject(fileName);

            var streamDescriptor = ScriptableObject.CreateInstance <OpenVDBStreamDescriptor>();

            streamDescriptor.name      = go.name + "_VDBDesc";
            streamDescriptor.pathToVDB = shortAssetPath;
            streamDescriptor.settings  = streamSettings;

            using (var vdbStream = new OpenVDBStream(go, streamDescriptor))
            {
                if (!vdbStream.Load())
                {
                    return;
                }

                var subassets = new Subassets(ctx);
                subassets.Add(streamDescriptor.name, streamDescriptor);
                GenerateSubAssets(subassets, vdbStream, streamDescriptor);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(go.name, go);
                ctx.SetMainObject(go);
#else
                ctx.SetMainAsset(go.name, go);
#endif
            }
        }
Beispiel #9
0
    public override void OnImportAsset(AssetImportContext ctx)
    {
        var text           = File.ReadAllText(ctx.assetPath);
        var luaScriptAsset = LuaScript.CreateFromString(text);

        //script name
        var fileName = Path.GetFileNameWithoutExtension(ctx.assetPath);

        luaScriptAsset.name = fileName;

        //script asset
#if UNITY_2017_3_OR_NEWER
        ctx.AddObjectToAsset("script", luaScriptAsset);
        ctx.SetMainObject(luaScriptAsset);
#else
        ctx.SetMainAsset("script", LuaScriptAsset);
#endif
    }
Beispiel #10
0
        public override void OnImportAsset(AssetImportContext impContext)
        {
            Attributes attributes = JsonUtility.FromJson <Attributes>(File.ReadAllText(impContext.assetPath));

            Texture2D texture = new Texture2D(attributes.width, attributes.height, attributes.tFormat, attributes.mips, true);

            texture.SetPixels(attributes.colors);
            texture.Apply();
            texture.wrapMode   = TextureWrapMode.Clamp;
            texture.filterMode = FilterMode.Point;
#if !UNITY_2017_3_OR_NEWER
            impContext.AddSubAsset("AttributesImage", texture);
            impContext.SetMainAsset("AttributesImage", texture);
#else
            impContext.AddObjectToAsset("AttributesImage", texture);
            impContext.SetMainObject(texture);
#endif
        }
Beispiel #11
0
    public override void OnImportAsset(AssetImportContext ctx)
    {
        var fileName = ctx.assetPath.Substring("Assets/Resources/".Length);

        PKFxAsset fxa   = null;
        Texture2D thumb = null;

        if (Path.GetExtension(ctx.assetPath) == ".pkat")
        {
            fxa   = ScriptableObject.CreateInstance <PKFxAtlasAsset>();
            thumb = Resources.Load("Icons/AT") as Texture2D;
        }
        else if (Path.GetExtension(ctx.assetPath) == ".pkan")
        {
            fxa   = ScriptableObject.CreateInstance <PKFxAnimationAsset>();
            thumb = Resources.Load("Icons/AN") as Texture2D;
        }
        else if (Path.GetExtension(ctx.assetPath) == ".pksc")
        {
            fxa   = ScriptableObject.CreateInstance <PKFxSimCacheAsset>();
            thumb = Resources.Load("Icons/SC") as Texture2D;
        }
        else if (Path.GetExtension(ctx.assetPath) == ".pkfm")
        {
            fxa   = ScriptableObject.CreateInstance <PKFxFontMetricsAsset>();
            thumb = Resources.Load("Icons/FM") as Texture2D;
        }
        else if (Path.GetExtension(ctx.assetPath) == ".pkmm")
        {
            fxa   = ScriptableObject.CreateInstance <PKFxMeshAsset>();
            thumb = Resources.Load("Icons/MM") as Texture2D;
        }

        if (fxa != null)
        {
            fxa.m_Data = File.ReadAllBytes(ctx.assetPath);
            fxa.name   = fxa.m_AssetName = fileName;
#if UNITY_2017_3 || UNITY_2017_4 || UNITY_2018
            ctx.AddObjectToAsset(fileName, fxa, thumb);
#else
            ctx.SetMainAsset(fileName, fxa, thumb);
#endif
        }
    }
        public override void OnImportAsset(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();

                Texture2D texture = (Texture2D)
                                    AssetDatabase.LoadAssetAtPath(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
            {
                return;
            }
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            stage = AnimData.LoadFromFile(ctx.assetPath);
            if (stage == null)
            {
                return;
            }

            MeshUtils.SimplifyStage(stage);

            savedClips    = new Dictionary <AudioDataPool.AudioPoolKey, AudioClip>();
            totalVertices = 0;
            totalLines    = 0;

            PreviewTexture = new Texture2D(1, 1);
            PreviewTexture.LoadImage(stage.previewFrames[0], false);
            PreviewTexture.Apply();

            if (Settings.Shader == null)
            {
                Settings.Shader = "AnimVR/Standard";
            }

            materialToUse = new Material(Shader.Find(Settings.Shader));
            materialToUse.SetFloat("_Unlit", Settings.UnlitByDefault ? 1 : 0);
            materialToUse.name = "BaseMaterial";

            ctx.AddSubAsset("BaseMaterial", materialToUse);

            needsAudioReimport = false;

            var stageObj = GenerateUnityObject(stage, ctx);

            ctx.SetMainAsset(stage.name, stageObj, PreviewTexture);

            InfoString = "FPS: " + stage.fps + ", " + stage.timelineLength + " frames \n"
                         + totalVertices + " verts, " + totalLines + " lines";

            savedClips = null;
            stage      = null;
        }
Beispiel #14
0
    public override void OnImportAsset(AssetImportContext ctx)
    {
        var existedPythonScriptAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(ctx.assetPath) as PythonScript;
        //script text
        var text              = File.ReadAllText(ctx.assetPath);
        int updateCount       = existedPythonScriptAsset == null ? 0 : existedPythonScriptAsset.updateCount;
        var pythonScriptAsset = PythonScript.CreateFromString(text, updateCount);

        //script name
        var fileName = Path.GetFileNameWithoutExtension(ctx.assetPath);

        pythonScriptAsset.name = fileName;

        //script asset
                #if UNITY_2017_3_OR_NEWER
        ctx.AddObjectToAsset("script", pythonScriptAsset);
        ctx.SetMainObject(pythonScriptAsset);
                #else
        ctx.SetMainAsset("script", pythonScriptAsset);
                #endif
    }
Beispiel #15
0
    public override void OnImportAsset(AssetImportContext ctx)
    {
        // set text assert for treat .sketch file as Unity asset.
        var textAsset = new TextAsset();

        ctx.SetMainAsset("MainAsset", textAsset);

        var path     = ctx.assetPath;
        var fileName = Path.GetFileNameWithoutExtension(path);

        /*
         *      create Sketch file named folder for export files.
         */
        var outputFolderPathParts = path.Split('/');

        // set filename as folder name.
        outputFolderPathParts[outputFolderPathParts.Length - 1] = fileName;

        var folderPath = string.Join("/", outputFolderPathParts);

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
            AssetDatabase.Refresh();
        }

        // execute slice export command.
        var proc = new ProcessStartInfo("/usr/local/bin/sketchtool", "export slices " + path + " --output=" + folderPath);

        proc.UseShellExecute = false;

        var p = Process.Start(proc);

        p.WaitForExit();

        // refresh for add exporterd images.
        AssetDatabase.Refresh();
    }
Beispiel #16
0
        public static void SaveToAsset(GameObject root, AnimationClip[] animations, AssetImportContext ctx, ImportSettings settings)
        {
#if UNITY_2018_2_OR_NEWER
            ctx.AddObjectToAsset("main", root);
            ctx.SetMainObject(root);
#else
            ctx.SetMainAsset("main obj", root);
#endif
            UnwrapParam?unwrapParams = new UnwrapParam()
            {
                angleError = settings.angleError,
                areaError  = settings.areaError,
                hardAngle  = settings.hardAngle,
                packMargin = settings.packMargin
            };

            MeshRenderer[]        renderers        = root.GetComponentsInChildren <MeshRenderer>(true);
            SkinnedMeshRenderer[] skinnedRenderers = root.GetComponentsInChildren <SkinnedMeshRenderer>(true);
            MeshFilter[]          filters          = root.GetComponentsInChildren <MeshFilter>(true);
            AddMeshes(filters, skinnedRenderers, ctx, settings.generateLightmapUVs ? unwrapParams : null);
            AddMaterials(renderers, skinnedRenderers, ctx);
            AddAnimations(animations, ctx, settings.animationSettings);
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            {
                var ext = Path.GetExtension(ctx.assetPath).ToLower();
                if (ext == ".vox")
                {
                    fileType = VoxelBase.FileType.vox;
                }
                else if (ext == ".qb")
                {
                    fileType = VoxelBase.FileType.qb;
                }
                else
                {
                    return;
                }
            }

            #region DefaultScale
            if (dataVersion == 0 &&
                importScale == Vector3.one &&
                AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(ctx.assetPath) == null)
            {
                var x = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleX", 1f);
                var y = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleY", 1f);
                var z = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleZ", 1f);
                importScale = new Vector3(x, y, z);
            }
            #endregion

            Action <string> LogImportError = (log) =>
            {
#if UNITY_2018_1_OR_NEWER
                ctx.LogImportError(log);
#else
                Debug.LogError(log);
#endif
            };

            var gameObject  = new GameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
            var voxelObject = gameObject.AddComponent <VoxelObject>();
            {
                voxelObject.legacyVoxImport               = legacyVoxImport;
                voxelObject.importMode                    = importMode;
                voxelObject.importScale                   = importScale;
                voxelObject.importOffset                  = importOffset;
                voxelObject.combineFaces                  = combineFaces;
                voxelObject.ignoreCavity                  = ignoreCavity;
                voxelObject.voxelStructure                = outputStructure ? ScriptableObject.CreateInstance <VoxelStructure>() : null;
                voxelObject.generateLightmapUVs           = generateLightmapUVs;
                voxelObject.generateLightmapUVsAngleError = generateLightmapUVsAngleError;
                voxelObject.generateLightmapUVsAreaError  = generateLightmapUVsAreaError;
                voxelObject.generateLightmapUVsHardAngle  = generateLightmapUVsHardAngle;
                voxelObject.generateLightmapUVsPackMargin = generateLightmapUVsPackMargin;
                voxelObject.generateTangents              = generateTangents;
                voxelObject.meshFaceVertexOffset          = meshFaceVertexOffset;
                voxelObject.loadFromVoxelFile             = loadFromVoxelFile;
                voxelObject.generateMipMaps               = generateMipMaps;
            }
            var objectCore = new VoxelObjectCore(voxelObject);
            try
            {
                if (!objectCore.Create(ctx.assetPath, null))
                {
                    LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                    DestroyImmediate(gameObject);
                    return;
                }
            }
            catch
            {
                LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                DestroyImmediate(gameObject);
                return;
            }

            #region Correspondence in Issue ID 947055 Correction in case before correction is applied
            for (int i = 0; i < voxelObject.materials.Count; i++)
            {
                if (voxelObject.materials[i] != null)
                {
                    voxelObject.materials[i].hideFlags |= HideFlags.NotEditable;
                }
            }
            if (voxelObject.atlasTexture != null)
            {
                voxelObject.atlasTexture.hideFlags |= HideFlags.NotEditable;
            }
            if (voxelObject.mesh != null)
            {
                voxelObject.mesh.hideFlags |= HideFlags.NotEditable;
            }
            #endregion

            #region Material
            {
                materials     = new Material[voxelObject.materialIndexes.Count];
                materialNames = new string[voxelObject.materialIndexes.Count];
                for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                {
                    var index    = voxelObject.materialIndexes[i];
                    var material = voxelObject.materials[index];
                    material.name    = string.Format("mat{0}", index);
                    materials[i]     = material;
                    materialNames[i] = material.name;
                }
                if (remappedMaterials != null)
                {
                    remappedMaterials = remappedMaterials.Where(item => item.material != null).ToArray();
                }
            }
            #endregion

            #region Collider
            switch (colliderType)
            {
            case ColliderType.Box:
                gameObject.AddComponent <BoxCollider>();
                break;

            case ColliderType.Sphere:
                gameObject.AddComponent <SphereCollider>();
                break;

            case ColliderType.Capsule:
                gameObject.AddComponent <CapsuleCollider>();
                break;

            case ColliderType.Mesh:
                gameObject.AddComponent <MeshCollider>();
                break;
            }
            #endregion

#if UNITY_2017_3_OR_NEWER
            ctx.AddObjectToAsset(gameObject.name, gameObject);
            ctx.AddObjectToAsset(voxelObject.mesh.name = "mesh", voxelObject.mesh);
            {
                var materials = new List <Material>();
                for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                {
                    var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                    materials.Add(material);
                    if (remappedMaterials != null)
                    {
                        var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                        if (index >= 0)
                        {
                            materials[i] = remappedMaterials[index].material;
                            continue;
                        }
                    }
                    ctx.AddObjectToAsset(material.name, material);
                }
                gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
            }
            ctx.AddObjectToAsset(voxelObject.atlasTexture.name = "tex", voxelObject.atlasTexture);
            if (voxelObject.voxelStructure != null)
            {
                ctx.AddObjectToAsset(voxelObject.voxelStructure.name = "structure", voxelObject.voxelStructure);
            }

            VoxelObject.DestroyImmediate(voxelObject);

            ctx.SetMainObject(gameObject);
#else
            ctx.SetMainAsset(gameObject.name, gameObject);
            ctx.AddSubAsset(voxelObject.mesh.name = "mesh", voxelObject.mesh);
            for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
            {
                var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                ctx.AddSubAsset(material.name, material);
            }
            ctx.AddSubAsset(voxelObject.atlasTexture.name = "tex", voxelObject.atlasTexture);
            if (voxelObject.voxelStructure != null)
            {
                ctx.AddSubAsset(voxelObject.voxelStructure.name = "structure", voxelObject.voxelStructure);
            }

            VoxelObject.DestroyImmediate(voxelObject);
#endif
            dataVersion = EditorDataVersion;
        }
        public override void OnImportAsset(AssetImportContext ctx)
        {
            {
                var ext = Path.GetExtension(ctx.assetPath).ToLower();
                if (ext == ".vox")
                {
                    fileType = VoxelBase.FileType.vox;
                }
                else if (ext == ".qb")
                {
                    fileType = VoxelBase.FileType.qb;
                }
                else
                {
                    return;
                }
            }

            #region DefaultScale
            if (dataVersion == 0 &&
                importScale == Vector3.one &&
                AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(ctx.assetPath) == null)
            {
                var x = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleX", 1f);
                var y = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleY", 1f);
                var z = EditorPrefs.GetFloat("VoxelImporter_DefaultScaleZ", 1f);
                importScale = new Vector3(x, y, z);
            }
            #endregion

            #region LegacyAssetNaming
            if (dataVersion > 0 && dataVersion < 6)
            {
                legacyAssetNaming = true;
            }
            #endregion

            Action <string> LogImportError = (log) =>
            {
#if UNITY_2018_1_OR_NEWER
                ctx.LogImportError(log);
#else
                Debug.LogError(log);
#endif
            };
            Action <VoxelBase> SetBasicOptions = (voxelObject) =>
            {
                voxelObject.importMode                    = importMode;
                voxelObject.importScale                   = importScale;
                voxelObject.importOffset                  = importOffset;
                voxelObject.combineFaces                  = combineFaces;
                voxelObject.ignoreCavity                  = ignoreCavity;
                voxelObject.shareSameFace                 = shareSameFace;
                voxelObject.removeUnusedPalettes          = removeUnusedPalettes;
                voxelObject.voxelStructure                = outputStructure ? ScriptableObject.CreateInstance <VoxelStructure>() : null;
                voxelObject.generateLightmapUVs           = generateLightmapUVs;
                voxelObject.generateLightmapUVsAngleError = generateLightmapUVsAngleError;
                voxelObject.generateLightmapUVsAreaError  = generateLightmapUVsAreaError;
                voxelObject.generateLightmapUVsHardAngle  = generateLightmapUVsHardAngle;
                voxelObject.generateLightmapUVsPackMargin = generateLightmapUVsPackMargin;
                voxelObject.generateTangents              = generateTangents;
                voxelObject.meshFaceVertexOffset          = meshFaceVertexOffset;
                voxelObject.loadFromVoxelFile             = loadFromVoxelFile;
                voxelObject.generateMipMaps               = generateMipMaps;
                voxelObject.legacyVoxImport               = legacyVoxImport;
                voxelObject.legacyAssetNaming             = legacyAssetNaming;
            };

            Action <VoxelBaseCore> Export = (core) =>
            {
                if (export)
                {
                    var fullPath = Application.dataPath + ctx.assetPath.Remove(0, "Assets".Length);
                    fullPath = fullPath.Remove(fullPath.LastIndexOf('.')) + ".dae";
                    core.ExportDaeFile(fullPath, false);
                }
            };

            var gameObject = new GameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
            if (string.IsNullOrEmpty(gameObjectName))
            {
                gameObjectName = gameObject.name;
            }
            if (meshMode == MeshMode.Combine)
            {
                #region Combine
                var voxelObject = gameObject.AddComponent <VoxelObject>();
                SetBasicOptions(voxelObject);
                var objectCore = new VoxelObjectCore(voxelObject);
                try
                {
                    if (!objectCore.Create(ctx.assetPath, null))
                    {
                        LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                        DestroyImmediate(gameObject);
                        return;
                    }
                }
                catch
                {
                    LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                    DestroyImmediate(gameObject);
                    return;
                }

                #region Correspondence in Issue ID 947055 Correction in case before correction is applied
                foreach (var material in voxelObject.materials)
                {
                    if (material != null)
                    {
                        material.hideFlags |= HideFlags.NotEditable;
                    }
                }
                if (voxelObject.atlasTexture != null)
                {
                    voxelObject.atlasTexture.hideFlags |= HideFlags.NotEditable;
                }
                if (voxelObject.mesh != null)
                {
                    voxelObject.mesh.hideFlags |= HideFlags.NotEditable;
                }
                #endregion

                #region Material
                {
                    materials     = new Material[voxelObject.materialIndexes.Count];
                    materialNames = new string[voxelObject.materialIndexes.Count];
                    for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                    {
                        var index    = voxelObject.materialIndexes[i];
                        var material = voxelObject.materials[index];
                        materials[i]     = material;
                        materialNames[i] = material.name;
                    }
                    if (remappedMaterials != null)
                    {
                        remappedMaterials = remappedMaterials.Where(item => item.material != null && materialNames.Contains(item.name)).ToArray();
                    }
                }
                #endregion

                #region Structure
                if (voxelObject.voxelStructure != null)
                {
                    if (legacyAssetNaming)
                    {
                        voxelObject.voxelStructure.name = "structure";
                    }
                    else
                    {
                        voxelObject.voxelStructure.name = Path.GetFileNameWithoutExtension(ctx.assetPath);
                    }
                }
                #endregion

                #region Collider
                switch (colliderType)
                {
                case ColliderType.Box:
                    gameObject.AddComponent <BoxCollider>();
                    break;

                case ColliderType.Sphere:
                    gameObject.AddComponent <SphereCollider>();
                    break;

                case ColliderType.Capsule:
                    gameObject.AddComponent <CapsuleCollider>();
                    break;

                case ColliderType.Mesh:
                    gameObject.AddComponent <MeshCollider>();
                    break;
                }
                #endregion

                Export(objectCore);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(gameObjectName, gameObject);
                ctx.AddObjectToAsset("mesh", voxelObject.mesh);
                {
                    var list = new List <Material>();
                    for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                    {
                        var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                        list.Add(material);
                        if (remappedMaterials != null)
                        {
                            var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                            if (index >= 0)
                            {
                                list[i] = remappedMaterials[index].material;
                                continue;
                            }
                        }
                        ctx.AddObjectToAsset(string.Format("mat{0}", i), material);
                    }
                    gameObject.GetComponent <MeshRenderer>().sharedMaterials = list.ToArray();
                }
                ctx.AddObjectToAsset("tex", voxelObject.atlasTexture);
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddObjectToAsset("structure", voxelObject.voxelStructure);
                }

                VoxelObject.DestroyImmediate(voxelObject);

                ctx.SetMainObject(gameObject);
#else
                ctx.SetMainAsset(gameObjectName, gameObject);
                ctx.AddSubAsset("mesh", voxelObject.mesh);
                for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                {
                    var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                    ctx.AddSubAsset(string.Format("mat{0}", i), material);
                }
                ctx.AddSubAsset("tex", voxelObject.atlasTexture);
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddSubAsset("structure", voxelObject.voxelStructure);
                }

                VoxelObject.DestroyImmediate(voxelObject);
#endif
                #endregion
            }
            else if (meshMode == MeshMode.Individual)
            {
                #region Individual
                var voxelObject = gameObject.AddComponent <VoxelChunksObject>();
                SetBasicOptions(voxelObject);
                {
                    voxelObject.createContactChunkFaces = createContactChunkFaces;
                    voxelObject.materialMode            = materialMode;
                }
                var objectCore = new VoxelChunksObjectCore(voxelObject);
                try
                {
                    if (!objectCore.Create(ctx.assetPath, null))
                    {
                        LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                        DestroyImmediate(gameObject);
                        return;
                    }
                }
                catch
                {
                    LogImportError(string.Format("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath));
                    DestroyImmediate(gameObject);
                    return;
                }

                #region Correspondence in Issue ID 947055 Correction in case before correction is applied
                if (voxelObject.materials != null)
                {
                    foreach (var material in voxelObject.materials)
                    {
                        if (material != null)
                        {
                            material.hideFlags |= HideFlags.NotEditable;
                        }
                    }
                }
                if (voxelObject.atlasTexture != null)
                {
                    voxelObject.atlasTexture.hideFlags |= HideFlags.NotEditable;
                }
                foreach (var chunk in voxelObject.chunks)
                {
                    if (chunk.materials != null)
                    {
                        foreach (var material in chunk.materials)
                        {
                            if (material != null)
                            {
                                material.hideFlags |= HideFlags.NotEditable;
                            }
                        }
                    }
                    if (chunk.atlasTexture != null)
                    {
                        chunk.atlasTexture.hideFlags |= HideFlags.NotEditable;
                    }
                    if (chunk.mesh != null)
                    {
                        chunk.mesh.hideFlags |= HideFlags.NotEditable;
                    }
                }
                #endregion

                #region Legacy
                if (legacyAssetNaming)
                {
                    foreach (var chunk in voxelObject.chunks)
                    {
                        var oldName = chunk.chunkName;
                        chunk.chunkName       = chunk.chunkName.Replace("Chunk(", "");
                        chunk.chunkName       = chunk.chunkName.Remove(chunk.chunkName.Length - 1, 1);
                        chunk.gameObject.name = chunk.chunkName;
                        chunk.mesh.name       = chunk.mesh.name.Replace(oldName, chunk.chunkName);
                        if (chunk.materials != null)
                        {
                            foreach (var mat in chunk.materials)
                            {
                                if (mat == null)
                                {
                                    continue;
                                }
                                mat.name = mat.name.Replace(oldName, chunk.chunkName);
                            }
                        }
                        if (chunk.atlasTexture != null)
                        {
                            chunk.atlasTexture.name = chunk.atlasTexture.name.Replace(oldName, chunk.chunkName);
                        }
                    }
                }
                #endregion

                #region Material
                {
                    if (materialMode == VoxelChunksObject.MaterialMode.Combine)
                    {
                        materials     = new Material[voxelObject.materialIndexes.Count];
                        materialNames = new string[voxelObject.materialIndexes.Count];
                        for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                        {
                            var index    = voxelObject.materialIndexes[i];
                            var material = voxelObject.materials[index];
                            materials[i]     = material;
                            materialNames[i] = material.name;
                        }
                    }
                    else if (materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        List <Material> list = new List <Material>();
                        foreach (var chunk in voxelObject.chunks)
                        {
                            for (int i = 0; i < chunk.materialIndexes.Count; i++)
                            {
                                var index    = chunk.materialIndexes[i];
                                var material = chunk.materials[index];
                                if (!list.Contains(material))
                                {
                                    list.Add(material);
                                }
                            }
                        }
                        materials     = list.ToArray();
                        materialNames = new string[list.Count];
                        for (int i = 0; i < list.Count; i++)
                        {
                            materialNames[i] = list[i].name;
                        }
                    }
                    if (remappedMaterials != null)
                    {
                        remappedMaterials = remappedMaterials.Where(item => item.material != null && materialNames.Contains(item.name)).ToArray();
                    }
                }
                #endregion

                #region Structure
                if (voxelObject.voxelStructure != null)
                {
                    if (legacyAssetNaming)
                    {
                        voxelObject.voxelStructure.name = "structure";
                    }
                    else
                    {
                        voxelObject.voxelStructure.name = Path.GetFileNameWithoutExtension(ctx.assetPath);
                    }
                }
                #endregion

                #region Collider
                foreach (var chunk in voxelObject.chunks)
                {
                    switch (colliderType)
                    {
                    case ColliderType.Box:
                        chunk.gameObject.AddComponent <BoxCollider>();
                        break;

                    case ColliderType.Sphere:
                        chunk.gameObject.AddComponent <SphereCollider>();
                        break;

                    case ColliderType.Capsule:
                        chunk.gameObject.AddComponent <CapsuleCollider>();
                        break;

                    case ColliderType.Mesh:
                        chunk.gameObject.AddComponent <MeshCollider>();
                        break;
                    }
                }
                #endregion

                Export(objectCore);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(gameObjectName, gameObject);
                foreach (var chunk in voxelObject.chunks)
                {
                    ctx.AddObjectToAsset(chunk.chunkName + "_mesh", chunk.mesh);
                }
                {
                    if (materialMode == VoxelChunksObject.MaterialMode.Combine)
                    {
                        var materials = new List <Material>();
                        for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                        {
                            var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                            materials.Add(material);
                            if (remappedMaterials != null)
                            {
                                var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                if (index >= 0)
                                {
                                    materials[i] = remappedMaterials[index].material;
                                    continue;
                                }
                            }
                            ctx.AddObjectToAsset(string.Format("mat{0}", i), material);
                        }
                        foreach (var chunk in voxelObject.chunks)
                        {
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                        }
                        ctx.AddObjectToAsset("tex", voxelObject.atlasTexture);
                    }
                    else if (materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        foreach (var chunk in voxelObject.chunks)
                        {
                            var materials = new List <Material>();
                            for (int i = 0; i < chunk.materialIndexes.Count; i++)
                            {
                                var material = chunk.materials[chunk.materialIndexes[i]];
                                materials.Add(material);
                                if (remappedMaterials != null)
                                {
                                    var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                    if (index >= 0)
                                    {
                                        materials[i] = remappedMaterials[index].material;
                                        continue;
                                    }
                                }
                                ctx.AddObjectToAsset(chunk.gameObject.name + string.Format("_mat{0}", i), material);
                            }
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                            ctx.AddObjectToAsset(chunk.gameObject.name + "_tex", chunk.atlasTexture);
                        }
                    }
                }
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddObjectToAsset("structure", voxelObject.voxelStructure);
                }

                foreach (var chunk in voxelObject.chunks)
                {
                    VoxelChunksObjectChunk.DestroyImmediate(chunk.GetComponent <VoxelChunksObjectChunk>());
                }
                VoxelObject.DestroyImmediate(voxelObject);

                ctx.SetMainObject(gameObject);
#else
                ctx.SetMainAsset(gameObjectName, gameObject);
                foreach (var chunk in voxelObject.chunks)
                {
                    ctx.AddSubAsset(chunk.gameObject.name + "_mesh", chunk.mesh);
                }
                {
                    if (materialMode == VoxelChunksObject.MaterialMode.Combine)
                    {
                        var materials = new List <Material>();
                        for (int i = 0; i < voxelObject.materialIndexes.Count; i++)
                        {
                            var material = voxelObject.materials[voxelObject.materialIndexes[i]];
                            materials.Add(material);
                            if (remappedMaterials != null)
                            {
                                var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                if (index >= 0)
                                {
                                    materials[i] = remappedMaterials[index].material;
                                    continue;
                                }
                            }
                            ctx.AddSubAsset(string.Format("mat{0}", i), material, material);
                        }
                        foreach (var chunk in voxelObject.chunks)
                        {
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                        }
                        ctx.AddSubAsset("tex", voxelObject.atlasTexture);
                    }
                    else if (materialMode == VoxelChunksObject.MaterialMode.Individual)
                    {
                        foreach (var chunk in voxelObject.chunks)
                        {
                            var materials = new List <Material>();
                            for (int i = 0; i < chunk.materialIndexes.Count; i++)
                            {
                                var material = chunk.materials[chunk.materialIndexes[i]];
                                materials.Add(material);
                                if (remappedMaterials != null)
                                {
                                    var index = ArrayUtility.FindIndex(remappedMaterials, (t) => { return(t.name == material.name); });
                                    if (index >= 0)
                                    {
                                        materials[i] = remappedMaterials[index].material;
                                        continue;
                                    }
                                }
                                ctx.AddSubAsset(chunk.gameObject.name + string.Format("_mat{0}", i), material);
                            }
                            chunk.gameObject.GetComponent <MeshRenderer>().sharedMaterials = materials.ToArray();
                            ctx.AddSubAsset(chunk.gameObject.name + "_tex", chunk.atlasTexture);
                        }
                    }
                }
                if (voxelObject.voxelStructure != null)
                {
                    ctx.AddSubAsset("structure", voxelObject.voxelStructure);
                }

                foreach (var chunk in voxelObject.chunks)
                {
                    VoxelChunksObjectChunk.DestroyImmediate(chunk.GetComponent <VoxelChunksObjectChunk>());
                }
                VoxelObject.DestroyImmediate(voxelObject);
#endif
                #endregion
            }

            dataVersion = EditorDataVersion;
        }
Beispiel #19
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var shortAssetPath = ctx.assetPath.Replace("Assets", "");

            AlembicStream.DisconnectStreamsWithPath(shortAssetPath);
            var sourcePath    = Application.dataPath + shortAssetPath;
            var destPath      = Application.streamingAssetsPath + shortAssetPath;
            var directoryPath = Path.GetDirectoryName(destPath);

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            if (File.Exists(destPath))
            {
                File.SetAttributes(destPath, FileAttributes.Normal);
            }
            File.Copy(sourcePath, destPath, true);

            var fileName = Path.GetFileNameWithoutExtension(destPath);
            var go       = new GameObject(fileName);

            go.transform.localScale *= scaleFactor;

            AlembicStreamDescriptor streamDescriptor = ScriptableObject.CreateInstance <AlembicStreamDescriptor>();

            streamDescriptor.name      = go.name + "_ABCDesc";
            streamDescriptor.pathToAbc = shortAssetPath;
            streamDescriptor.settings  = streamSettings;

            using (var abcStream = new AlembicStream(go, streamDescriptor))
            {
                abcStream.AbcLoad();
                AbcStartTime  = abcStream.AbcStartTime;
                AbcEndTime    = abcStream.AbcEndTime;
                AbcFrameCount = abcStream.AbcFrameCount;

                startFrame = startFrame < 0 ? 0 : startFrame;
                endFrame   = endFrame > AbcFrameCount - 1 ? AbcFrameCount - 1 : endFrame;

                streamDescriptor.minFrame      = startFrame;
                streamDescriptor.maxFrame      = endFrame;
                streamDescriptor.abcFrameCount = AbcFrameCount;
                streamDescriptor.abcDuration   = AbcEndTime - AbcStartTime;
                streamDescriptor.abcStartTime  = AbcStartTime;

                var streamPlayer = go.AddComponent <AlembicStreamPlayer>();
                streamPlayer.streamDescriptor = streamDescriptor;
                streamPlayer.startFrame       = startFrame;
                streamPlayer.endFrame         = endFrame;

                AddObjectToAsset(ctx, streamDescriptor.name, streamDescriptor);
                GenerateSubAssets(ctx, abcStream.alembicTreeRoot, streamDescriptor);

                AlembicStream.ReconnectStreamsWithPath(shortAssetPath);

#if UNITY_2017_3_OR_NEWER
                ctx.AddObjectToAsset(go.name, go);
                ctx.SetMainObject(go);
#else
                ctx.SetMainAsset(go.name, go);
#endif
            }
        }
Beispiel #20
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            {
                var ext = Path.GetExtension(ctx.assetPath).ToLower();
                if (ext == ".vox")
                {
                    fileType = VoxelBase.FileType.vox;
                }
                else if (ext == ".qb")
                {
                    fileType = VoxelBase.FileType.qb;
                }
                else
                {
                    return;
                }
            }
            var gameObject  = new GameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
            var voxelObject = gameObject.AddComponent <VoxelObject>();
            {
                voxelObject.legacyVoxImport      = legacyVoxImport;
                voxelObject.importMode           = importMode;
                voxelObject.importScale          = importScale;
                voxelObject.importOffset         = importOffset;
                voxelObject.combineFaces         = combineFaces;
                voxelObject.ignoreCavity         = ignoreCavity;
                voxelObject.voxelStructure       = outputStructure ? ScriptableObject.CreateInstance <VoxelStructure>() : null;
                voxelObject.generateLightmapUVs  = generateLightmapUVs;
                voxelObject.meshFaceVertexOffset = meshFaceVertexOffset;
                voxelObject.loadFromVoxelFile    = loadFromVoxelFile;
                voxelObject.generateMipMaps      = generateMipMaps;
            }
            var objectCore = new VoxelObjectCore(voxelObject);

            try
            {
                if (!objectCore.Create(ctx.assetPath, null))
                {
                    Debug.LogErrorFormat("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath);
                    DestroyImmediate(gameObject);
                    return;
                }
            }
            catch
            {
                Debug.LogErrorFormat("<color=green>[Voxel Importer]</color> ScriptedImporter error. file:{0}", ctx.assetPath);
                DestroyImmediate(gameObject);
                return;
            }

            #region Material
            if (retainExisting)
            {
                bool changed = false;
                var  assets  = AssetDatabase.LoadAllAssetsAtPath(ctx.assetPath);
                for (int i = 0; i < voxelObject.materials.Count; i++)
                {
                    var material = assets.FirstOrDefault(c => c.name == string.Format("mat{0}", i)) as Material;
                    if (material != null)
                    {
                        material.mainTexture     = voxelObject.atlasTexture;
                        voxelObject.materials[i] = material;
                        changed = true;
                    }
                }
                if (changed)
                {
                    var renderer = gameObject.GetComponent <MeshRenderer>();
                    renderer.sharedMaterials = voxelObject.materials.ToArray();
                }
            }
            #endregion

            #region Collider
            switch (colliderType)
            {
            case ColliderType.Box:
                gameObject.AddComponent <BoxCollider>();
                break;

            case ColliderType.Sphere:
                gameObject.AddComponent <SphereCollider>();
                break;

            case ColliderType.Capsule:
                gameObject.AddComponent <CapsuleCollider>();
                break;

            case ColliderType.Mesh:
                gameObject.AddComponent <MeshCollider>();
                break;
            }
            #endregion

#if UNITY_2017_3_OR_NEWER
            ctx.AddObjectToAsset(gameObject.name, gameObject);
            ctx.AddObjectToAsset(voxelObject.mesh.name = "mesh", voxelObject.mesh);
            for (int i = 0; i < voxelObject.materials.Count; i++)
            {
                ctx.AddObjectToAsset(voxelObject.materials[i].name = string.Format("mat{0}", i), voxelObject.materials[i]);
            }
            ctx.AddObjectToAsset(voxelObject.atlasTexture.name = "tex", voxelObject.atlasTexture);
            if (voxelObject.voxelStructure != null)
            {
                ctx.AddObjectToAsset(voxelObject.voxelStructure.name = "structure", voxelObject.voxelStructure);
            }

            VoxelObject.DestroyImmediate(voxelObject);

            ctx.SetMainObject(gameObject);
#else
            ctx.SetMainAsset(gameObject.name, gameObject);
            ctx.AddSubAsset(voxelObject.mesh.name = "mesh", voxelObject.mesh);
            for (int i = 0; i < voxelObject.materials.Count; i++)
            {
                ctx.AddSubAsset(voxelObject.materials[i].name = string.Format("mat{0}", i), voxelObject.materials[i]);
            }
            ctx.AddSubAsset(voxelObject.atlasTexture.name = "tex", voxelObject.atlasTexture);
            if (voxelObject.voxelStructure != null)
            {
                ctx.AddSubAsset(voxelObject.voxelStructure.name = "structure", voxelObject.voxelStructure);
            }

            VoxelObject.DestroyImmediate(voxelObject);
#endif
        }
Beispiel #21
0
 public static void SetMainObject(this AssetImportContext ctx, string key, Object o)
 {
     ctx.SetMainAsset(key, o);
 }
        public override void OnImportAsset(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.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
        }
Beispiel #23
0
#pragma warning restore 0649

        public override void OnImportAsset(AssetImportContext ctx)
        {
            byte[]    bytes = File.ReadAllBytes(ctx.assetPath);
            Texture2D tex   = new Texture2D(2, 2, TextureFormat.RGBA32, false);

            tex.LoadImage(bytes);

            originalSize = new Vector2Int(tex.width, tex.height);

            if (scaledSize.x < 0 || scaledSize.y < 0)
            {
                LogImportError(ctx, "Scaled Size can't be smaller than 0!");
                scaledSize = new Vector2Int(0, 0);
            }

            if (scaledSize.x == 0)
            {
                scaledSize.x = originalSize.x;
            }
            if (scaledSize.y == 0)
            {
                scaledSize.y = originalSize.y;
            }

            if (padding.x < 0 || padding.y < 0)
            {
                LogImportError(ctx, "Padding can't be smaller than 0!");
                padding = new Vector2Int(0, 0);
            }
            else if (padding.x >= scaledSize.x || padding.y >= scaledSize.y)
            {
                LogImportError(ctx, "Padding can't be greater than or equal to Scaled Size!");
                padding = new Vector2Int(0, 0);
            }

            if (scaledSize != originalSize || padding.x != 0 || padding.y != 0)
            {
                if (!preserveAspectRatio)
                {
                    ResizeTexture(ref tex, scaledSize, padding, paddingColor);
                }
                else
                {
                    float aspectRatio = (float)originalSize.x / originalSize.y;

                    Vector2Int imageContentsSize = scaledSize - padding;
                    int        targetWidth       = Mathf.RoundToInt(imageContentsSize.y * aspectRatio);
                    int        targetHeight      = Mathf.RoundToInt(imageContentsSize.x / aspectRatio);

                    if (targetWidth <= imageContentsSize.x)
                    {
                        imageContentsSize.x = targetWidth;
                    }
                    else if (targetHeight <= imageContentsSize.y)
                    {
                        imageContentsSize.y = targetHeight;
                    }
                    else
                    {
                        if ((float)targetWidth / imageContentsSize.x < (float)targetHeight / imageContentsSize.y)
                        {
                            imageContentsSize.x = targetWidth;
                        }
                        else
                        {
                            imageContentsSize.y = targetHeight;
                        }
                    }

                    ResizeTexture(ref tex, scaledSize, scaledSize - imageContentsSize, paddingColor);
                }

                bytes = saveAsPNG ? tex.EncodeToPNG() : tex.EncodeToJPG(Mathf.Clamp(jpegQuality, 1, 100));
            }
            else
            {
                // Check if encoding the image as JPEG or PNG will produce a smaller image file
                byte[] bytes2 = saveAsPNG ? tex.EncodeToPNG() : tex.EncodeToJPG(Mathf.Clamp(jpegQuality, 1, 100));
                if (bytes2.Length < bytes.Length)
                {
                    bytes = bytes2;
                }
            }

            // Generate icon
            ResizeTexture(ref tex, new Vector2Int(ICON_SIZE, ICON_SIZE), new Vector2Int(0, 0), new Color(0, 0, 0, 0));

            RuntimeTexture runtimeTexture = ScriptableObject.CreateInstance <RuntimeTexture>();

            ((RuntimeTexture.IEditorInterface)runtimeTexture).Initialize(bytes, scaledSize, generateMipMaps, readWriteEnabled);

#if UNITY_2017_3_OR_NEWER
            ctx.AddObjectToAsset("main obj", runtimeTexture, tex);
            ctx.SetMainObject(runtimeTexture);
#else
            ctx.SetMainAsset("main obj", runtimeTexture, tex);
#endif
        }