private static void ImportAddon(string GUID, bool interactive = true)
 {
     AssetDatabase.ImportPackage(AssetDatabase.GUIDToAssetPath(GUID), interactive);
 }
示例#2
0
        static void OnCompilationFinished(object context)
        {
            var polyApiPath = AssetDatabase.GUIDToAssetPath(k_PolyApiGuid);

            // Load the asset in case it was recently deleted, and its guid is still loaded in the database
            if (string.IsNullOrEmpty(polyApiPath) || AssetDatabase.LoadAssetAtPath <MonoScript>(polyApiPath) == null)
            {
                Cleanup();
                return;
            }

            var runtimeFolder = Directory.GetParent(polyApiPath).Parent;

            if (runtimeFolder == null)
            {
                Cleanup();
                return;
            }

            var ptUtilsPath = AssetDatabase.GUIDToAssetPath(k_PtUtilsGuid);

            if (string.IsNullOrEmpty(ptUtilsPath))
            {
                Cleanup();
                return;
            }

            var editorFolder = Directory.GetParent(ptUtilsPath);

            if (editorFolder == null)
            {
                Cleanup();
                return;
            }

            var runtimeAssemblyDefinitionPath = Path.Combine(runtimeFolder.ToString(), k_RuntimeAssemblyDefinitionFileName);

            if (!File.Exists(runtimeAssemblyDefinitionPath))
            {
                var runtimeAssemblyDefinition = new AssemblyDefinition
                {
                    Name            = k_RuntimeAssemblyDefinitionName,
                    AllowUnsafeCode = true
                };

                File.WriteAllText(runtimeAssemblyDefinitionPath, JsonUtility.ToJson(runtimeAssemblyDefinition));
            }

            var editorAssemblyDefinitionPath = Path.Combine(editorFolder.ToString(), k_EditorAssemblyDefinitionFileName);

            if (!File.Exists(editorAssemblyDefinitionPath))
            {
                var editorAssemblyDefinition = new AssemblyDefinition
                {
                    Name             = k_EditorAssemblyDefinitionName,
                    References       = new[] { k_RuntimeAssemblyDefinitionName },
                    IncludePlatforms = k_IncludePlatformsEditorOnly
                };

                File.WriteAllText(editorAssemblyDefinitionPath, JsonUtility.ToJson(editorAssemblyDefinition));
            }

            BuildTargetGroup currentGroup;
            var defineString = GetDefineString(out currentGroup);

            if (string.IsNullOrEmpty(defineString) || defineString.Contains(k_IncludePolyToolkitDefine))
            {
                return;
            }

            var defines = defineString.Split(';').ToList();

            defines.Add(k_IncludePolyToolkitDefine);
            defineString = string.Join(";", defines);

            PlayerSettings.SetScriptingDefineSymbolsForGroup(currentGroup, defineString);
        }
示例#3
0
    private void OnGUI()
    {
        armatureObj = EditorGUILayout.ObjectField(new GUIContent("Animator Object", "Your Model's Animator object"),
                                                  armatureObj, typeof(Animator), true);
        if (armatureObj != null)
        {
            ani = (Animator)armatureObj;
        }
        else
        {
            startingBone = null;
            smr          = null;
        }

        if (armatureObj && !ani.isHuman)
        {
            if (startingBone == null)
            {
                if (ani.transform.childCount > 0)
                {
                    startingBone = ani.transform.GetChild(0);
                    for (var i = 0; i < ani.transform.childCount; i++)
                    {
                        if (ani.transform.GetChild(i).childCount > 0)
                        {
                            startingBone = ani.transform.GetChild(i).GetChild(0);
                            break;
                        }
                    }
                }
            }

            startingBone = EditorGUILayout.ObjectField(new GUIContent("Starting Bone", "Where the bones start from"),
                                                       startingBone, typeof(Transform), true);
        }
        else
        {
            startingBone = null;
        }

        bone = EditorGUILayout.ObjectField(new GUIContent("Bone Model", "The Model to use as the bone"), bone,
                                           typeof(Object), true);
        if (armatureObj != null && smr == null)
        {
            foreach (var skinedmeshr in ani.GetComponentsInChildren <SkinnedMeshRenderer>())
            {
                if (skinedmeshr.transform.parent == ani.transform)
                {
                    smr = skinedmeshr;
                    break;
                }
            }
        }

        smr = EditorGUILayout.ObjectField(new GUIContent("Skinned Mesh Renderer", "The main skinned mesh renderer"),
                                          smr, typeof(SkinnedMeshRenderer), true);
        boneMaterial = (Material)EditorGUILayout.ObjectField(
            new GUIContent("Bone Material", "The Material you want for your bones"), boneMaterial, typeof(Material),
            true);

        if (armatureObj && ani.isHuman)
        {
            if (haveIKLines)
            {
                ikMaterial = (Material)EditorGUILayout.ObjectField(
                    new GUIContent("IK Material", "The Material you want for your IK Lines"), ikMaterial,
                    typeof(Material), true);
            }
            haveIKLines = EditorGUILayout.Toggle("Have IK Lines", haveIKLines);
        }
        else
        {
            haveIKLines = false;
        }

        //Toggle for Spook Mode
        spookMode = EditorGUILayout.Toggle("Spook Mode (Optional)", spookMode);

        var error = false;

        if (armatureObj == null)
        {
            EditorGUILayout.HelpBox("No Animator found", MessageType.Error);
            error = true;
        }

        if (bone == null)
        {
            EditorGUILayout.HelpBox("No Bone Object found", MessageType.Error);
            error = true;
        }

        if (smr == null)
        {
            EditorGUILayout.HelpBox("No Skinned Mesh Renderer found", MessageType.Error);
            error = true;
        }

        if (boneMaterial == null)
        {
            EditorGUILayout.HelpBox("No Bone Material found", MessageType.Error);
            error = true;
        }

        if (ikMaterial == null && haveIKLines)
        {
            EditorGUILayout.HelpBox("No IK Material found", MessageType.Error);
            error = true;
        }

        if (error)
        {
            return;
        }

        EditorGUILayout.Separator();

        if (GUILayout.Button("Generate"))
        {
            var guids1          = AssetDatabase.FindAssets("XSBonerGenerator", null);
            var untouchedString = AssetDatabase.GUIDToAssetPath(guids1[0]);
            var splitString     = untouchedString.Split('/');

            ArrayUtility.RemoveAt(ref splitString, splitString.Length - 1);
            ArrayUtility.RemoveAt(ref splitString, splitString.Length - 1);

            var finalFilePath   = string.Join("/", splitString);
            var pathToGenerated = finalFilePath + "/Generated";
            var editorPath      = string.Join("/", splitString) + "/Editor";

            if (!Directory.Exists(pathToGenerated))
            {
                Directory.CreateDirectory(pathToGenerated);
            }

            bone         = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(bone), typeof(Object));
            boneMaterial =
                (Material)AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(boneMaterial), typeof(Material));
            ikMaterial =
                (Material)AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(ikMaterial), typeof(Material));

            var name     = Regex.Replace(ani.name, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
            var bonename = Regex.Replace(bone.name, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);

            bones            = new List <Transform>();
            bonesByHash      = new Hashtable();
            boneWeights      = new List <BoneWeight>();
            combineInstances = new List <CombineInstance>();
            coloUrs          = new List <Color>();

            var boneIndex = 0;
            foreach (var _bone in ((SkinnedMeshRenderer)smr).bones)
            {
                if (_bone != null)
                {
                    bones.Add(_bone);
                    bonesByHash.Add(_bone.name, boneIndex);
                    boneIndex++;
                }
            }

            recursiveShit(startingBone != null ? (Transform)startingBone : ani.GetBoneTransform(HumanBodyBones.Hips),
                          collectDynamicBones(ani.transform));

            //keep bindposes
            var bindposes = new List <Matrix4x4>();

            for (var b = 0; b < bones.Count; b++)
            {
                bindposes.Add(bones[b].worldToLocalMatrix * ani.transform.worldToLocalMatrix);
            }


            var yourBones = new GameObject(name + "_" + bonename + "_YourBones");
            yourBones.transform.parent = ani.transform;

            var yourSkinnedMeshRenderer = yourBones.AddComponent <SkinnedMeshRenderer>();
            yourSkinnedMeshRenderer.sharedMesh = new Mesh
            {
                name = name + "_" + bonename + "_YourBones"
            };


            //Adding Audio Source for Super Spooky Mode.
            if (spookMode)
            {
                yourBones.AddComponent <AudioSource>();
                var doot = yourBones.GetComponent <AudioSource>();
                doot.clip         = (AudioClip)AssetDatabase.LoadAssetAtPath(editorPath + "/Doot.mp3", typeof(AudioClip));
                doot.spatialBlend = 1;
                doot.dopplerLevel = 0;
                doot.minDistance  = 2;
                doot.maxDistance  = 10;
            }

            //----
            yourSkinnedMeshRenderer.sharedMesh.CombineMeshes(combineInstances.ToArray());

            var scale = ani.transform.localScale;

            var boneVertices = new List <Vector3>();
            for (var i = 0; i < yourSkinnedMeshRenderer.sharedMesh.vertexCount; i++)
            {
                var vertex = yourSkinnedMeshRenderer.sharedMesh.vertices[i];
                vertex.x *= scale.x;
                vertex.y *= scale.y;
                vertex.z *= scale.z;
                vertex   += ani.transform.position;
                boneVertices.Add(vertex);
            }

            if (haveIKLines)
            {
                IKLines(boneVertices, HumanBodyBones.RightUpperArm, HumanBodyBones.RightHand,
                        HumanBodyBones.RightLowerArm);
                IKLines(boneVertices, HumanBodyBones.LeftUpperArm, HumanBodyBones.LeftHand,
                        HumanBodyBones.LeftLowerArm);
                IKLines(boneVertices, HumanBodyBones.RightUpperLeg, HumanBodyBones.RightFoot,
                        HumanBodyBones.RightLowerLeg);
                IKLines(boneVertices, HumanBodyBones.LeftUpperLeg, HumanBodyBones.LeftFoot,
                        HumanBodyBones.LeftLowerLeg);
            }

            yourSkinnedMeshRenderer.sharedMesh.vertices = boneVertices.ToArray();

            if (haveIKLines)
            {
                yourSkinnedMeshRenderer.sharedMesh.subMeshCount = 2;
                var values = Enumerable.Range(yourSkinnedMeshRenderer.sharedMesh.vertexCount - 12, 12).ToArray();
                yourSkinnedMeshRenderer.sharedMesh.SetTriangles(values, 1);
            }

            yourSkinnedMeshRenderer.bones    = bones.ToArray();
            yourSkinnedMeshRenderer.rootBone = bones[0];
            yourSkinnedMeshRenderer.sharedMesh.boneWeights = boneWeights.ToArray();
            yourSkinnedMeshRenderer.sharedMesh.bindposes   = bindposes.ToArray();
            yourSkinnedMeshRenderer.sharedMesh.colors      = coloUrs.ToArray();
            yourSkinnedMeshRenderer.sharedMaterials        =
                haveIKLines ? new[] { boneMaterial, ikMaterial } : new[] { boneMaterial };

            yourSkinnedMeshRenderer.sharedMesh.RecalculateBounds();

            AssetDatabase.CreateAsset(yourSkinnedMeshRenderer.sharedMesh,
                                      pathToGenerated + "/" + name + "_" + bonename + "_YourBones.asset");
            AssetDatabase.SaveAssets();

            var previousMesh = yourSkinnedMeshRenderer.sharedMesh;
            yourSkinnedMeshRenderer.sharedMesh = null;
            yourSkinnedMeshRenderer.sharedMesh = previousMesh;

            armatureObj = null;
        }
    }
示例#4
0
    void OnGUI()
    {
        if (window == null)
        {
            window = GetWindow(typeof(SceneSwitcher));
        }

        GUILayout.Label("Search for Scene");
        GUILayout.BeginHorizontal(GUI.skin.FindStyle("Toolbar"));
        GUI.SetNextControlName("SearchField");
        sceneLookup = GUILayout.TextField(sceneLookup, GUI.skin.FindStyle("ToolbarSeachTextField"), GUILayout.Width(window.position.width - (string.IsNullOrEmpty(sceneLookup) ? 21f : 37f)));

        //search clear button
        if (!string.IsNullOrEmpty(sceneLookup))
        {
            if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton")))
            {
                Unfocus();
            }
        }

        if (GUILayout.Button("", EditorStyles.toolbarDropDown, GUILayout.Width(15f)))
        {
            // create custom dropdown menu on button click
            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("Search By Path"), searchByPath == true, OnSearchFilterChanged, !searchByPath);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Open Search History"), false, OnSearchHistoryOpened, null);

            menu.ShowAsContext();
        }
        GUILayout.EndHorizontal();

        EditorGUILayout.Space();
        GUILayout.Label("Active Scene: " + EditorSceneManager.GetActiveScene().name, EditorStyles.boldLabel);
        EditorGUILayout.Space();

        scrollPos = GUILayout.BeginScrollView(scrollPos);
        if (string.IsNullOrEmpty(sceneLookup)) //list all scenes
        {
            GUIStyle style = EditorStyles.foldout;
            style.fontSize = 15;

            #region Scenes in Build
            List <string> disabledScenesInBuild = new List <string>();
            buildFold = EditorGUILayout.Foldout(buildFold, "Scenes In Build", true);

            if (buildFold)
            {
                //List all ACTIVE scenes in Build Settings
                foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
                {
                    if (!scene.enabled)
                    {
                        disabledScenesInBuild.Add(scene.path);
                    }
                    else
                    {
                        string scenePath = scene.path;
                        string sceneName = scenePath.Substring(scenePath.LastIndexOf("/") + 1).Replace(".unity", string.Empty);

                        EditorGUILayout.Space();
                        if (GUILayout.Button(sceneName))
                        {
                            SwitchScenes(scenePath); Unfocus();
                        }
                        GUILayout.TextField("(" + scenePath + ")", EditorStyles.textField);
                    }
                }

                //List all DISABLED scenes in Build Settings
                if (disabledScenesInBuild.Count > 0)
                {
                    GUILayout.Label("[DISABLED SCENES IN BUILD]");

                    for (int i = 0; i < disabledScenesInBuild.Count; i++)
                    {
                        string scenePath = disabledScenesInBuild[i];
                        string sceneName = scenePath.Substring(scenePath.LastIndexOf("/") + 1).Replace(".unity", string.Empty);

                        EditorGUILayout.Space();
                        if (GUILayout.Button(sceneName))
                        {
                            EditorSceneManager.OpenScene(scenePath); Unfocus();
                        }
                        GUILayout.TextField("(" + scenePath + ")");
                    }
                }
            }
            #endregion

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            #region Scenes in Project
            string[] allScenePaths = AssetDatabase.FindAssets("t:scene");
            projectFold = EditorGUILayout.Foldout(projectFold, "Scenes In Project", true);

            if (projectFold)
            {
                for (int i = 0; i < allScenePaths.Length; i++)
                {
                    string scenePath = AssetDatabase.GUIDToAssetPath(allScenePaths[i]);
                    string sceneName = scenePath.Substring(scenePath.LastIndexOf("/") + 1).Replace(".unity", string.Empty);

                    EditorGUILayout.Space();
                    if (GUILayout.Button(sceneName))
                    {
                        SwitchScenes(scenePath);
                    }
                    GUILayout.TextField("(" + scenePath + ")");
                }
            }
            #endregion
        }
        else //list scenes matching search results
        {
            string[] allScenes = AssetDatabase.FindAssets("t:scene");
            searchCount = 0;
            for (int i = 0; i < allScenes.Length; i++)
            {
                string scenePath = AssetDatabase.GUIDToAssetPath(allScenes[i]);
                string sceneName = scenePath.Substring(scenePath.LastIndexOf("/") + 1).Replace(".unity", string.Empty);
                if (sceneName.ToLower().Contains(sceneLookup.ToLower()) || (searchByPath && scenePath.ToLower().Contains(sceneLookup.ToLower())))
                {
                    EditorGUILayout.Space();
                    if (GUILayout.Button(sceneName))
                    {
                        SwitchScenes(scenePath); Unfocus();
                    }
                    GUILayout.Label("(" + scenePath + ")");
                    searchCount++;
                }
            }
        }
        GUILayout.EndScrollView();

        // Add to search history
        if (!string.IsNullOrEmpty(sceneLookup) && GUI.GetNameOfFocusedControl() != "SearchField" && lastSearchInstance.ToLower() != sceneLookup.ToLower())
        {
            SceneSearchHistory.AddToHistory(this, new SceneSearchHistory.SearchHistory(sceneLookup, searchByPath, searchCount));
            lastSearchInstance = sceneLookup;
            GUI.SetNextControlName("SearchField");
            GUI.FocusControl("SearchField");
        }
    }
        protected override AssetGridItem GetItem(AssetData data)
        {
            const float jitterMargin = 0.125f;

            if (Mathf.Abs(scrollOffset - m_LastHiddenItemOffset) < itemSize.z * jitterMargin) // Avoid jitter while scrolling rows in and out of view
            {
                return(null);
            }

            // If this AssetData hasn't fetched its asset yet, do so now
            if (data.asset == null)
            {
                data.asset   = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(data.index));
                data.preview = data.asset as GameObject;
            }

            var item = base.GetItem(data);

            item.transform.localPosition = m_StartPosition;

            item.scaleFactor = m_ScaleFactor;
            item.SetVisibility(true);

            switch (data.type)
            {
            case "Material":
                var material = data.asset as Material;
                if (material)
                {
                    item.material = material;
                }
                else
                {
                    LoadFallbackTexture(item, data);
                }
                break;

            case "Texture2D":
                goto case "Texture";

            case "Texture":
                var texture = data.asset as Texture;
                if (texture)
                {
                    item.texture = texture;
                }
                else
                {
                    LoadFallbackTexture(item, data);
                }
                break;

            default:
                GameObject icon;
                if (m_IconDictionary.TryGetValue(data.type, out icon))
                {
                    item.icon = icon;
                }
                else
                {
                    LoadFallbackTexture(item, data);
                }
                break;
            }
            return(item);
        }
示例#6
0
    // Before Material is imported we modify default settings


    Material OnAssignMaterialModel(Material mat, Renderer renderer)
    {
        //Copy default Material

        Material material = new Material(mat);
        bool     Loaded   = false;


        //Check if material directory exists if not create it
        if (!Directory.Exists(Application.dataPath + "/Material"))
        {
            //if it doesn't, create it
            Directory.CreateDirectory(Application.dataPath + "/Material");
        }


        //If material has no name, create a default one
        if (material.name == "")
        {
            material.name = "defaultName";
        }


        //Material path
        var materialPath = "Assets/Material/" + material.name + ".mat";


        //Load Material if it already exists
        if (AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)))
        {
            material = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));
            Loaded   = true;
        }


        bool hasAlpha = false;

        // This is the lab renderer shader for the Unity asset store, I use it for VR purpose
        material.shader = Shader.Find("Valve/vr_standard");
        // Use the default one if not using VR
        if (material.shader == null)
        {
            material.shader = Shader.Find("Standard");
        }

        //Remove default texture Unity has assigned (Can mess up things if you have an ALPHA and COLOR texture)
        material.mainTexture = null;

        //Remove default texture Unity has assigned
        material.SetTexture("_DetailAlbedoMap", null);

        //Check if Material has assigned Alpha texture to it and if it is inverted
        string[] matchingAssets = AssetDatabase.FindAssets(AbsoluteName(material.name) + "INVERTALPHA");

        //if not Check if Material has assigned Alpha texture
        if ((matchingAssets.Length == 0))
        {
            matchingAssets = AssetDatabase.FindAssets(AbsoluteName(material.name) + "ALPHA");
        }

        // If asset is found
        if (matchingAssets.Length > 0)
        {
            // Load Texture
            Texture currentTexture = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(matchingAssets[0]), typeof(Texture)) as Texture;
            if (currentTexture != null && material != null)
            {
                // Assign texture and set mode to ALphaBend or Fade
                material.SetFloat("_Mode", 2);
                material.mainTexture = currentTexture;

                //Since there is already a texture set color to white
                material.color = new Color(1, 1, 1, material.color.a);
                hasAlpha       = true;
            }
        }

        //Check if Material has assigned Color texture
        matchingAssets = AssetDatabase.FindAssets(AbsoluteName(material.name) + "COLOR");

        // If asset is found
        if (matchingAssets.Length > 0)
        {
            // Load Texture
            Texture currentTexture = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(matchingAssets[0]), typeof(Texture)) as Texture;
            if (currentTexture != null && material != null)
            {
                // If material already has alpha,  set it to second albedo Map (this makes it look the same as in cinema)
                if (hasAlpha == true)
                {
                    material.SetTexture("_DetailAlbedoMap", currentTexture);
                }
                else
                {
                    // if no Alpha texture, set texture to main texture
                    material.mainTexture = currentTexture;
                    material.color       = new Color(1, 1, 1, material.color.a);
                }
            }
        }

        //Check if Material has assigned Bump texture
        matchingAssets = AssetDatabase.FindAssets(AbsoluteName(material.name) + "BUMP");

        // If asset is found
        if (matchingAssets.Length > 0)
        {
            // Load Texture
            Texture currentTexture = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(matchingAssets[0]), typeof(Texture)) as Texture;
            if (currentTexture != null && material != null)
            {
                // set Bump texture to shader
                material.SetTexture("_BumpMap", currentTexture);
            }
        }

        //Check if Material has assigned LUMINANCE texture
        matchingAssets = AssetDatabase.FindAssets(AbsoluteName(material.name) + "LUMINANCE");

        // If asset is found
        if (matchingAssets.Length > 0)
        {
            // Load Texture
            Texture currentTexture = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(matchingAssets[0]), typeof(Texture)) as Texture;
            if (currentTexture != null && material != null)
            {
                // Use default main material for better Color,  use White as default
                material.SetTexture("_EmissionMap", material.mainTexture);
                material.SetColor("_EmissionColor", Color.white);
            }
        }
        // If material doesn't exist, create it
        if (Loaded == false)
        {
            AssetDatabase.CreateAsset(material, "Assets/Material/" + material.name + ".mat");
        }
        return(null);
    }
示例#7
0
        public bool Locate(object key, Type type, out IList <IResourceLocation> locations)
        {
            CacheKey cacheKey = new CacheKey()
            {
                m_key = key, m_type = type
            };

            if (m_Cache.TryGetValue(cacheKey, out locations))
            {
                return(locations != null);
            }

            locations = new List <IResourceLocation>();
            if (m_keyToEntries.TryGetValue(key, out List <AddressableAssetEntry> entries))
            {
                foreach (AddressableAssetEntry e in entries)
                {
                    if (AssetDatabase.IsValidFolder(e.AssetPath) && !e.labels.Contains(key as string))
                    {
                        continue;
                    }

                    if (type == null)
                    {
                        if (e.MainAssetType != typeof(SceneAsset))
                        {
                            ObjectIdentifier[] ids =
                                ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(new GUID(e.guid),
                                                                                        EditorUserBuildSettings.activeBuildTarget);
                            IEnumerable <Type> subObjectTypes = AddressableAssetEntry.GatherSubObjectTypes(ids, e.guid);

                            if (subObjectTypes.Any())
                            {
                                foreach (Type t in subObjectTypes)
                                {
                                    GatherEntryLocations(e, t, locations, m_AddressableAssetTree);
                                }
                            }
                            else
                            {
                                GatherEntryLocations(e, null, locations, m_AddressableAssetTree);
                            }
                        }
                        else
                        {
                            GatherEntryLocations(e, null, locations, m_AddressableAssetTree);
                        }
                    }
                    else
                    {
                        GatherEntryLocations(e, type, locations, m_AddressableAssetTree);
                    }
                }
            }

            string keyStr = key as string;

            if (!string.IsNullOrEmpty(keyStr))
            {
                //check if the key is a guid first
                var keyPath = AssetDatabase.GUIDToAssetPath(keyStr);
                if (!string.IsNullOrEmpty(keyPath))
                {
                    //only look for folders from GUID if no locations have been found
                    if (locations.Count == 0)
                    {
                        var slash = keyPath.LastIndexOf('/');
                        while (slash > 0)
                        {
                            keyPath = keyPath.Substring(0, slash);
                            var parentFolderKey = AssetDatabase.AssetPathToGUID(keyPath);
                            if (string.IsNullOrEmpty(parentFolderKey))
                            {
                                break;
                            }

                            if (m_keyToEntries.ContainsKey(parentFolderKey))
                            {
                                locations.Add(new ResourceLocationBase(keyPath, AssetDatabase.GUIDToAssetPath(keyStr), typeof(AssetDatabaseProvider).FullName, type));
                                break;
                            }
                            slash = keyPath.LastIndexOf('/');
                        }
                    }
                }
                else
                {
                    //if the key is not a GUID, see if it is contained in a folder entry
                    keyPath = keyStr;
                    int slash = keyPath.LastIndexOf('/');
                    while (slash > 0)
                    {
                        keyPath = keyPath.Substring(0, slash);
                        if (m_keyToEntries.TryGetValue(keyPath, out var entry))
                        {
                            foreach (var e in entry)
                            {
                                var internalId = GetInternalIdFromFolderEntry(keyStr, e);
                                if (!string.IsNullOrEmpty(internalId) && !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(internalId)))
                                {
                                    locations.Add(new ResourceLocationBase(keyStr, internalId, typeof(AssetDatabaseProvider).FullName, type));
                                }
                            }
                            break;
                        }
                        slash = keyPath.LastIndexOf('/');
                    }
                }
            }

            //check resources folders
            if (m_includeResourcesFolders)
            {
                UnityEngine.Object obj = Resources.Load(keyStr, type == null ? typeof(UnityEngine.Object) : type);
                if (obj != null)
                {
                    locations.Add(new ResourceLocationBase(keyStr, keyStr, typeof(LegacyResourcesProvider).FullName, type));
                }
            }

            if (locations.Count == 0)
            {
                locations = null;
                m_Cache.Add(cacheKey, locations);
                return(false);
            }

            m_Cache.Add(cacheKey, locations);
            return(true);
        }
        protected static void CollectDependenciesInPrefab(out PrefabReferenceData[] prds, out AssetReferencedData[] ards)
        {
            string[] all   = AssetDatabase.GetAllAssetPaths();
            float    step1 = 0.3f;
            int      len   = all.Length;
            List <AssetReferencedData>            ars = new List <AssetReferencedData>(2048);
            Dictionary <int, AssetReferencedData> instanceId2Asset = new Dictionary <int, AssetReferencedData>(1024);

            for (int i = 0; i < len; i++)
            {
                string path = all[i];
                float  t    = Mathf.Lerp(0f, step1, (i + 0.5f) / len);
                EditorUtility.DisplayProgressBar("Collecting Dependencies",
                                                 string.Format("Step 1 ({0} / {1}) {2}", i + 1, len, path), t);
                if (AssetDatabase.IsValidFolder(path))
                {
                    continue;
                }
                if (!path.StartsWith("Assets/"))
                {
                    continue;
                }
                if (path.LastIndexOf(".unity", System.StringComparison.OrdinalIgnoreCase) == path.Length - 6)
                {
                    continue;
                }
                AssetReferencedData ard = new AssetReferencedData();
                ard.path   = path;
                ard.asset  = AssetDatabase.LoadMainAssetAtPath(path);
                ard.assets = AssetDatabase.LoadAllAssetsAtPath(path);
                ars.Add(ard);
                foreach (Object obj in ard.assets)
                {
                    if (obj == null)
                    {
                        continue;
                    }
                    instanceId2Asset.Add(obj.GetInstanceID(), ard);
                }
            }
            string[] prefabs = AssetDatabase.FindAssets("t:prefab");
            len = prefabs.Length;
            List <PrefabReferenceData> prs        = new List <PrefabReferenceData>(2048);
            Stack <Transform>          trans      = new Stack <Transform>();
            List <Component>           components = new List <Component>();

            for (int i = 0; i < len; i++)
            {
                PrefabReferenceData prd = new PrefabReferenceData();
                prd.path = AssetDatabase.GUIDToAssetPath(prefabs[i]);
                prs.Add(prd);
                float t = Mathf.Lerp(step1, 1f, (i + 0.5f) / len);
                EditorUtility.DisplayProgressBar("Collecting Dependencies",
                                                 string.Format("Step 2 ({0} / {1}) {2}", i + 1, len, prd.path), t);
                prd.asset = AssetDatabase.LoadMainAssetAtPath(prd.path);
                GameObject go = prd.asset as GameObject;
                if (go == null)
                {
                    continue;
                }
                trans.Push(go.transform);
                while (trans.Count > 0)
                {
                    Transform tt = trans.Pop();
                    tt.GetComponents <Component>(components);
                    foreach (Component component in components)
                    {
                        if (component == null || component is Transform)
                        {
                            continue;
                        }
                        SerializedObject   so = new SerializedObject(component);
                        SerializedProperty p  = so.GetIterator();
                        while (p.NextVisible(true))
                        {
                            if (p.propertyType != SerializedPropertyType.ObjectReference)
                            {
                                continue;
                            }
                            AssetReferencedData ard;
                            if (!instanceId2Asset.TryGetValue(p.objectReferenceInstanceIDValue, out ard))
                            {
                                continue;
                            }
                            if (ard == null || ard.path == prd.path)
                            {
                                continue;
                            }
                            AddReferenceData(prd.path, prd.references, component, p, ard.path);
                            ReferencedData rd = null;
                            foreach (ReferencedData trd in ard.referenced)
                            {
                                if (trd.mainObject == prd.asset)
                                {
                                    rd = trd;
                                    break;
                                }
                            }
                            if (rd == null)
                            {
                                rd            = new ReferencedData();
                                rd.mainObject = prd.asset;
                                ard.referenced.Add(rd);
                            }
                            AddReferenceData(prd.path, rd.references, component, p, ard.path);
                        }
                    }
                    components.Clear();
                    for (int j = tt.childCount - 1; j >= 0; j--)
                    {
                        trans.Push(tt.GetChild(j));
                    }
                }
            }
            EditorUtility.ClearProgressBar();
            prds = prs.ToArray();
            ards = ars.ToArray();
        }
示例#9
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath);

            if (oldShader != null)
            {
                ShaderUtil.ClearShaderMessages(oldShader);
            }

            List <PropertyCollector.TextureInfo> configuredTextures;
            string path = ctx.assetPath;

            AssetCollection assetCollection = new AssetCollection();

            MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);

            var textGraph = File.ReadAllText(path, Encoding.UTF8);
            var graph     = new GraphData
            {
                messageManager = new MessageManager(), assetGuid = AssetDatabase.AssetPathToGUID(path)
            };

            MultiJson.Deserialize(graph, textGraph);
            graph.OnEnable();
            graph.ValidateGraph();

            Shader shader = null;

#if VFX_GRAPH_10_0_0_OR_NEWER
            if (!graph.isOnlyVFXTarget)
#endif
            {
                // build the shader text
                // this will also add Target dependencies into the asset collection
                var text = GetShaderText(path, out configuredTextures, assetCollection, graph);

#if UNITY_2021_1_OR_NEWER
                // 2021.1 or later is guaranteed to have the new version of this function
                shader = ShaderUtil.CreateShaderAsset(ctx, text, false);
#else
                // earlier builds of Unity may or may not have it
                // here we try to invoke the new version via reflection
                var createShaderAssetMethod = typeof(ShaderUtil).GetMethod(
                    "CreateShaderAsset",
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding,
                    null,
                    new Type[] { typeof(AssetImportContext), typeof(string), typeof(bool) },
                    null);

                if (createShaderAssetMethod != null)
                {
                    shader = createShaderAssetMethod.Invoke(null, new Object[] { ctx, text, false }) as Shader;
                }
                else
                {
                    // method doesn't exist in this version of Unity, call old version
                    // this doesn't create dependencies properly, but is the best that we can do
                    shader = ShaderUtil.CreateShaderAsset(text, false);
                }
#endif

                if (graph.messageManager.nodeMessagesChanged)
                {
                    if (graph.messageManager.AnyError())
                    {
                        Debug.LogError($"Shader Graph at {path} has at least one error.");
                    }
                    else
                    {
                        Debug.LogWarning($"Shader Graph at {path} has at least one warning.");
                    }
                }

                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());
            }

            UnityEngine.Object mainObject = shader;
#if VFX_GRAPH_10_0_0_OR_NEWER
            ShaderGraphVfxAsset vfxAsset = null;
            if (graph.hasVFXTarget)
            {
                vfxAsset = GenerateVfxShaderGraphAsset(graph);
                if (mainObject == null)
                {
                    mainObject = vfxAsset;
                }
                else
                {
                    //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset
                    vfxAsset.name = Path.GetFileNameWithoutExtension(path);
                    ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset);
                }
            }
#endif

            Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon");
            ctx.AddObjectToAsset("MainAsset", mainObject, texture);
            ctx.SetMainObject(mainObject);

            foreach (var target in graph.activeTargets)
            {
                if (target is IHasMetadata iHasMetadata)
                {
                    var metadata = iHasMetadata.GetMetadataObject();
                    if (metadata == null)
                    {
                        continue;
                    }

                    metadata.hideFlags = HideFlags.HideInHierarchy;
                    ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata);
                }
            }

            var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>();
            sgMetadata.hideFlags         = HideFlags.HideInHierarchy;
            sgMetadata.assetDependencies = new List <UnityEngine.Object>();

            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage))
                {
                    // this sucks that we have to fully load these assets just to set the reference,
                    // which then gets serialized as the GUID that we already have here.  :P

                    var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
                    if (!string.IsNullOrEmpty(dependencyPath))
                    {
                        sgMetadata.assetDependencies.Add(
                            AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object)));
                    }
                }
            }
            ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata);

            // declare dependencies
            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency))
                {
                    ctx.DependsOnSourceAsset(asset.Key);

                    // I'm not sure if this warning below is actually used or not, keeping it to be safe
                    var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key);

                    // Ensure that dependency path is relative to project
                    if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/"))
                    {
                        Debug.LogWarning($"Invalid dependency path: {assetPath}", mainObject);
                    }
                }

                // NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies
                // HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies
                // on GUIDs that don't exist in the project.  For both of those reasons, we re-declare the dependencies here.
                if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
                {
                    ctx.DependsOnArtifact(asset.Key);
                }
            }
        }
示例#10
0
        public string GetSubshader(IMasterNode iMasterNode, GenerationMode mode, List <string> sourceAssetDependencyPaths = null)
        {
            if (sourceAssetDependencyPaths != null)
            {
                // HDLitSubShader.cs
                sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("bac1a9627cfec924fa2ea9c65af8eeca"));
                // HDSubShaderUtilities.cs
                sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("713ced4e6eef4a44799a4dd59041484b"));
            }

            var masterNode = iMasterNode as HDLitMasterNode;

            var subShader = new ShaderGenerator();

            subShader.AddShaderChunk("SubShader", true);
            subShader.AddShaderChunk("{", true);
            subShader.Indent();
            {
                SurfaceMaterialTags materialTags = HDSubShaderUtilities.BuildMaterialTags(masterNode.surfaceType, masterNode.alphaTest.isOn, masterNode.drawBeforeRefraction.isOn, masterNode.sortPriority);

                // Add tags at the SubShader level
                {
                    var tagsVisitor = new ShaderStringBuilder();
                    materialTags.GetTags(tagsVisitor, HDRenderPipeline.k_ShaderTagName);
                    subShader.AddShaderChunk(tagsVisitor.ToString(), false);
                }

                // generate the necessary shader passes
                bool opaque      = (masterNode.surfaceType == SurfaceType.Opaque);
                bool transparent = !opaque;

                bool distortionActive               = transparent && masterNode.distortion.isOn;
                bool transparentBackfaceActive      = transparent && masterNode.backThenFrontRendering.isOn;
                bool transparentDepthPrepassActive  = transparent && masterNode.alphaTest.isOn && masterNode.alphaTestDepthPrepass.isOn;
                bool transparentDepthPostpassActive = transparent && masterNode.alphaTest.isOn && masterNode.alphaTestDepthPostpass.isOn;

                GenerateShaderPassLit(masterNode, m_PassMETA, mode, subShader, sourceAssetDependencyPaths);
                GenerateShaderPassLit(masterNode, m_PassShadowCaster, mode, subShader, sourceAssetDependencyPaths);
                GenerateShaderPassLit(masterNode, m_SceneSelectionPass, mode, subShader, sourceAssetDependencyPaths);

                if (opaque)
                {
                    GenerateShaderPassLit(masterNode, m_PassDepthOnly, mode, subShader, sourceAssetDependencyPaths);
                    GenerateShaderPassLit(masterNode, m_PassGBuffer, mode, subShader, sourceAssetDependencyPaths);
                    GenerateShaderPassLit(masterNode, m_PassMotionVectors, mode, subShader, sourceAssetDependencyPaths);
                }

                if (distortionActive)
                {
                    GenerateShaderPassLit(masterNode, m_PassDistortion, mode, subShader, sourceAssetDependencyPaths);
                }

                if (transparentBackfaceActive)
                {
                    GenerateShaderPassLit(masterNode, m_PassTransparentBackface, mode, subShader, sourceAssetDependencyPaths);
                }

                // Assign define here based on opaque or transparent to save some variant
                m_PassForward.ExtraDefines = opaque ? HDSubShaderUtilities.s_ExtraDefinesForwardOpaque : HDSubShaderUtilities.s_ExtraDefinesForwardTransparent;
                GenerateShaderPassLit(masterNode, m_PassForward, mode, subShader, sourceAssetDependencyPaths);

                if (transparentDepthPrepassActive)
                {
                    GenerateShaderPassLit(masterNode, m_PassTransparentDepthPrepass, mode, subShader, sourceAssetDependencyPaths);
                }

                if (transparentDepthPostpassActive)
                {
                    GenerateShaderPassLit(masterNode, m_PassTransparentDepthPostpass, mode, subShader, sourceAssetDependencyPaths);
                }
            }
            subShader.Deindent();
            subShader.AddShaderChunk("}", true);

            subShader.AddShaderChunk(@"CustomEditor ""UnityEditor.ShaderGraph.HDLitGUI""");

            return(subShader.GetShaderString(0));
        }
        /// <summary>
        /// 简单收集
        /// </summary>
        public static void CollectShaderVariant()
        {
            //先搜集所有keyword到工具类SVC
            ToolSVC = new ShaderVariantCollection();
            var shaders = AssetDatabase.FindAssets("t:Shader", new string[] { "Assets", "Packages" }).ToList();

            foreach (var shader in shaders)
            {
                ShaderVariantCollection.ShaderVariant sv = new ShaderVariantCollection.ShaderVariant();
                var shaderPath = AssetDatabase.GUIDToAssetPath(shader);
                sv.shader = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath);
                ToolSVC.Add(sv);
                //
                allShaderNameList.Add(shaderPath);
            }


            //防空
            var dirt = Path.GetDirectoryName(toolsSVCpath);

            if (!Directory.Exists(dirt))
            {
                Directory.CreateDirectory(dirt);
            }

            AssetDatabase.CreateAsset(ToolSVC, toolsSVCpath);


            //搜索所有Mat
            var paths   = BApplication.GetAllRuntimeDirects().ToArray();
            var assets  = AssetDatabase.FindAssets("t:Prefab", paths).ToList();
            var assets2 = AssetDatabase.FindAssets("t:Material", paths);

            assets.AddRange(assets2);
            List <string> allMatPaths = new List <string>();

            //GUID to assetPath
            for (int i = 0; i < assets.Count; i++)
            {
                var path = AssetDatabase.GUIDToAssetPath(assets[i]);
                //获取依赖中的mat
                var dependenciesPath = AssetDatabase.GetDependencies(path, true);
                var mats             = dependenciesPath.ToList().FindAll((dp) => AssetDatabase.GetMainAssetTypeAtPath(dp) == typeof(Material));
                allMatPaths.AddRange(mats);
            }

            allMatPaths = allMatPaths.Distinct().ToList();
            ShaderVariantCollection allShaderVaraint = null;

            //收集ShaderVaraint
            var tools = new ShaderVariantsCollectionTools();

            allShaderVaraint = tools.CollectionKeywords(allMatPaths.ToArray(), ToolSVC);



            var targetDir = Path.GetDirectoryName(BResources.ALL_SHADER_VARAINT_ASSET_PATH);

            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }

            AssetDatabase.DeleteAsset(BResources.ALL_SHADER_VARAINT_ASSET_PATH);
            AssetDatabase.CreateAsset(allShaderVaraint, BResources.ALL_SHADER_VARAINT_ASSET_PATH);
            AssetDatabase.Refresh();

            // var dependencies = AssetDatabase.GetDependencies(BResources.ALL_SHADER_VARAINT_ASSET_PATH);
            // foreach (var guid in dependencies )
            // {
            //     Debug.Log("依赖shader:" + guid);
            // }
        }
示例#12
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        SerializedProperty key            = property.FindPropertyRelative("Key");
        SerializedProperty resource       = property.FindPropertyRelative("Resource");
        SerializedProperty resourceFilter = property.FindPropertyRelative("ResourceFilter");

        float w = position.width;
        float x = position.x;

        position.width  = c_LabelWidth;
        position.height = c_FieldHeight;
        string keyStr = key.stringValue;

        string[] list     = new string[] { "selfEffect", "hitEffect", "emitEffect", "targetEffect", "selfEffect1", "selfEffect2", "selfEffect3", "hitEffect1", "hitEffect2", "hitEffect3", "emitEffect1", "emitEffect2", "emitEffect3", "targetEffect1", "targetEffect2", "targetEffect3" };
        int      keyIndex = System.Array.IndexOf(list, keyStr);

        EditorGUI.BeginChangeCheck();
        keyIndex = EditorGUI.Popup(position, keyIndex, list);
        if (EditorGUI.EndChangeCheck())
        {
            if (keyIndex >= 0)
            {
                key.stringValue = list[keyIndex];
            }
        }

        position.width = 240;
        position.x    += c_LabelWidth;
        string[] guids = AssetDatabase.FindAssets("t:Prefab," + Path.GetFileName(resource.stringValue));
        Object   v     = null;

        for (int i = 0; i < guids.Length; ++i)
        {
            string path = AssetDatabase.GUIDToAssetPath(guids[i]);
            if (path.Contains("Resources/" + resource.stringValue))
            {
                v = AssetDatabase.LoadAssetAtPath <GameObject>(path);
                break;
            }
        }
        EditorGUI.BeginChangeCheck();
        v = EditorGUI.ObjectField(position, v, typeof(GameObject), false);
        if (EditorGUI.EndChangeCheck())
        {
            string respath    = AssetDatabase.GetAssetPath(v.GetInstanceID());
            int    startIndex = respath.IndexOf(c_Resources);
            if (startIndex >= 0)
            {
                resource.stringValue = respath.Substring(startIndex + c_Resources.Length, respath.Length - startIndex - c_Resources.Length - c_Ext.Length);
            }
            else
            {
                resource.stringValue = respath;
            }
        }

        position.width = w - 240;
        position.x    += 240;
        EditorGUI.LabelField(position, resource.stringValue);

        EditorGUI.EndProperty();
    }
示例#13
0
        public override bool Run(FileInfo buildTarget)
        {
            if (!quitCallbackAdded)
            {
                // On domain reload, the quitCallbackAdded is reset to default (false), and
                // registerd event handlers are reset. To ensure we don't have an zombie processes
                // we ensure to kill processes we were tracking just prior to the assembly
                // being reloaded OR just prior to exiting the editor.
                AssemblyReloadEvents.beforeAssemblyReload += OnEditorUnload;
                EditorApplication.quitting += OnEditorUnload;
                quitCallbackAdded           = true;
            }

            PosixSocketBridgeRunner.EnsureRunning();

            var    guids          = AssetDatabase.FindAssets("websockify");
            string websockifyPath = "";

            foreach (var g in guids)
            {
                var jsPath = AssetDatabase.GUIDToAssetPath(g);
                if (Path.GetFileName(jsPath) == "websockify.js")
                {
                    websockifyPath = Path.GetFullPath(jsPath);
                }
            }

            string projectPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
            string stevePath   = Path.Combine(projectPath, "Library", "DotsRuntimeBuild", "artifacts", "Stevedore");

            string httpServerPath = Path.Combine(stevePath, "http-server", "bin", "http-server");

#if UNITY_EDITOR_OSX
            string nodePath = Path.Combine(stevePath, "node-mac-x64", "bin", "node");
#elif UNITY_EDITOR_LINUX
            string nodePath = Path.Combine(stevePath, "node-linux-x64", "bin", "node");
#else
            string nodePath = Path.Combine(stevePath, "node-win-x64", "node.exe");
#endif

            if (!File.Exists(nodePath) || !File.Exists(httpServerPath))
            {
                return(ReportSuccessWithWarning(buildTarget.FullName, $"Unable to run web build: can't find either {nodePath} or {httpServerPath}"));
            }

            string serverArgs     = $"\"{httpServerPath}\" -c-1 -s -p 8084 .";
            string websockifyArgs = $"\"{websockifyPath}\" 54998 localhost:34999";

            // Start http-server
            var serverStartInfo = new ProcessStartInfo();
            serverStartInfo.FileName         = nodePath;
            serverStartInfo.Arguments        = serverArgs;
            serverStartInfo.WorkingDirectory = buildTarget.Directory.FullName;
            serverStartInfo.CreateNoWindow   = true;
            serverStartInfo.UseShellExecute  = false;

            EnsureProcessDead(serverProcess);
            serverProcess = new Process()
            {
                StartInfo = serverStartInfo
            };
            var success = serverProcess.Start();
            if (!success)
            {
                serverProcess = null;
                return(ReportSuccessWithWarning(buildTarget.FullName, "Error starting local server. Unable to run web build."));
            }

            // Start the websockify proxy server
            var wsStartInfo = new ProcessStartInfo();
            wsStartInfo.FileName        = nodePath;
            wsStartInfo.Arguments       = websockifyArgs;
            wsStartInfo.CreateNoWindow  = true;
            wsStartInfo.UseShellExecute = false;

            EnsureProcessDead(wsProcess);
            wsProcess = new Process()
            {
                StartInfo = wsStartInfo
            };
            success = wsProcess.Start();
            if (!success)
            {
                wsProcess = null;
                return(ReportSuccessWithWarning(buildTarget.FullName, "Error starting websockify proxy server. Unable to run web build."));
            }

            Application.OpenURL("http://localhost:8084/" + buildTarget.Name);

            return(true);
        }
示例#14
0
        public GraphElementSearcherDatabase AddMacros()
        {
            string[] assetGUIDs             = AssetDatabase.FindAssets($"t:{typeof(VSGraphAssetModel).Name}");
            List <VSGraphAssetModel> macros = assetGUIDs.Select(assetGuid =>
                                                                AssetDatabase.LoadAssetAtPath <VSGraphAssetModel>(AssetDatabase.GUIDToAssetPath(assetGuid)))
                                              .Where(x =>
            {
                if (x.GraphModel == null)
                {
                    Debug.Log("No GraphModel");
                }
                else if (x.GraphModel.Stencil == null)
                {
                    Debug.Log("No Stencil");
                }
                else
                {
                    return(x.GraphModel.Stencil.GetType() == typeof(MacroStencil));
                }

                return(false);
            })
                                              .ToList();

            if (macros.Count == 0)
            {
                return(this);
            }

            SearcherItem parent = SearcherItemUtility.GetItemFromPath(Items, k_Macros);

            foreach (VSGraphAssetModel macro in macros)
            {
                parent.AddChild(new GraphNodeModelSearcherItem(
                                    new GraphAssetSearcherItemData(macro),
                                    data => data.CreateMacroRefNode(macro.GraphModel as VSGraphModel),
                                    $"{k_Macro} {macro.name}"
                                    ));
            }

            return(this);
        }
示例#15
0
    Texture2D BuildAnimationSpriteAtlas()
    {
        int nTotalFrame = 0;

        for (int n = 0; n < m_Sel.m_SpriteList.Count; n++)
        {
            if (m_Sel.m_SpriteList[n].m_bIncludedAtlas == false || m_Sel.m_SpriteList[n].m_TextureGUID == "")
            {
                continue;
            }

            Texture2D selTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(m_Sel.m_SpriteList[n].m_TextureGUID), typeof(Texture2D));
            m_Sel.m_SpriteList[n].m_nFrameCount = selTexture.width / selTexture.height;
            m_Sel.m_SpriteList[n].m_nFrameSize  = selTexture.height;
            m_Sel.m_nFrameSize = m_Sel.m_SpriteList[n].m_nFrameSize;

            nTotalFrame += m_Sel.m_SpriteList[n].m_nFrameCount;
        }

        int       nTexSize     = GetTextureSize(nTotalFrame, m_Sel.m_nFrameSize);
        int       nCapSize     = m_Sel.m_nFrameSize;
        int       nMaxCount    = (nTexSize / nCapSize) * (nTexSize / nCapSize);
        int       nTexHeight   = (nTotalFrame <= nMaxCount / 2 ? nTexSize / 2 : nTexSize);
        Texture2D AtlasTexture = new Texture2D(nTexSize, nTexHeight, TextureFormat.ARGB32, false);
        Color     clearColor   = new Color(0, 0, 0, 0);

        m_Sel.m_nTilingX = nTexSize / nCapSize;
        m_Sel.m_nTilingY = nTexHeight / nCapSize;
        Debug.Log(nMaxCount);
        Debug.Log(nTexHeight);
        Debug.Log(m_Sel.m_nTilingY);

        // clear
        for (int x = 0; x < AtlasTexture.width; x++)
        {
            for (int y = 0; y < AtlasTexture.height; y++)
            {
                AtlasTexture.SetPixel(x, y, clearColor);
            }
        }

        // copy
        int nSaveCount = 0;

        for (int n = 0; n < m_Sel.m_SpriteList.Count; n++)
        {
            if (m_Sel.m_SpriteList[n].m_bIncludedAtlas == false || m_Sel.m_SpriteList[n].m_TextureGUID == "")
            {
                continue;
            }
            m_Sel.m_SpriteList[n].m_nStartFrame = nSaveCount;

            // Load Texture ---------------------------------------------------------
            Texture2D selTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(m_Sel.m_SpriteList[n].m_TextureGUID), typeof(Texture2D));
            SetSourceTexture(selTexture);

            for (int sn = 0; sn < m_Sel.m_SpriteList[n].m_nFrameCount; sn++)
            {
                Color[] colBuf = selTexture.GetPixels(m_Sel.m_nFrameSize * sn, 0, m_Sel.m_nFrameSize, m_Sel.m_nFrameSize);

                // 알파조정 처리
                for (int an = 0; an < colBuf.Length; an++)
                {
                    if (m_Sel.m_SpriteList[n].m_fMaxTextureAlpha < colBuf[an].a)
                    {
                        colBuf[an].a = m_Sel.m_SpriteList[n].m_fMaxTextureAlpha;
                    }
                }

                AtlasTexture.SetPixels(((nSaveCount) % (nTexSize / nCapSize)) * nCapSize, nTexHeight - (((nSaveCount) / (nTexSize / nCapSize) + 1) * nCapSize), nCapSize, nCapSize, colBuf);
                nSaveCount++;
            }

            selTexture = null;
        }

        return(AtlasTexture);
    }
示例#16
0
        // TODO: Fix this
        static ShaderGraphVfxAsset GenerateVfxShaderGraphAsset(GraphData graph)
        {
            var target = graph.activeTargets.FirstOrDefault(x => x is VFXTarget) as VFXTarget;

            if (target == null)
            {
                return(null);
            }

            // we need to override graph.isSubgraph, so save old state to restore it
            // (this is not great, but whole VFX pipeline is rather hacky at the moment)
            // use try/finally to ensure it always gets restored
            bool oldIsSubGraph = graph.isSubGraph;

            try
            {
                // override to generate as a subgraph, as that is what VFX is using it as
                graph.isSubGraph = true;

                var nl     = Environment.NewLine;
                var indent = new string(' ', 4);
                var asset  = ScriptableObject.CreateInstance <ShaderGraphVfxAsset>();
                var result = asset.compilationResult = new GraphCompilationResult();
                var mode   = GenerationMode.ForReals;

                asset.lit           = target.lit;
                asset.alphaClipping = target.alphaTest;

                var assetGuid = graph.assetGuid;
                var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
                var hlslName  = NodeUtils.GetHLSLSafeName(Path.GetFileNameWithoutExtension(assetPath));

                var ports = new List <MaterialSlot>();
                var nodes = new List <AbstractMaterialNode>();

                foreach (var vertexBlock in graph.vertexContext.blocks)
                {
                    vertexBlock.value.GetInputSlots(ports);
                    NodeUtils.DepthFirstCollectNodesFromNode(nodes, vertexBlock);
                }

                foreach (var fragmentBlock in graph.fragmentContext.blocks)
                {
                    fragmentBlock.value.GetInputSlots(ports);
                    NodeUtils.DepthFirstCollectNodesFromNode(nodes, fragmentBlock);
                }

                //Remove inactive blocks from generation
                {
                    var tmpCtx = new TargetActiveBlockContext(new List <BlockFieldDescriptor>(), null);
                    target.GetActiveBlocks(ref tmpCtx);
                    ports.RemoveAll(materialSlot =>
                    {
                        return(!tmpCtx.activeBlocks.Any(o => materialSlot.RawDisplayName() == o.displayName));
                    });
                }

                var bodySb        = new ShaderStringBuilder(1);
                var graphIncludes = new IncludeCollection();
                var registry      = new FunctionRegistry(new ShaderStringBuilder(), graphIncludes, true);

                foreach (var properties in graph.properties)
                {
                    properties.ValidateConcretePrecision(graph.concretePrecision);
                }

                foreach (var node in nodes)
                {
                    if (node is IGeneratesBodyCode bodyGenerator)
                    {
                        bodySb.currentNode = node;
                        bodyGenerator.GenerateNodeCode(bodySb, mode);
                        bodySb.ReplaceInCurrentMapping(PrecisionUtil.Token, node.concretePrecision.ToShaderString());
                    }

                    if (node is IGeneratesFunction generatesFunction)
                    {
                        registry.builder.currentNode = node;
                        generatesFunction.GenerateNodeFunction(registry, mode);
                    }
                }
                bodySb.currentNode = null;

                var portNodeSets = new HashSet <AbstractMaterialNode> [ports.Count];
                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    var port    = ports[portIndex];
                    var nodeSet = new HashSet <AbstractMaterialNode>();
                    NodeUtils.CollectNodeSet(nodeSet, port);
                    portNodeSets[portIndex] = nodeSet;
                }

                var portPropertySets = new HashSet <string> [ports.Count];
                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    portPropertySets[portIndex] = new HashSet <string>();
                }

                foreach (var node in nodes)
                {
                    if (!(node is PropertyNode propertyNode))
                    {
                        continue;
                    }

                    for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                    {
                        var portNodeSet = portNodeSets[portIndex];
                        if (portNodeSet.Contains(node))
                        {
                            portPropertySets[portIndex].Add(propertyNode.property.objectId);
                        }
                    }
                }

                var shaderProperties = new PropertyCollector();
                foreach (var node in nodes)
                {
                    node.CollectShaderProperties(shaderProperties, GenerationMode.ForReals);
                }

                asset.SetTextureInfos(shaderProperties.GetConfiguredTexutres());

                var codeSnippets      = new List <string>();
                var portCodeIndices   = new List <int> [ports.Count];
                var sharedCodeIndices = new List <int>();
                for (var i = 0; i < portCodeIndices.Length; i++)
                {
                    portCodeIndices[i] = new List <int>();
                }

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"#include \"Packages/com.unity.shadergraph/ShaderGraphLibrary/Functions.hlsl\"{nl}");

                foreach (var include in graphIncludes)
                {
                    sharedCodeIndices.Add(codeSnippets.Count);
                    codeSnippets.Add(include.value + nl);
                }

                for (var registryIndex = 0; registryIndex < registry.names.Count; registryIndex++)
                {
                    var name      = registry.names[registryIndex];
                    var source    = registry.sources[name];
                    var precision = source.nodes.First().concretePrecision;

                    var hasPrecisionMismatch = false;
                    var nodeNames            = new HashSet <string>();
                    foreach (var node in source.nodes)
                    {
                        nodeNames.Add(node.name);
                        if (node.concretePrecision != precision)
                        {
                            hasPrecisionMismatch = true;
                            break;
                        }
                    }

                    if (hasPrecisionMismatch)
                    {
                        var message = new StringBuilder($"Precision mismatch for function {name}:");
                        foreach (var node in source.nodes)
                        {
                            message.AppendLine($"{node.name} ({node.objectId}): {node.concretePrecision}");
                        }
                        throw new InvalidOperationException(message.ToString());
                    }

                    var code = source.code.Replace(PrecisionUtil.Token, precision.ToShaderString());
                    code = $"// Node: {string.Join(", ", nodeNames)}{nl}{code}";
                    var codeIndex = codeSnippets.Count;
                    codeSnippets.Add(code + nl);
                    for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                    {
                        var portNodeSet = portNodeSets[portIndex];
                        foreach (var node in source.nodes)
                        {
                            if (portNodeSet.Contains(node))
                            {
                                portCodeIndices[portIndex].Add(codeIndex);
                                break;
                            }
                        }
                    }
                }

                foreach (var property in graph.properties)
                {
                    if (property.isExposed)
                    {
                        continue;
                    }

                    for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                    {
                        var portPropertySet = portPropertySets[portIndex];
                        if (portPropertySet.Contains(property.objectId))
                        {
                            portCodeIndices[portIndex].Add(codeSnippets.Count);
                        }
                    }

                    ShaderStringBuilder builder = new ShaderStringBuilder();
                    property.ForeachHLSLProperty(h => h.AppendTo(builder));

                    codeSnippets.Add($"// Property: {property.displayName}{nl}{builder.ToCodeBlock()}{nl}{nl}");
                }


                var inputStructName        = $"SG_Input_{assetGuid}";
                var outputStructName       = $"SG_Output_{assetGuid}";
                var evaluationFunctionName = $"SG_Evaluate_{assetGuid}";

                #region Input Struct

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"struct {inputStructName}{nl}{{{nl}");

                #region Requirements

                var portRequirements = new ShaderGraphRequirements[ports.Count];
                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    var requirementsNodes = portNodeSets[portIndex].ToList();
                    requirementsNodes.Add(ports[portIndex].owner);
                    portRequirements[portIndex] = ShaderGraphRequirements.FromNodes(requirementsNodes, ports[portIndex].stageCapability);
                }

                var portIndices = new List <int>();
                portIndices.Capacity = ports.Count;

                void AddRequirementsSnippet(Func <ShaderGraphRequirements, bool> predicate, string snippet)
                {
                    portIndices.Clear();
                    for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                    {
                        if (predicate(portRequirements[portIndex]))
                        {
                            portIndices.Add(portIndex);
                        }
                    }

                    if (portIndices.Count > 0)
                    {
                        foreach (var portIndex in portIndices)
                        {
                            portCodeIndices[portIndex].Add(codeSnippets.Count);
                        }

                        codeSnippets.Add($"{indent}{snippet};{nl}");
                    }
                }

                void AddCoordinateSpaceSnippets(InterpolatorType interpolatorType, Func <ShaderGraphRequirements, NeededCoordinateSpace> selector)
                {
                    foreach (var space in EnumInfo <CoordinateSpace> .values)
                    {
                        var neededSpace = space.ToNeededCoordinateSpace();
                        AddRequirementsSnippet(r => (selector(r) & neededSpace) > 0, $"float3 {space.ToVariableName(interpolatorType)}");
                    }
                }

                // TODO: Rework requirements system to make this better
                AddCoordinateSpaceSnippets(InterpolatorType.Normal, r => r.requiresNormal);
                AddCoordinateSpaceSnippets(InterpolatorType.Tangent, r => r.requiresTangent);
                AddCoordinateSpaceSnippets(InterpolatorType.BiTangent, r => r.requiresBitangent);
                AddCoordinateSpaceSnippets(InterpolatorType.ViewDirection, r => r.requiresViewDir);
                AddCoordinateSpaceSnippets(InterpolatorType.Position, r => r.requiresPosition);

                AddRequirementsSnippet(r => r.requiresVertexColor, $"float4 {ShaderGeneratorNames.VertexColor}");
                AddRequirementsSnippet(r => r.requiresScreenPosition, $"float4 {ShaderGeneratorNames.ScreenPosition}");
                AddRequirementsSnippet(r => r.requiresFaceSign, $"float4 {ShaderGeneratorNames.FaceSign}");

                foreach (var uvChannel in EnumInfo <UVChannel> .values)
                {
                    AddRequirementsSnippet(r => r.requiresMeshUVs.Contains(uvChannel), $"half4 {uvChannel.GetUVName()}");
                }

                AddRequirementsSnippet(r => r.requiresTime, $"float3 {ShaderGeneratorNames.TimeParameters}");

                #endregion

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"}};{nl}{nl}");

                #endregion

                // VFX Code heavily relies on the slotId from the original MasterNodes
                // Since we keep these around for upgrades anyway, for now it is simpler to use them
                // Therefore we remap the output blocks back to the original Ids here
                var originialPortIds = new int[ports.Count];
                for (int i = 0; i < originialPortIds.Length; i++)
                {
                    if (!VFXTarget.s_BlockMap.TryGetValue((ports[i].owner as BlockNode).descriptor, out var originalId))
                    {
                        continue;
                    }

                    // In Master Nodes we had a different BaseColor/Color slot id between Unlit/Lit
                    // In the stack we use BaseColor for both cases. Catch this here.
                    if (asset.lit && originalId == ShaderGraphVfxAsset.ColorSlotId)
                    {
                        originalId = ShaderGraphVfxAsset.BaseColorSlotId;
                    }

                    originialPortIds[i] = originalId;
                }

                #region Output Struct

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"struct {outputStructName}{nl}{{");

                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    var port = ports[portIndex];
                    portCodeIndices[portIndex].Add(codeSnippets.Count);
                    codeSnippets.Add($"{nl}{indent}{port.concreteValueType.ToShaderString(graph.concretePrecision)} {port.shaderOutputName}_{originialPortIds[portIndex]};");
                }

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"{nl}}};{nl}{nl}");

                #endregion

                #region Graph Function

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"{outputStructName} {evaluationFunctionName}({nl}{indent}{inputStructName} IN");

                var inputProperties     = new List <AbstractShaderProperty>();
                var portPropertyIndices = new List <int> [ports.Count];
                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    portPropertyIndices[portIndex] = new List <int>();
                }

                foreach (var property in graph.properties)
                {
                    if (!property.isExposed)
                    {
                        continue;
                    }

                    var propertyIndex = inputProperties.Count;
                    var codeIndex     = codeSnippets.Count;

                    for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                    {
                        var portPropertySet = portPropertySets[portIndex];
                        if (portPropertySet.Contains(property.objectId))
                        {
                            portCodeIndices[portIndex].Add(codeIndex);
                            portPropertyIndices[portIndex].Add(propertyIndex);
                        }
                    }

                    inputProperties.Add(property);
                    codeSnippets.Add($",{nl}{indent}/* Property: {property.displayName} */ {property.GetPropertyAsArgumentString()}");
                }

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"){nl}{{");

                #region Node Code

                for (var mappingIndex = 0; mappingIndex < bodySb.mappings.Count; mappingIndex++)
                {
                    var mapping = bodySb.mappings[mappingIndex];
                    var code    = bodySb.ToString(mapping.startIndex, mapping.count);
                    if (string.IsNullOrWhiteSpace(code))
                    {
                        continue;
                    }

                    code = $"{nl}{indent}// Node: {mapping.node.name}{nl}{code}";
                    var codeIndex = codeSnippets.Count;
                    codeSnippets.Add(code);
                    for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                    {
                        var portNodeSet = portNodeSets[portIndex];
                        if (portNodeSet.Contains(mapping.node))
                        {
                            portCodeIndices[portIndex].Add(codeIndex);
                        }
                    }
                }

                #endregion

                #region Output Mapping

                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"{nl}{indent}// VFXMasterNode{nl}{indent}{outputStructName} OUT;{nl}");

                // Output mapping
                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    var port = ports[portIndex];
                    portCodeIndices[portIndex].Add(codeSnippets.Count);
                    codeSnippets.Add($"{indent}OUT.{port.shaderOutputName}_{originialPortIds[portIndex]} = {port.owner.GetSlotValue(port.id, GenerationMode.ForReals, graph.concretePrecision)};{nl}");
                }

                #endregion

                // Function end
                sharedCodeIndices.Add(codeSnippets.Count);
                codeSnippets.Add($"{indent}return OUT;{nl}}}{nl}");

                #endregion

                result.codeSnippets      = codeSnippets.ToArray();
                result.sharedCodeIndices = sharedCodeIndices.ToArray();
                result.outputCodeIndices = new IntArray[ports.Count];
                for (var i = 0; i < ports.Count; i++)
                {
                    result.outputCodeIndices[i] = portCodeIndices[i].ToArray();
                }

                var outputMetadatas = new OutputMetadata[ports.Count];
                for (int portIndex = 0; portIndex < outputMetadatas.Length; portIndex++)
                {
                    outputMetadatas[portIndex] = new OutputMetadata(portIndex, ports[portIndex].shaderOutputName, originialPortIds[portIndex]);
                }

                asset.SetOutputs(outputMetadatas);

                asset.evaluationFunctionName = evaluationFunctionName;
                asset.inputStructName        = inputStructName;
                asset.outputStructName       = outputStructName;
                asset.portRequirements       = portRequirements;
                asset.concretePrecision      = graph.concretePrecision;
                asset.SetProperties(inputProperties);
                asset.outputPropertyIndices = new IntArray[ports.Count];
                for (var portIndex = 0; portIndex < ports.Count; portIndex++)
                {
                    asset.outputPropertyIndices[portIndex] = portPropertyIndices[portIndex].ToArray();
                }

                return(asset);
            }
            finally
            {
                graph.isSubGraph = oldIsSubGraph;
            }
        }
    void VisualizeHits()
    {
        var current = Event.current;

        var windowRect = position;

        windowRect.height = BaseHeight;

        GUILayout.BeginVertical();
        GUILayout.Space(5);

        for (var i = 0; i < _hits.Count; i++)
        {
            var style = i % 2 == 0 ? Styles.EntryOdd : Styles.EntryEven;

            GUILayout.BeginHorizontal(GUILayout.Height(EditorGUIUtility.singleLineHeight * 2),
                                      GUILayout.ExpandWidth(true));
            var elementRect = GUILayoutUtility.GetRect(0, 0, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
            GUILayout.EndHorizontal();

            windowRect.height += EditorGUIUtility.singleLineHeight * 2;

            if (current.type == EventType.Repaint)
            {
                style.Draw(elementRect, false, false, i == _selectedIndex, false);
                var assetPath = AssetDatabase.GUIDToAssetPath(_hits[i]);
                var icon      = AssetDatabase.GetCachedIcon(assetPath);

                var iconRect = elementRect;
                iconRect.x     = 30;
                iconRect.width = 25;
                GUI.DrawTexture(iconRect, icon, ScaleMode.ScaleToFit);

                var assetName        = Path.GetFileName(assetPath);
                var coloredAssetName = new StringBuilder();

                var start = assetName.ToLower().IndexOf(_input);
                var end   = start + _input.Length;

                // Sometimes the AssetDatabase finds assets without the search input in it.
                if (start == -1)
                {
                    coloredAssetName.Append(string.Format("<color=#{0}>{1}</color>", Styles.NormalColor, assetName));
                }
                else
                {
                    if (0 != start)
                    {
                        coloredAssetName.Append(string.Format("<color=#{0}>{1}</color>", Styles.NormalColor, assetName.Substring(0, start)));
                    }

                    coloredAssetName.Append(string.Format("<color=#{0}><b>{1}</b></color>", Styles.HighlightColor, assetName.Substring(start, end - start)));

                    if (end != assetName.Length - end)
                    {
                        coloredAssetName.Append(string.Format("<color=#{0}>{1}</color>", Styles.NormalColor, assetName.Substring(end, assetName.Length - end)));
                    }
                }

                var labelRect = elementRect;
                labelRect.x = 60;
                GUI.Label(labelRect, coloredAssetName.ToString(), Styles.ResultLabelStyle);
            }

            if (current.type == EventType.MouseDown && elementRect.Contains(current.mousePosition))
            {
                _selectedIndex = i;

                if (current.clickCount == 2)
                {
                    OpenSelectedAssetAndClose();
                }
                else
                {
                    FocusSelection();
                }

                Repaint();
            }
        }

        windowRect.height += 5;
        position           = windowRect;

        GUILayout.EndVertical();
    }
示例#18
0
        /// <summary>
        /// Check for Updates with GitHub
        /// </summary>
        static void CheckForUpdate()
        {
            var fileContent = string.Empty;

            EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f);

            // Because were not a runtime framework, lets just use the simplest way of doing this
            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs");
                }
            }
            catch (Exception e)
            {
                if (Debug)
                {
                    UnityEngine.Debug.Log("[VSCode] " + e.Message);
                }

                // Don't go any further if there is an error
                return;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            // Set the last update time
            LastUpdate = DateTime.Now;

            // Fix for oddity in downlo
            if (fileContent.Substring(0, 2) != "/*")
            {
                int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase);

                // Jump over junk characters
                fileContent = fileContent.Substring(startPosition);
            }

            string[] fileExploded = fileContent.Split('\n');
            if (fileExploded.Length > 7)
            {
                float github = Version;
                if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github))
                {
                    GitHubVersion = github;
                }


                if (github > Version)
                {
                    var GUIDs = AssetDatabase.FindAssets("t:Script VSCode");
                    var path  = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar +
                                AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar);

                    if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No"))
                    {
                        // Always make sure the file is writable
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
                        fileInfo.IsReadOnly = false;

                        // Write update file
                        File.WriteAllText(path, fileContent);

                        // Force update on text file
                        AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate);
                    }
                }
            }
        }
示例#19
0
    private void DrawMainContentMenu()
    {
        void DrawItem(GameObject obj)
        {
            var texture = AssetPreview.GetAssetPreview(obj);

            var layoutStyle = new GUIStyle {
                margin = new RectOffset {
                    left = 5, right = 5
                }
            };

            EditorGUILayout.BeginVertical(layoutStyle, GUILayout.Width(c_itemSize));
            {
                var labelStyle = new GUIStyle();
                var c          = new Color(0.2f, 0.2f, 0.2f);
                var tex        = new Texture2D(2, 2);
                tex.SetPixels(new Color[] { c, c, c, c });
                tex.Apply();
                labelStyle.normal.background = tex;
                labelStyle.normal.textColor  = Color.white;
                labelStyle.fontStyle         = FontStyle.BoldAndItalic;
                labelStyle.alignment         = TextAnchor.MiddleCenter;
                EditorGUILayout.SelectableLabel(obj.name, labelStyle, GUILayout.Width(c_itemSize), GUILayout.Height(20));

                var buttonStyle = new GUIStyle();
                buttonStyle.normal.background = tex;
                if (GUILayout.Button(texture, buttonStyle, GUILayout.Width(c_itemSize), GUILayout.Height(c_itemSize)))
                {
                    InstantiateNewItem(obj);
                }
            }
            EditorGUILayout.EndVertical();
        }

        if (m_assetGuidsMap == null)
        {
            RefreshGuids();
        }

        m_prefabsScroll = EditorGUILayout.BeginScrollView(m_prefabsScroll);

        int maxCols = (int)Mathf.Round(MainManuWidth / (c_itemSize)) - 1;
        int idx     = 0;

        foreach (var guids in m_assetGuidsMap)
        {
            EditorGUILayout.Space(20);

            bool foldout = m_assetsFoldout[idx];
            foldout = EditorGUILayout.Foldout(
                foldout,
                guids.Key,
                true,
                new GUIStyle {
                fontStyle = FontStyle.Bold, fontSize = 20, contentOffset = new Vector2(0, -5)
            });

            m_assetsFoldout[idx++] = foldout;

            if (!foldout)
            {
                // separator line
                EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
                continue;
            }

            int i = 0;
            int j = 0;
            EditorGUILayout.BeginHorizontal();
            foreach (var guid in guids.Value)
            {
                var asset = AssetDatabase.LoadAssetAtPath <GameObject>(AssetDatabase.GUIDToAssetPath(guid));
                if (asset == null)
                {
                    continue;
                }

                DrawItem(asset);

                i++;
                if (i >= maxCols)
                {
                    i = 0;
                    j++;

                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.Space(5);
                    EditorGUILayout.BeginHorizontal();
                }
            }
            EditorGUILayout.EndHorizontal();

            // separator line
            EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
        }

        EditorGUILayout.EndScrollView();
    }
示例#20
0
        // showDefinedOnly: 只显示已定义
        // searchCount: 结果数量限制
        private void UpdateSearchResults()
        {
            var keyword                 = _searchKeyword;
            var sliceKeyword            = _searchSliceKeyword;
            var showDefinedOnly         = _showDefinedOnly;
            var showSelectionOnly       = _showSelectionOnly;
            var showStreamingAssetsOnly = _showStreamingAssetsOnly;
            var searchCount             = _data.searchMax;

            _searchResults.Clear();
            var selectionSet = new HashSet <string>();

            if (showSelectionOnly)
            {
                for (int i = 0, size = Selection.objects.Length; i < size; i++)
                {
                    var sel       = Selection.objects[i];
                    var assetPath = AssetDatabase.GetAssetPath(sel);
                    if (!string.IsNullOrEmpty(assetPath))
                    {
                        selectionSet.Add(assetPath);
                    }
                }
            }

            _data.ForEachAsset((bundleInfo, bundleSplit, bundleSlice, assetGuid) =>
            {
                if (_searchResults.Count < searchCount)
                {
                    if (!showStreamingAssetsOnly || bundleSlice.streamingAssets)
                    {
                        var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
                        if (!showSelectionOnly || selectionSet.Contains(assetPath))
                        {
                            if (string.IsNullOrEmpty(keyword) ||
                                assetPath.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                if (string.IsNullOrEmpty(sliceKeyword) ||
                                    bundleSlice.name.IndexOf(sliceKeyword, StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    var attrs = _data.GetAssetAttributes(assetGuid);
                                    if (attrs != null || !showDefinedOnly)
                                    {
                                        var result = new SearchResult()
                                        {
                                            bundleInfo  = bundleInfo,
                                            bundleSplit = bundleSplit,
                                            bundleSlice = bundleSlice,
                                            assetPath   = assetPath,
                                            assetGuid   = assetGuid,
                                        };

                                        _searchResults.Add(result);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
        static string GenerateFields(string indent, GenerationSettings settings)
        {
            var lines       = new List <string> (128);
            var uniquesList = new HashSet <string> ();
            var options     = settings.Options;

            var ignoredPaths = string.IsNullOrEmpty(settings.IgnoredPaths) ?
                               new string[0] : settings.IgnoredPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            // layers, layer masks
            if ((int)(options & Options.Layers) != 0)
            {
                foreach (var layerName in InternalEditorUtility.layers)
                {
                    lines.Add(string.Format(LayerName, indent, CleanupName(layerName), CleanupValue(layerName)));
                    lines.Add(string.Format(LayerMask, indent, CleanupName(layerName)));
                }
            }

            // tags
            if ((int)(options & Options.Tags) != 0)
            {
                foreach (var tagName in InternalEditorUtility.tags)
                {
                    lines.Add(string.Format(TagName, indent, CleanupName(tagName), CleanupValue(tagName)));
                }
            }

            // scenes
            if ((int)(options & Options.Scenes) != 0)
            {
                foreach (var scene in EditorBuildSettings.scenes)
                {
                    if (!ShouldBeIgnored(scene.path, ignoredPaths))
                    {
                        var sceneName = Path.GetFileNameWithoutExtension(scene.path);
                        lines.Add(string.Format(SceneName, indent, CleanupName(sceneName), CleanupValue(sceneName)));
                    }
                }
            }

            // animators
            if ((int)(options & Options.Animators) != 0)
            {
                foreach (var guid in AssetDatabase.FindAssets("t:animatorcontroller"))
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    if (!ShouldBeIgnored(assetPath, ignoredPaths))
                    {
                        var ac = AssetDatabase.LoadAssetAtPath <UnityEditor.Animations.AnimatorController> (assetPath);
                        for (int i = 0, iMax = ac.parameters.Length; i < iMax; i++)
                        {
                            var name = ac.parameters[i].name.Trim();
                            if (!uniquesList.Contains(name))
                            {
                                lines.Add(string.Format(AnimatorName, indent, CleanupName(name), CleanupValue(name)));
                                uniquesList.Add(name);
                            }
                        }
                    }
                }
                uniquesList.Clear();
            }

            // axes
            if ((int)(options & Options.Axes) != 0)
            {
                var inputManager = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0];
                var axes         = new SerializedObject(inputManager).FindProperty("m_Axes");
                for (int i = 0, iMax = axes.arraySize; i < iMax; i++)
                {
                    var axis = axes.GetArrayElementAtIndex(i).FindPropertyRelative("m_Name").stringValue;
                    if (!uniquesList.Contains(axis))
                    {
                        lines.Add(string.Format(AxisName, indent, CleanupName(axis), CleanupValue(axis)));
                        uniquesList.Add(axis);
                    }
                }
                uniquesList.Clear();
            }

            // shaders
            if ((int)(options & Options.Shaders) != 0)
            {
                foreach (var guid in AssetDatabase.FindAssets("t:shader"))
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(guid);
                    if (!ShouldBeIgnored(assetPath, ignoredPaths))
                    {
                        var shader = AssetDatabase.LoadAssetAtPath <Shader> (assetPath);
                        if (shader.name.IndexOf("Hidden", StringComparison.Ordinal) != 0)
                        {
                            for (int i = 0, iMax = ShaderUtil.GetPropertyCount(shader); i < iMax; i++)
                            {
                                if (!ShaderUtil.IsShaderPropertyHidden(shader, i))
                                {
                                    var name = ShaderUtil.GetPropertyName(shader, i);
                                    if (!uniquesList.Contains(name))
                                    {
                                        lines.Add(string.Format(ShaderName, indent, CleanupName(name), CleanupValue(name)));
                                        uniquesList.Add(name);
                                    }
                                }
                            }
                        }
                    }
                }
                uniquesList.Clear();
            }

            // sorting layers
            if ((int)(options & Options.SortingLayers) != 0)
            {
                foreach (var sortLayer in SortingLayer.layers)
                {
                    lines.Add(string.Format(SortingLayerName, indent, CleanupName(sortLayer.name), sortLayer.id));
                }
            }

            lines.Sort();
            return(string.Join("\n\n", lines.ToArray()));
        }
示例#22
0
        private static AssetAttributes DrawSingleAssetAttributes(BundleBuilderData data, string assetGuid,
                                                                 BundleBuilderWindow builder, bool batchMode, Action additionalOp)
        {
            var assetPath   = AssetDatabase.GUIDToAssetPath(assetGuid);
            var assetObject = AssetDatabase.LoadMainAssetAtPath(assetPath);
            var attrs       = data.GetAssetAttributes(assetGuid);
            var bNew        = attrs == null;

            if (bNew)
            {
                attrs = new AssetAttributes();
            }

            var nAssetPacker =
                (AssetPacker)EditorGUILayout.EnumPopup(attrs.packer, GUILayout.MaxWidth(110f));
            var nPriority = EditorGUILayout.IntSlider(attrs.priority, 0, data.priorityMax,
                                                      GUILayout.MaxWidth(220f));

            EditorGUILayout.ObjectField(assetObject, typeof(Object), false, GUILayout.MaxWidth(180f));
            EditorGUILayout.TextField(assetPath);
            var fileInfoWidth = 60f;

            EditorGUILayout.LabelField(GetFileSizeString(assetPath), _rightAlignStyle, GUILayout.MaxWidth(fileInfoWidth));
            additionalOp?.Invoke();

            if (batchMode)
            {
                if (nAssetPacker != attrs.packer)
                {
                    builder?.ApplyAllMarks(attributes => attributes.packer = nAssetPacker);
                }

                if (nPriority != attrs.priority)
                {
                    var deltaPriority = nPriority - attrs.priority;
                    builder?.ApplyAllMarks(attributes => attributes.priority = Math.Max(0,
                                                                                        Math.Min(data.priorityMax, attributes.priority + deltaPriority)));
                }
            }
            else
            {
                if (nAssetPacker != attrs.packer)
                {
                    attrs.packer = nAssetPacker;
                    data.MarkAsDirty();
                }

                if (nPriority != attrs.priority)
                {
                    attrs.priority = nPriority;
                    data.MarkAsDirty();
                }

                if (attrs.priority == 0 && attrs.packer == AssetPacker.Auto)
                {
                    data.RemoveAssetAttributes(assetGuid);
                }
                else if (bNew)
                {
                    if (attrs.priority != 0 || attrs.packer != AssetPacker.Auto)
                    {
                        var newAttributes = data.AddAssetAttributes(assetGuid);
                        newAttributes.priority = attrs.priority;
                        newAttributes.packer   = attrs.packer;
                    }
                }
            }

            return(attrs);
        }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
#if !(UNITY_5_0 || UNITY_5_1)
        EditorGUILayout.HelpBox(helpText, MessageType.Info);

        if (GUILayout.Button("Take snapshot"))
        {
#if (UNITY_5_2)
            var sceneName = Path.GetFileNameWithoutExtension(EditorApplication.currentScene);
            var scenePath = Path.GetDirectoryName(EditorApplication.currentScene);
            var assetPath = scenePath + "/" + sceneName;
            if (!AssetDatabase.IsValidFolder(assetPath))
            {
                var guid = AssetDatabase.CreateFolder(scenePath, sceneName);
                assetPath = AssetDatabase.GUIDToAssetPath(guid);
            }
#endif
            var directions = new Quaternion[] {
                Quaternion.LookRotation(Vector3.forward),
                Quaternion.LookRotation(Vector3.back),
                Quaternion.LookRotation(Vector3.left),
                Quaternion.LookRotation(Vector3.right),
                Quaternion.LookRotation(Vector3.up, Vector3.back),
                Quaternion.LookRotation(Vector3.down, Vector3.forward)
            };

            Camera tempCamera = null;
            foreach (SteamVR_Skybox target in targets)
            {
#if !(UNITY_5_2)
                var targetScene = target.gameObject.scene;
                var sceneName   = Path.GetFileNameWithoutExtension(targetScene.path);
                var scenePath   = Path.GetDirectoryName(targetScene.path);
                var assetPath   = scenePath + "/" + sceneName;
                if (!AssetDatabase.IsValidFolder(assetPath))
                {
                    var guid = AssetDatabase.CreateFolder(scenePath, sceneName);
                    assetPath = AssetDatabase.GUIDToAssetPath(guid);
                }
#endif
                var camera = target.GetComponent <Camera>();
                if (camera == null)
                {
                    if (tempCamera == null)
                    {
                        tempCamera = new GameObject().AddComponent <Camera>();
                    }
                    camera = tempCamera;
                }

                var targetTexture = camera.targetTexture;
                if (camera.targetTexture == null)
                {
                    targetTexture = new RenderTexture(1024, 1024, 24);
                    targetTexture.antiAliasing = 8;
                    camera.targetTexture       = targetTexture;
                }

                var oldPosition  = target.transform.localPosition;
                var oldRotation  = target.transform.localRotation;
                var baseRotation = target.transform.rotation;

                var t = camera.transform;
                t.position          = target.transform.position;
                camera.orthographic = false;
                camera.fieldOfView  = 90;

                for (int i = 0; i < directions.Length; i++)
                {
                    t.rotation = baseRotation * directions[i];
                    camera.Render();

                    // Copy to texture and save to disk.
                    RenderTexture.active = targetTexture;
                    var texture = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.ARGB32, false);
                    texture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
                    texture.Apply();
                    RenderTexture.active = null;

                    var assetName = string.Format(nameFormat, assetPath, target.name, i);
                    System.IO.File.WriteAllBytes(assetName, texture.EncodeToPNG());
                }

                if (camera != tempCamera)
                {
                    target.transform.localPosition = oldPosition;
                    target.transform.localRotation = oldRotation;
                }
            }

            if (tempCamera != null)
            {
                Object.DestroyImmediate(tempCamera.gameObject);
            }

            // Now that everything has be written out, reload the associated assets and assign them.
            AssetDatabase.Refresh();
            foreach (SteamVR_Skybox target in targets)
            {
#if !(UNITY_5_2)
                var targetScene = target.gameObject.scene;
                var sceneName   = Path.GetFileNameWithoutExtension(targetScene.path);
                var scenePath   = Path.GetDirectoryName(targetScene.path);
                var assetPath   = scenePath + "/" + sceneName;
#endif
                for (int i = 0; i < directions.Length; i++)
                {
                    var assetName = string.Format(nameFormat, assetPath, target.name, i);
                    var importer  = AssetImporter.GetAtPath(assetName) as TextureImporter;
                    importer.textureFormat = TextureImporterFormat.RGB24;
                    importer.wrapMode      = TextureWrapMode.Clamp;
                    importer.mipmapEnabled = false;
                    importer.SaveAndReimport();

                    var texture = AssetDatabase.LoadAssetAtPath <Texture>(assetName);
                    target.SetTextureByIndex(i, texture);
                }
            }
        }
        else if (GUILayout.Button("Take stereo snapshot"))
        {
            const int width      = 4096;
            const int height     = width / 2;
            const int halfHeight = height / 2;

            var textures = new Texture2D[] {
                new Texture2D(width, height, TextureFormat.ARGB32, false),
                new Texture2D(width, height, TextureFormat.ARGB32, false)
            };

            var timer = new System.Diagnostics.Stopwatch();

            Camera tempCamera = null;
            foreach (SteamVR_Skybox target in targets)
            {
                timer.Start();
#if !(UNITY_5_2)
                var targetScene = target.gameObject.scene;
                var sceneName   = Path.GetFileNameWithoutExtension(targetScene.path);
                var scenePath   = Path.GetDirectoryName(targetScene.path);
                var assetPath   = scenePath + "/" + sceneName;
                if (!AssetDatabase.IsValidFolder(assetPath))
                {
                    var guid = AssetDatabase.CreateFolder(scenePath, sceneName);
                    assetPath = AssetDatabase.GUIDToAssetPath(guid);
                }
#endif
                var camera = target.GetComponent <Camera>();
                if (camera == null)
                {
                    if (tempCamera == null)
                    {
                        tempCamera = new GameObject().AddComponent <Camera>();
                    }
                    camera = tempCamera;
                }

                var fx = camera.gameObject.AddComponent <SteamVR_SphericalProjection>();

                var oldTargetTexture = camera.targetTexture;
                var oldOrthographic  = camera.orthographic;
                var oldFieldOfView   = camera.fieldOfView;
                var oldAspect        = camera.aspect;

                var oldPosition  = target.transform.localPosition;
                var oldRotation  = target.transform.localRotation;
                var basePosition = target.transform.position;
                var baseRotation = target.transform.rotation;

                var transform = camera.transform;

                int   cellSize = int.Parse(target.StereoCellSize.ToString().Substring(1));
                float ipd      = target.StereoIpdMm / 1000.0f;
                int   vTotal   = halfHeight / cellSize;
                float dv       = 90.0f / vTotal;           // vertical degrees per segment
                float dvHalf   = dv / 2.0f;

                var targetTexture = new RenderTexture(cellSize, cellSize, 24);
                targetTexture.wrapMode     = TextureWrapMode.Clamp;
                targetTexture.antiAliasing = 8;

                camera.fieldOfView   = dv;
                camera.orthographic  = false;
                camera.targetTexture = targetTexture;

                // Render sections of a sphere using a rectilinear projection
                // and resample using a sphereical projection into a single panorama
                // texture per eye.  We break into sections in order to keep the eye
                // separation similar around the sphere.  Rendering alternates between
                // top and bottom sections, sweeping horizontally around the sphere,
                // alternating left and right eyes.
                for (int v = 0; v < vTotal; v++)
                {
                    var pitch  = 90.0f - (v * dv) - dvHalf;
                    var uTotal = width / targetTexture.width;
                    var du     = 360.0f / uTotal; // horizontal degrees per segment
                    var duHalf = du / 2.0f;

                    var vTarget = v * halfHeight / vTotal;

                    for (int i = 0; i < 2; i++)                     // top, bottom
                    {
                        if (i == 1)
                        {
                            pitch   = -pitch;
                            vTarget = height - vTarget - cellSize;
                        }

                        for (int u = 0; u < uTotal; u++)
                        {
                            var yaw = -180.0f + (u * du) + duHalf;

                            var uTarget = u * width / uTotal;

                            var xOffset = -ipd / 2 * Mathf.Cos(pitch * Mathf.Deg2Rad);

                            for (int j = 0; j < 2; j++)                             // left, right
                            {
                                var texture = textures[j];

                                if (j == 1)
                                {
                                    xOffset = -xOffset;
                                }

                                var offset = baseRotation * Quaternion.Euler(0, yaw, 0) * new Vector3(xOffset, 0, 0);
                                transform.position = basePosition + offset;

                                var direction = Quaternion.Euler(pitch, yaw, 0.0f);
                                transform.rotation = baseRotation * direction;

                                // vector pointing to center of this section
                                var N = direction * Vector3.forward;

                                // horizontal span of this section in degrees
                                var phi0 = yaw - (du / 2);
                                var phi1 = phi0 + du;

                                // vertical span of this section in degrees
                                var theta0 = pitch + (dv / 2);
                                var theta1 = theta0 - dv;

                                var midPhi    = (phi0 + phi1) / 2;
                                var baseTheta = Mathf.Abs(theta0) < Mathf.Abs(theta1) ? theta0 : theta1;

                                // vectors pointing to corners of image closes to the equator
                                var V00 = Quaternion.Euler(baseTheta, phi0, 0.0f) * Vector3.forward;
                                var V01 = Quaternion.Euler(baseTheta, phi1, 0.0f) * Vector3.forward;

                                // vectors pointing to top and bottom midsection of image
                                var V0M = Quaternion.Euler(theta0, midPhi, 0.0f) * Vector3.forward;
                                var V1M = Quaternion.Euler(theta1, midPhi, 0.0f) * Vector3.forward;

                                // intersection points for each of the above
                                var P00 = V00 / Vector3.Dot(V00, N);
                                var P01 = V01 / Vector3.Dot(V01, N);
                                var P0M = V0M / Vector3.Dot(V0M, N);
                                var P1M = V1M / Vector3.Dot(V1M, N);

                                // calculate basis vectors for plane
                                var P00_P01 = P01 - P00;
                                var P0M_P1M = P1M - P0M;

                                var uMag = P00_P01.magnitude;
                                var vMag = P0M_P1M.magnitude;

                                var uScale = 1.0f / uMag;
                                var vScale = 1.0f / vMag;

                                var uAxis = P00_P01 * uScale;
                                var vAxis = P0M_P1M * vScale;

                                // update material constant buffer
                                fx.Set(N, phi0, phi1, theta0, theta1,
                                       uAxis, P00, uScale,
                                       vAxis, P0M, vScale);

                                camera.aspect = uMag / vMag;
                                camera.Render();

                                RenderTexture.active = targetTexture;
                                texture.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), uTarget, vTarget);
                                RenderTexture.active = null;
                            }
                        }
                    }
                }

                // Save textures to disk.
                for (int i = 0; i < 2; i++)
                {
                    var texture = textures[i];

                    texture.Apply();
                    var assetName = string.Format(nameFormat, assetPath, target.name, i);
                    File.WriteAllBytes(assetName, texture.EncodeToPNG());
                }

                // Cleanup.
                if (camera != tempCamera)
                {
                    camera.targetTexture = oldTargetTexture;
                    camera.orthographic  = oldOrthographic;
                    camera.fieldOfView   = oldFieldOfView;
                    camera.aspect        = oldAspect;

                    target.transform.localPosition = oldPosition;
                    target.transform.localRotation = oldRotation;
                }
                else
                {
                    tempCamera.targetTexture = null;
                }

                DestroyImmediate(targetTexture);
                DestroyImmediate(fx);

                timer.Stop();
                Debug.Log(string.Format("Screenshot took {0} seconds.", timer.Elapsed));
            }

            if (tempCamera != null)
            {
                DestroyImmediate(tempCamera.gameObject);
            }

            DestroyImmediate(textures[0]);
            DestroyImmediate(textures[1]);

            // Now that everything has be written out, reload the associated assets and assign them.
            AssetDatabase.Refresh();
            foreach (SteamVR_Skybox target in targets)
            {
#if !(UNITY_5_2)
                var targetScene = target.gameObject.scene;
                var sceneName   = Path.GetFileNameWithoutExtension(targetScene.path);
                var scenePath   = Path.GetDirectoryName(targetScene.path);
                var assetPath   = scenePath + "/" + sceneName;
#endif
                for (int i = 0; i < 2; i++)
                {
                    var assetName = string.Format(nameFormat, assetPath, target.name, i);
                    var importer  = AssetImporter.GetAtPath(assetName) as TextureImporter;
                    importer.mipmapEnabled = false;
                    importer.wrapMode      = TextureWrapMode.Repeat;
                    importer.SetPlatformTextureSettings("Standalone", width, TextureImporterFormat.RGB24);
                    importer.SaveAndReimport();

                    var texture = AssetDatabase.LoadAssetAtPath <Texture2D>(assetName);
                    target.SetTextureByIndex(i, texture);
                }
            }
        }
#endif
    }
示例#24
0
        public override BuildResult Run(BuildContext context)
        {
            var manifest               = context.BuildManifest;
            var rootAssembly           = context.GetComponentOrDefault <DotsRuntimeRootAssembly>();
            var buildScenes            = context.GetComponentOrDefault <SceneList>();
            var targetName             = rootAssembly.MakeBeeTargetName(context.BuildConfigurationName);
            var scenePaths             = buildScenes.GetScenePathsForBuild();
            var buildConfigurationGuid = context.BuildConfigurationAssetGUID;
            var dataDirectory          = WorldExport.GetOrCreateDataDirectoryFrom(rootAssembly.StagingDirectory.Combine(targetName));
            var logsDirectory          = WorldExport.GetOrCreateLogDirectoryFrom(targetName);

            var sceneGuids = scenePaths.SelectMany(scenePath =>
            {
                var guids = EditorEntityScenes.GetSubScenes(AssetDatabaseCompatibility.PathToGUID(scenePath)).ToList();
                guids.Add(AssetDatabaseCompatibility.PathToGUID(scenePath));
                return(guids);
            }).Distinct().ToList();

            //Save all unsaved scenes of the project first
            foreach (var guid in sceneGuids)
            {
                string scenePath = AssetDatabase.GUIDToAssetPath(guid.ToString());
                var    scene     = SceneManager.GetSceneByPath(scenePath);
                EditorSceneManager.SaveScene(scene);
            }

            var requiresRefresh       = false;
            var sceneBuildConfigGuids = new NativeArray <GUID>(sceneGuids.Count, Allocator.TempJob);

            for (int i = 0; i != sceneBuildConfigGuids.Length; i++)
            {
                sceneBuildConfigGuids[i] = SceneWithBuildConfigurationGUIDs.EnsureExistsFor(sceneGuids[i], new Hash128(buildConfigurationGuid), false, out var thisRequiresRefresh);
                requiresRefresh         |= thisRequiresRefresh;
            }
            if (requiresRefresh)
            {
                AssetDatabase.Refresh();
            }

            var artifactHashes = new NativeArray <UnityEngine.Hash128>(sceneGuids.Count, Allocator.TempJob);

            AssetDatabaseCompatibility.ProduceArtifactsRefreshIfNecessary(sceneBuildConfigGuids, typeof(SubSceneImporter), artifactHashes);

            bool succeeded = true;

            for (int i = 0; i != sceneBuildConfigGuids.Length; i++)
            {
                var sceneGuid    = sceneGuids[i];
                var artifactHash = artifactHashes[i];

                AssetDatabaseCompatibility.GetArtifactPaths(artifactHash, out var artifactPaths);

                List <FileInfo> exportedFiles     = new List <FileInfo>();
                bool            foundEntityHeader = false;
                foreach (var artifactPath in artifactPaths)
                {
                    var ext = Path.GetExtension(artifactPath).ToLower().Replace(".", "");
                    if (ext == EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesHeader))
                    {
                        foundEntityHeader = true;
                        var destinationFile = dataDirectory.FullName + Path.DirectorySeparatorChar + EntityScenesPaths.RelativePathFolderFor(sceneGuid, EntityScenesPaths.PathType.EntitiesHeader, -1);
                        new NPath(artifactPath).MakeAbsolute().Copy(new NPath(destinationFile).MakeAbsolute().EnsureParentDirectoryExists());
                        exportedFiles.Add(new FileInfo(destinationFile));
                    }
                    else if (ext == EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesBinary))
                    {
                        var destinationFile = dataDirectory.FullName + Path.DirectorySeparatorChar + EntityScenesPaths.RelativePathFolderFor(sceneGuid, EntityScenesPaths.PathType.EntitiesBinary, EntityScenesPaths.GetSectionIndexFromPath(artifactPath));
                        new NPath(artifactPath).MakeAbsolute().Copy(new NPath(destinationFile).MakeAbsolute().EnsureParentDirectoryExists());
                        exportedFiles.Add(new FileInfo(destinationFile));
                    }
                    else if (ext == EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesConversionLog))
                    {
                        var destinationFile = logsDirectory.FullName + Path.DirectorySeparatorChar + $"{sceneGuid}.{EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesConversionLog)}";
                        new NPath(artifactPath).MakeAbsolute().Copy(new NPath(destinationFile).MakeAbsolute().EnsureParentDirectoryExists());
                        var result = PrintConversionLogToUnityConsole(artifactPath);
                        if (result.HasError || result.HasException)
                        {
                            UnityEngine.Debug.LogError("Failed to export scene: " + Path.GetFileName(AssetDatabase.GUIDToAssetPath(sceneGuid.ToString())));
                            succeeded = false;
                        }
                    }
                    else if (new Hash128(ext).IsValid) //Asset files are exported as {artifactHash}.{assetguid}
                    {
                        var destinationFile = dataDirectory.FullName + Path.DirectorySeparatorChar + ext;
                        new NPath(artifactPath).MakeAbsolute().Copy(new NPath(destinationFile).MakeAbsolute().EnsureParentDirectoryExists());
                        exportedFiles.Add(new FileInfo(destinationFile));
                    }
                }

                if (!foundEntityHeader)
                {
                    Debug.LogError($"Failed to build EntityScene for '{AssetDatabaseCompatibility.GuidToPath(sceneGuid)}'.");
                    succeeded = false;
                }

                //UpdateManifest
                manifest.Add(new Guid(sceneGuid.ToString()), AssetDatabase.GUIDToAssetPath(sceneGuid.ToString()), exportedFiles);
            }

            var catalogPath = Path.Combine(dataDirectory.ToString(), SceneSystem.k_SceneInfoFileName);

            WriteCatalogFile(catalogPath, buildScenes);
            manifest.AddAdditionalFilesToDeploy(new FileInfo(catalogPath.ToString()));

            sceneBuildConfigGuids.Dispose();
            artifactHashes.Dispose();

            if (succeeded)
            {
                return(context.Success());
            }
            return(context.Failure($"Failed to export scenes"));
        }
示例#25
0
    static void DoCreateSpriteObject()
    {
        tk2dSpriteCollectionData sprColl = null;

        if (sprColl == null)
        {
            // try to inherit from other Sprites in scene
            tk2dSprite spr = GameObject.FindObjectOfType(typeof(tk2dSprite)) as tk2dSprite;
            if (spr)
            {
                sprColl = spr.collection;
            }
        }

        if (sprColl == null)
        {
            tk2dSpriteCollectionIndex[] spriteCollections = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
            foreach (var v in spriteCollections)
            {
                GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
                var        sc   = scgo.GetComponent <tk2dSpriteCollectionData>();
                if (sc != null && sc.spriteDefinitions != null && sc.spriteDefinitions.Length > 0)
                {
                    sprColl = sc;
                    break;
                }
            }

            if (sprColl == null)
            {
                EditorUtility.DisplayDialog("Create Sprite", "Unable to create sprite as no SpriteCollections have been found.", "Ok");
                return;
            }
        }

        tk2dSpriteAnimation[] anims = tk2dEditorUtility.GetOrCreateIndex().GetSpriteAnimations();
        tk2dSpriteAnimation   anim  = null;

        foreach (var a in anims)
        {
            if (a != null && a.clips != null && a.clips.Length > 0)
            {
                anim = a;
                break;
            }
        }

        if (anim == null)
        {
            EditorUtility.DisplayDialog("Create Animated Sprite", "Unable to create animated sprite as no SpriteAnimations have been found.", "Ok");
            return;
        }

        if (anim.clips[0].frames.Length == 0 || anim.clips[0].frames[0].spriteCollection == null)
        {
            EditorUtility.DisplayDialog("Create Animated Sprite", "Invalid SpriteAnimation has been found.", "Ok");
            return;
        }

        GameObject         go     = tk2dEditorUtility.CreateGameObjectInScene("AnimatedSprite");
        tk2dAnimatedSprite sprite = go.AddComponent <tk2dAnimatedSprite>();

        sprite.collection = anim.clips[0].frames[0].spriteCollection;
        sprite.Build();

        sprite.spriteId = anim.clips[0].frames[0].spriteId;
        sprite.anim     = anim;
    }
示例#26
0
    public override void OnInspectorGUI()
    {
        AddScriptNameField(m_Sel);

        int  nClickIndex  = -1;
        int  nClickButton = 0;
        Rect rect;
        int  nLeftWidth    = 35;
        int  nAddHeight    = 30;
        int  nDelWidth     = 35;
        int  nLineHeight   = 18;
        int  nSpriteHeight = nLeftWidth;
        List <NcSpriteFactory.NcSpriteNode> spriteList = m_Sel.m_SpriteList;

        m_FxmPopupManager = GetFxmPopupManager();

        // --------------------------------------------------------------
        bool bClickButton = false;

        EditorGUI.BeginChangeCheck();
        {
            m_UndoManager.CheckUndo();
            // --------------------------------------------------------------
            EditorGUILayout.Space();
            m_Sel.m_SpriteType = (NcSpriteFactory.SPRITE_TYPE)EditorGUILayout.EnumPopup(GetHelpContent("m_SpriteType"), m_Sel.m_SpriteType);

            // --------------------------------------------------------------
            if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation && m_Sel.gameObject.GetComponent("NcSpriteAnimation") == null)
            {
                rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight));
                {
                    if (FXMakerLayout.GUIButton(rect, GetHelpContent("Add NcSpriteAnimation Component"), true))
                    {
                        m_Sel.gameObject.AddComponent("NcSpriteAnimation");
                    }
                    GUILayout.Label("");
                }
                EditorGUILayout.EndHorizontal();
            }
            // --------------------------------------------------------------
            if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteTexture && m_Sel.gameObject.GetComponent("NcSpriteTexture") == null)
            {
                rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight));
                {
                    if (FXMakerLayout.GUIButton(rect, GetHelpContent("Add NcSpriteTexture Component"), true))
                    {
                        m_Sel.gameObject.AddComponent("NcSpriteTexture");
                    }
                    GUILayout.Label("");
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.Space();

            // --------------------------------------------------------------
            int nSelIndex = EditorGUILayout.IntSlider(GetHelpContent("m_nCurrentIndex"), m_Sel.m_nCurrentIndex, 0, (spriteList == null ? 0 : spriteList.Count));
            if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteTexture)
            {
                m_Sel.m_fUvScale = EditorGUILayout.FloatField(GetHelpContent("m_fUvScale"), m_Sel.m_fUvScale);
            }
            m_Sel.m_nMaxAtlasTextureSize = EditorGUILayout.IntPopup("nMaxAtlasTextureSize", m_Sel.m_nMaxAtlasTextureSize, NgEnum.m_TextureSizeStrings, NgEnum.m_TextureSizeIntters);
//          m_Sel.m_AtlasMaterial		= (Material)EditorGUILayout.ObjectField(GetHelpContent("m_AtlasMaterial")	, m_Sel.m_AtlasMaterial, typeof(Material), false);

            if (m_Sel.m_nCurrentIndex != nSelIndex)
            {
                m_Sel.m_nCurrentIndex = nSelIndex;
                m_Sel.SetSprite(nSelIndex, false);
            }

            // check

            // Add Button ------------------------------------------------------
            EditorGUILayout.Space();
            rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(nAddHeight * 2));
            {
                Rect lineRect = FXMakerLayout.GetInnerVerticalRect(rect, 2, 0, 1);
                if (GUI.Button(FXMakerLayout.GetInnerHorizontalRect(lineRect, 3, 0, 1), GetHelpContent("Add Sprite")))
                {
                    bClickButton = true;
                    m_Sel.AddSpriteNode();
                }
                if (GUI.Button(FXMakerLayout.GetInnerHorizontalRect(lineRect, 3, 1, 1), GetHelpContent("Build Sprite")))
                {
                    bClickButton = true;
                    BuildSpriteAtlas(m_Sel.renderer.sharedMaterial);
                }
                if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(lineRect, 3, 2, 1), GetHelpContent("Clear All"), (0 < m_Sel.GetSpriteNodeCount())))
                {
                    bClickButton = true;
                    if (m_FxmPopupManager != null)
                    {
                        m_FxmPopupManager.CloseNcPrefabPopup();
                    }
                    m_Sel.ClearAllSpriteNode();
                }
                lineRect = FXMakerLayout.GetInnerVerticalRect(rect, 2, 1, 1);
                if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(lineRect, 3, 0, 1), GetHelpContent("Sequence"), (0 < m_Sel.GetSpriteNodeCount())))
                {
                    m_Sel.m_bSequenceMode = true;
                    bClickButton          = true;
                    m_Sel.SetSprite(0, false);
                }
                if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(lineRect, 3, 1, 1), GetHelpContent("NewMaterial"), true))
                {
                    Material newMat  = new Material(m_Sel.renderer.sharedMaterial);
                    string   matPath = AssetDatabase.GetAssetPath(m_Sel.renderer.sharedMaterial);
                    NgMaterial.SaveMaterial(newMat, NgFile.TrimFilenameExt(matPath), m_Sel.name);
                    m_Sel.renderer.sharedMaterial = newMat;
//                  m_Sel.renderer.sharedMaterial = (Material)AssetDatabase.LoadAssetAtPath(savePath, typeof(Material));
                }

                GUILayout.Label("");
            }
            EditorGUILayout.EndHorizontal();

            // Select ShotType -------------------------------------------------
//			m_Sel.m_ShowType		= (NcSpriteFactory.SHOW_TYPE)EditorGUILayout.EnumPopup		(GetHelpContent("m_ShowType")	, m_Sel.m_ShowType);
            // --------------------------------------------------------------
            EditorGUILayout.Space();
            rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(nLineHeight));
            {
                m_Sel.m_ShowType = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 5, 0, 1), m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.NONE, GetHelpContent("NONE"), true) ? NcSpriteFactory.SHOW_TYPE.NONE                : m_Sel.m_ShowType;
                m_Sel.m_ShowType = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 5, 1, 1), m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.ALL, GetHelpContent("ALL"), true) ? NcSpriteFactory.SHOW_TYPE.ALL         : m_Sel.m_ShowType;
                if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation)
                {
                    m_Sel.m_ShowType = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 5, 2, 1), m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.SPRITE, GetHelpContent("SPRITE"), true) ? NcSpriteFactory.SHOW_TYPE.SPRITE              : m_Sel.m_ShowType;
                    m_Sel.m_ShowType = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 5, 3, 1), m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.ANIMATION, GetHelpContent("ANIMATION"), true) ? NcSpriteFactory.SHOW_TYPE.ANIMATION   : m_Sel.m_ShowType;
                }
                m_Sel.m_ShowType = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 5, 4, 1), m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.EFFECT, GetHelpContent("EFFECT"), true) ? NcSpriteFactory.SHOW_TYPE.EFFECT              : m_Sel.m_ShowType;
                GUILayout.Label("");
            }
            EditorGUILayout.EndHorizontal();

            // Show Option -------------------------------------------------
            EditorGUILayout.Space();
            rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(nLineHeight));
            {
                m_Sel.m_bShowEffect = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 3, 0, 1), m_Sel.m_bShowEffect, GetHelpContent("m_bShowEffect"), true);
                if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation)
                {
                    m_Sel.m_bTestMode     = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 3, 1, 1), m_Sel.m_bTestMode, GetHelpContent("m_bTestMode"), true);
                    m_Sel.m_bSequenceMode = FXMakerLayout.GUIToggle(FXMakerLayout.GetInnerHorizontalRect(rect, 3, 2, 1), m_Sel.m_bSequenceMode, GetHelpContent("m_bSequenceMode"), true);
                }
                GUILayout.Label("");
            }
            EditorGUILayout.EndHorizontal();

            // Node List ------------------------------------------------------
            for (int n = 0; n < (spriteList != null ? spriteList.Count : 0); n++)
            {
                EditorGUILayout.Space();

                EditorGUI.BeginChangeCheck();
                // Load Texture ---------------------------------------------------------
                Texture2D selTexture = null;
                if (spriteList[n].m_TextureGUID != "")
                {
                    selTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(spriteList[n].m_TextureGUID), typeof(Texture2D));
                }

                // Enabled --------------------------------------------------------------
                rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(nLineHeight));
                {
                    Rect subRect;
                    // enable
                    spriteList[n].m_bIncludedAtlas = GUILayout.Toggle(spriteList[n].m_bIncludedAtlas, "Idx", GUILayout.Width(nLeftWidth));
                    // change index
                    subRect       = rect;
                    subRect.x    += nLeftWidth;
                    subRect.width = nLineHeight * 2;
                    int newPos = EditorGUI.IntPopup(subRect, n, NgConvert.GetIntStrings(0, spriteList.Count), NgConvert.GetIntegers(0, spriteList.Count));
                    if (newPos != n)
                    {
                        NcSpriteFactory.NcSpriteNode node = spriteList[n];
                        m_Sel.m_SpriteList.Remove(node);
                        m_Sel.m_SpriteList.Insert(newPos, node);
                        return;
                    }

                    // name
                    subRect        = rect;
                    subRect.x     += nLeftWidth + nLineHeight * 2;
                    subRect.width -= nLeftWidth + nLineHeight * 2;
                    spriteList[n].m_TextureName = selTexture == null ? "" : selTexture.name;
                    GUI.Label(subRect, (selTexture == null ? "" : "(" + spriteList[n].m_nFrameCount + ") " + selTexture.name));
                    GUI.Box(subRect, "");
                    GUI.Box(rect, "");

                    // delete
                    if (GUI.Button(new Rect(subRect.x + subRect.width - nDelWidth, subRect.y, nDelWidth, subRect.height), GetHelpContent("Del")))
                    {
                        bClickButton = true;
                        if (m_FxmPopupManager != null)
                        {
                            m_FxmPopupManager.CloseNcPrefabPopup();
                        }
                        m_Sel.DeleteSpriteNode(n);
                        return;
                    }
                }
                EditorGUILayout.EndHorizontal();

                // MaxAlpha -------------------------------------------------------------
                spriteList[n].m_fMaxTextureAlpha = EditorGUILayout.FloatField(GetHelpContent("m_fMaxTextureAlpha"), spriteList[n].m_fMaxTextureAlpha);

                // Texture --------------------------------------------------------------
                rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(nSpriteHeight));
                {
                    GUILayout.Label("", GUILayout.Width(nLeftWidth));

                    Rect subRect = rect;
                    subRect.width = nLeftWidth;
                    FXMakerLayout.GetOffsetRect(rect, 0, 5, 0, -5);
                    EditorGUI.BeginChangeCheck();
                    selTexture = (Texture2D)EditorGUI.ObjectField(subRect, GetHelpContent(""), selTexture, typeof(Texture2D), false);
                    if (EditorGUI.EndChangeCheck())
                    {
                        if (selTexture != null)
                        {
                            spriteList[n].m_TextureGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(selTexture));
                        }
                    }
                    if (selTexture != null)
                    {
                        if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation)
                        {
                            spriteList[n].m_nFrameCount = selTexture.width / selTexture.height;
                            spriteList[n].m_nFrameSize  = selTexture.height;
                            m_Sel.m_nFrameSize          = spriteList[n].m_nFrameSize;
                        }
                        else
                        {
                            spriteList[n].m_nFrameCount = 1;
                            spriteList[n].m_nFrameSize  = 1;
                            m_Sel.m_nFrameSize          = 1;
                        }
                    }

                    // draw texture
                    subRect = FXMakerLayout.GetOffsetRect(rect, nLeftWidth + 4, 0, 0, -4);
                    if (selTexture != null)
                    {
                        GUI.DrawTexture(FXMakerLayout.GetOffsetRect(subRect, 0, 0, -nDelWidth, 0), selTexture, ScaleMode.ScaleToFit, true, selTexture.width / selTexture.height);
                    }

                    // delete
                    if (GUI.Button(new Rect(subRect.x + subRect.width - nDelWidth, subRect.y, nDelWidth, subRect.height), GetHelpContent("Rmv")))
                    {
                        spriteList[n].m_TextureGUID = "";
                        spriteList[n].m_nFrameCount = 0;
                        spriteList[n].m_nFrameSize  = 0;
                    }
                    GUI.Box(rect, "");
                }
                EditorGUILayout.EndHorizontal();

                // Change selIndex
                Event e = Event.current;
                if (e.type == EventType.MouseDown)
                {
                    if (rect.Contains(e.mousePosition))
                    {
                        nClickIndex  = n;
                        nClickButton = e.button;
                    }
                }

                // SpriteNode ----------------------------------------------------------
                if (bClickButton == false)
                {
                    if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation && m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.ALL || m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.SPRITE)
                    {
                        spriteList[n].m_bLoop = EditorGUILayout.Toggle(GetHelpContent("m_bLoop"), spriteList[n].m_bLoop);
                        spriteList[n].m_fTime = EditorGUILayout.Slider(GetHelpContent("m_fTime"), spriteList[n].m_nFrameCount / spriteList[n].m_fFps, 0, 5, null);
                        spriteList[n].m_fFps  = EditorGUILayout.Slider(GetHelpContent("m_fFps"), spriteList[n].m_nFrameCount / spriteList[n].m_fTime, 50, 1, null);
                    }

                    if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation && m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.ALL || m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.ANIMATION)
                    {
                        spriteList[n].m_nNextSpriteIndex = EditorGUILayout.Popup("m_nNextSpriteIndex", spriteList[n].m_nNextSpriteIndex + 1, GetSpriteNodeNames()) - 1;
                        spriteList[n].m_nTestMode        = EditorGUILayout.Popup("m_nTestMode", spriteList[n].m_nTestMode, NgConvert.ContentsToStrings(FxmTestControls.GetHcEffectControls_Trans(FxmTestControls.AXIS.Z)), GUILayout.MaxWidth(Screen.width));
                        spriteList[n].m_fTestSpeed       = EditorGUILayout.FloatField("m_fTestSpeed", spriteList[n].m_fTestSpeed);

                        SetMinValue(ref spriteList[n].m_fTestSpeed, 0.01f);
                        SetMinValue(ref spriteList[n].m_fTestSpeed, 0.01f);
                    }

                    if (m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.ALL || m_Sel.m_ShowType == NcSpriteFactory.SHOW_TYPE.EFFECT)
                    {
                        // char effect -------------------------------------------------------------
                        spriteList[n].m_EffectPrefab = (GameObject)EditorGUILayout.ObjectField(GetHelpContent("m_EffectPrefab"), spriteList[n].m_EffectPrefab, typeof(GameObject), false, null);

                        rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight * 0.7f));
                        {
                            if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(rect, 2, 0, 1), GetHelpContent("SelEffect"), (m_FxmPopupManager != null)))
                            {
                                m_FxmPopupManager.ShowSelectPrefabPopup(m_Sel, n, 0, true);
                            }
                            if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(rect, 2, 1, 1), GetHelpContent("ClearEffect"), (spriteList[n].m_EffectPrefab != null)))
                            {
                                bClickButton = true;
                                spriteList[n].m_EffectPrefab = null;
                            }
                            GUILayout.Label("");
                        }
                        EditorGUILayout.EndHorizontal();

                        if (spriteList[n].m_EffectPrefab != null)
                        {
                            if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation)
                            {
                                spriteList[n].m_nEffectFrame     = EditorGUILayout.IntSlider(GetHelpContent("m_nEffectFrame"), spriteList[n].m_nEffectFrame, 0, spriteList[n].m_nFrameCount, null);
                                spriteList[n].m_bEffectOnlyFirst = EditorGUILayout.Toggle(GetHelpContent("m_bEffectOnlyFirst"), spriteList[n].m_bEffectOnlyFirst);
                            }
                            spriteList[n].m_fEffectSpeed = EditorGUILayout.FloatField("m_fEffectSpeed", spriteList[n].m_fEffectSpeed);
                            spriteList[n].m_fEffectScale = EditorGUILayout.FloatField("m_fEffectScale", spriteList[n].m_fEffectScale);
                            spriteList[n].m_EffectPos    = EditorGUILayout.Vector3Field("m_EffectPos", spriteList[n].m_EffectPos, null);
                            spriteList[n].m_EffectRot    = EditorGUILayout.Vector3Field("m_EffectRot", spriteList[n].m_EffectRot, null);

                            SetMinValue(ref spriteList[n].m_fEffectScale, 0.001f);
                        }

                        EditorGUILayout.Space();

                        // char sound -------------------------------------------------------------
                        spriteList[n].m_AudioClip = (AudioClip)EditorGUILayout.ObjectField(GetHelpContent("m_AudioClip"), spriteList[n].m_AudioClip, typeof(AudioClip), false, null);

                        rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight * 0.7f));
                        {
//                          if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(rect, 2, 0, 1), GetHelpContent("SelAudio"), (m_FxmPopupManager != null)))
//								m_FxmPopupManager.ShowSelectAudioClipPopup(m_Sel);
                            if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(rect, 2, 1, 1), GetHelpContent("ClearAudio"), (spriteList[n].m_AudioClip != null)))
                            {
                                bClickButton = true;
                                spriteList[n].m_AudioClip = null;
                            }
                            GUILayout.Label("");
                        }
                        EditorGUILayout.EndHorizontal();

                        if (spriteList[n].m_AudioClip != null)
                        {
                            if (m_Sel.m_SpriteType == NcSpriteFactory.SPRITE_TYPE.NcSpriteAnimation)
                            {
                                spriteList[n].m_nSoundFrame     = EditorGUILayout.IntSlider(GetHelpContent("m_nSoundFrame"), spriteList[n].m_nSoundFrame, 0, spriteList[n].m_nFrameCount, null);
                                spriteList[n].m_bSoundOnlyFirst = EditorGUILayout.Toggle(GetHelpContent("m_bSoundOnlyFirst"), spriteList[n].m_bSoundOnlyFirst);
                            }
                            spriteList[n].m_bSoundLoop   = EditorGUILayout.Toggle(GetHelpContent("m_bSoundLoop"), spriteList[n].m_bSoundLoop);
                            spriteList[n].m_fSoundVolume = EditorGUILayout.Slider(GetHelpContent("m_fSoundVolume"), spriteList[n].m_fSoundVolume, 0, 1.0f, null);
                            spriteList[n].m_fSoundPitch  = EditorGUILayout.Slider(GetHelpContent("m_fSoundPitch"), spriteList[n].m_fSoundPitch, -3, 3.0f, null);
                        }
                    }
                }

                if (EditorGUI.EndChangeCheck())
                {
                    nClickIndex = n;
                }

                selTexture = null;
            }

            // Select Node ----------------------------------------------------
            if (0 <= nClickIndex)
            {
                m_Sel.SetSprite(nClickIndex, false);
                if (m_Sel.m_bTestMode && 0 <= spriteList[nClickIndex].m_nTestMode && GetFXMakerMain())
                {
                    GetFXMakerMain().GetFXMakerControls().SetTransIndex(spriteList[nClickIndex].m_nTestMode, (4 <= spriteList[nClickIndex].m_nTestMode ? 1.8f : 1.0f), spriteList[nClickIndex].m_fTestSpeed);
                }
                // Rotate
                if (nClickButton == 1)
                {
                    m_Sel.transform.Rotate(0, 180, 0);
                }
                nClickIndex  = -1;
                bClickButton = true;
            }

            m_UndoManager.CheckDirty();
        }
        // --------------------------------------------------------------
        if ((EditorGUI.EndChangeCheck() || bClickButton) && GetFXMakerMain())
        {
            GetFXMakerMain().CreateCurrentInstanceEffect(true);
        }
        // ---------------------------------------------------------------------
        if (GUI.tooltip != "")
        {
            m_LastTooltip = GUI.tooltip;
        }
        HelpBox(m_LastTooltip);
    }
示例#27
0
        private ProceduralPathSettings FindPathSettings()
        {
            ProceduralPathSettings settings = AssetDatabase.FindAssets("t:ProceduralPathSettings")
                                              .Select(guid => AssetDatabase.LoadAssetAtPath <ProceduralPathSettings>(AssetDatabase.GUIDToAssetPath(guid)))
                                              .First();

            PathSettings = settings;
            return(settings);
        }
示例#28
0
    Texture2D BuildUVSpriteAtlas()
    {
        Texture2D[] textures    = new Texture2D[m_Sel.m_SpriteList.Count];
        Rect[]      textureRect = new Rect[m_Sel.m_SpriteList.Count];

        for (int n = 0; n < m_Sel.m_SpriteList.Count; n++)
        {
            if (m_Sel.m_SpriteList[n].m_bIncludedAtlas == false || m_Sel.m_SpriteList[n].m_TextureGUID == "")
            {
                textures[n] = null;
                continue;
            }

            Texture2D selTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(m_Sel.m_SpriteList[n].m_TextureGUID), typeof(Texture2D));
            SetSourceTexture(selTexture);
            m_Sel.m_SpriteList[n].m_nFrameCount = 1;
            m_Sel.m_SpriteList[n].m_nFrameSize  = 1;
            m_Sel.m_nFrameSize = 1;
            textures[n]        = selTexture;
            textureRect[n]     = new Rect(0, 0, selTexture.width, selTexture.height);
        }

        Color     clearColor   = new Color(0, 0, 0, 0);
        Texture2D AtlasTexture = new Texture2D(32, 32, TextureFormat.ARGB32, false);

        Rect[] packRects = AtlasTexture.PackTextures(textures, 3, m_Sel.m_nMaxAtlasTextureSize);
        m_Sel.m_nTilingX      = 1;
        m_Sel.m_nTilingY      = 1;
        m_Sel.m_fTextureRatio = AtlasTexture.width / (float)AtlasTexture.height;

        // clear
        for (int x = 0; x < AtlasTexture.width; x++)
        {
            for (int y = 0; y < AtlasTexture.height; y++)
            {
                AtlasTexture.SetPixel(x, y, clearColor);
            }
        }

        // copy
        for (int n = 0; n < m_Sel.m_SpriteList.Count; n++)
        {
            if (m_Sel.m_SpriteList[n].m_bIncludedAtlas == false || m_Sel.m_SpriteList[n].m_TextureGUID == "")
            {
                continue;
            }
            m_Sel.m_SpriteList[n].m_nStartFrame = 0;

            m_Sel.m_SpriteList[n].m_UvRect = packRects[n];
//          Debug.Log(packRects[n]);
//          Debug.Log(textureRect[n]);
//          Debug.Log(new Rect((int)(packRects[n].x*AtlasTexture.width), (int)(packRects[n].y*AtlasTexture.height), (int)(packRects[n].width*AtlasTexture.width), (int)(packRects[n].height*AtlasTexture.height)));

            // 알파조정 처리
            Color[] colBuf = textures[n].GetPixels();
            for (int an = 0; an < colBuf.Length; an++)
            {
                if (m_Sel.m_SpriteList[n].m_fMaxTextureAlpha < colBuf[an].a)
                {
                    colBuf[an].a = m_Sel.m_SpriteList[n].m_fMaxTextureAlpha;
                }
            }

            AtlasTexture.SetPixels((int)(packRects[n].x * AtlasTexture.width), (int)(packRects[n].y * AtlasTexture.height), (int)(packRects[n].width * AtlasTexture.width), (int)(packRects[n].height * AtlasTexture.height), colBuf);
        }
        return(AtlasTexture);
    }
示例#29
0
 public override void ReadFromString(ref uint index, ref string[] nodeParams)
 {
     try
     {
         int count = Convert.ToInt32(nodeParams[index++]);
         for (int i = 0; i < count; i++)
         {
             AdditionalLineType           lineType  = (AdditionalLineType)Enum.Parse(typeof(AdditionalLineType), nodeParams[index++]);
             string                       lineValue = nodeParams[index++];
             AdditionalDirectiveContainer newItem   = ScriptableObject.CreateInstance <AdditionalDirectiveContainer>();
             newItem.hideFlags = HideFlags.HideAndDontSave;
             newItem.LineType  = lineType;
             newItem.LineValue = lineValue;
             if (UIUtils.CurrentShaderVersion() > 15607)
             {
                 newItem.GUIDToggle = Convert.ToBoolean(nodeParams[index++]);
                 newItem.GUIDValue  = nodeParams[index++];
                 if (newItem.GUIDToggle)
                 {
                     newItem.LibObject = AssetDatabase.LoadAssetAtPath <TextAsset>(AssetDatabase.GUIDToAssetPath(newItem.GUIDValue));
                     if (newItem.LibObject == null)
                     {
                         Debug.LogWarning("Include file not found with GUID " + newItem.GUIDValue);
                     }
                 }
             }
             m_additionalDirectives.Add(newItem);
         }
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
 }
        /// <summary>
        /// 尝试查找当前生成物体上已经存在的自动生成脚本。
        /// </summary>
        /// <param name="gameObject"></param>
        /// <param name="script"></param>
        /// <param name="willBeOverride"></param>
        /// <returns></returns>
        protected virtual bool tryFindExistScript(GameObject gameObject, out MonoScript script, out bool willBeOverride)
        {
            //对所有脚本进行筛选
            var scripts = AssetDatabase.FindAssets("t:MonoScript")
                          .Select(g => AssetDatabase.GUIDToAssetPath(g))
                          .Select(p => AssetDatabase.LoadAssetAtPath <MonoScript>(p))
                          .Where(s => s != null);
            List <MonoScript> scriptList = new List <MonoScript>();

            foreach (var s in scripts)
            {
                //不是MonoBehaviour则跳过
                Type type = s.GetClass();
                if (type == null)
                {
                    continue;
                }
                AutoCompoAttribute autoCompo = type.getAttribute <AutoCompoAttribute>();
                int instanceID = gameObject.GetInstanceID();
                if (autoCompo != null && autoCompo.instanceID == instanceID)
                {
                    //如果脚本上有AutoCompo特性说明它是该物体的脚本,则返回这个脚本
                    script         = s;
                    willBeOverride = false;
                    return(true);
                }
                if ((type.IsSubclassOf(typeof(MonoBehaviour)) || type.IsSubclassOf(typeof(Component))) &&//如果这个脚本是组件
                    gameObject.GetComponent(type) != null   //并且在当前物体上存在这个脚本的实例
                    )
                {
                    //先添加到列表中,随后选出最适合作为目标脚本的脚本
                    scriptList.Add(s);
                }
            }
            if (scriptList.Count < 1)
            {
                //不存在符合的脚本
                script         = null;
                willBeOverride = false;
                return(false);
            }
            else if (scriptList.Count > 1)
            {
                //存在超过一个脚本,先查找其中自动生成的脚本
                MonoScript autoGenScript = scriptList.FirstOrDefault(s => s.text.Contains("<auto-generated>"));
                if (autoGenScript == null)
                {
                    //不存在自动生成的脚本
                    script         = null;
                    willBeOverride = false;
                    return(false);
                }
                //获取自动生成的类型,优先选择其中不是自动生成的脚本
                Type type = autoGenScript.GetClass();
                script = null;
                foreach (var s in scriptList)
                {
                    Type t = s.GetClass();
                    if (t == type && !s.text.Contains("<auto-generated>"))
                    {
                        script = s;
                        break;
                    }
                }
                if (script == null)
                {
                    //全是自动生成的,则返回第一个
                    script = scriptList[0];
                }
                willBeOverride = true;
                return(true);
            }
            else
            {
                //只有一个脚本,如果是自动生成的则返回这个脚本
                script = scriptList[0];
                if (script.text.Contains("<auto-generated>"))
                {
                    willBeOverride = true;
                    return(true);
                }
                else
                {
                    script         = null;
                    willBeOverride = false;
                    return(false);
                }
            }
        }