public static void GetTextureSize(TextureImporter textureImporter, out int width, out int height) { object[] args = new object[2] { 0, 0 }; MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance); mi.Invoke(textureImporter, args); width = (int)args[0]; height = (int)args[1]; }
// Texture processing End public static void TextureProcessingEnd(TextureImporter a_rTextureImporter, TextureImporterSettings a_rTextureImporterSettings) { if(a_rTextureImporter != null) { a_rTextureImporter.SetTextureSettings(a_rTextureImporterSettings); if(AssetDatabase.WriteImportSettingsIfDirty(a_rTextureImporter.assetPath)) { AssetDatabase.ImportAsset(a_rTextureImporter.assetPath, ImportAssetOptions.ForceSynchronousImport ); AssetDatabase.Refresh(); } } Uni2DAssetPostprocessor.Enabled = true; }
// http://forum.unity3d.com/threads/165295-Getting-original-size-of-texture-asset-in-pixels public static bool GetImageSize(TextureImporter importer, out int width, out int height) { if (importer != null) { object[] args = new object[2] { 0, 0 }; MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance); mi.Invoke(importer, args); width = (int)args[0]; height = (int)args[1]; return true; } height = width = 0; return false; }
private void UseSelectedTexture() { if (Selection.objects.Length > 1) { selectedTexture = null; } else { selectedTexture = Selection.activeObject as Texture2D; } if (selectedTexture != null) { var assetPath = AssetDatabase.GetAssetPath(selectedTexture); importer = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (importer) { var extension = Path.GetExtension(assetPath); var pathWithoutExtension = assetPath.Remove(assetPath.Length - extension.Length, extension.Length); var xmlPath = pathWithoutExtension + ".xml"; var textAsset = AssetDatabase.LoadAssetAtPath(xmlPath, typeof (TextAsset)); if (textAsset != null) { xmlAsset = textAsset as TextAsset; } else { xmlAsset = null; subTextures = null; } ParseXML(); } else { xmlAsset = null; subTextures = null; } } else { importer = null; xmlAsset = null; subTextures = null; } Repaint(); }
/// <summary> /// 更新Sprite对应的Meta文件 /// </summary> /// <param name="importer"></param> /// <param name="file"></param> void UpdateSpriteMetaData(TextureImporter importer, string file) { if (importer.textureType == TextureImporterType.Advanced) { importer.textureType = TextureImporterType.Sprite; } importer.maxTextureSize = 4096; importer.spriteImportMode = SpriteImportMode.Multiple; importer.textureFormat = TextureImporterFormat.RGBA32; //在路径中找到Plist文件,解析出SpriteData信息 List<SpriteData> sdList = PListFile.Parse(file); List<SpriteMetaData> metaDataList = new List<SpriteMetaData>(); for (int i = 0; i < sdList.Count; i++) { SpriteMetaData smd = new SpriteMetaData(); smd.name = sdList[i].name; float x = sdList[i].x; float y = sdList[i].y; float w = sdList[i].width; float h = sdList[i].height; smd.rect = new UnityEngine.Rect(x, y, w, h); smd.pivot = new UnityEngine.Vector2(0, 0); smd.alignment = (int)UnityEngine.SpriteAlignment.Center; metaDataList.Add(smd); } //将格式化后的数据送给Engine importer.spritesheet = metaDataList.ToArray(); }
void ImportStandard(string filename, SurfaceFormat expectedSurfaceFormat) { var importer = new TextureImporter( ); var context = new TestImporterContext(intermediateDirectory, outputDirectory); var content = importer.Import(filename, context); Assert.NotNull(content); Assert.AreEqual(content.Faces.Count, 1); Assert.AreEqual(content.Faces[0].Count, 1); Assert.AreEqual(content.Faces[0][0].Width, 64); Assert.AreEqual(content.Faces[0][0].Height, 64); SurfaceFormat format; Assert.True(content.Faces[0][0].TryGetFormat(out format)); Assert.AreEqual(expectedSurfaceFormat, format); // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions try { Directory.Delete(intermediateDirectory, true); Directory.Delete(outputDirectory, true); } catch(DirectoryNotFoundException) { } }
public Mesh CreateMeshFromVerts(Vector3[] vertsToCopy, Mesh mesh, List<int> pathSplitIds, Transform SpriteGO = null) { List<Vector3> resultsLocal = new List<Vector3>(); List<int> resultsTriIndexesLocal = new List<int>(); List<int> resultsTriIndexesReversedLocal = new List<int>(); List<Vector2> uvsLocal = new List<Vector2>(); List<Vector3> normalsLocal = new List<Vector3>(); Sprite spr = new Sprite(); Rect rec = new Rect(); Vector3 bound = Vector3.zero; TextureImporter textureImporter = new TextureImporter(); if(SpriteGO !=null && SpriteGO.GetComponent<SpriteRenderer>() && SpriteGO.GetComponent<SpriteRenderer>().sprite) { spr = SpriteGO.GetComponent<SpriteRenderer>().sprite; rec = spr.rect; bound = SpriteGO.GetComponent<Renderer>().bounds.max- SpriteGO.GetComponent<Renderer>().bounds.min ; textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(spr)) as TextureImporter; } List<PolygonPoint> p2 = new List<PolygonPoint>(); List<TriangulationPoint> extraPoints = new List<TriangulationPoint>(); int i = 0; for (i = 0; i < vertsToCopy.Count(); i ++) { if(i<pathSplitIds[0]) p2.Add(new PolygonPoint(vertsToCopy [i].x, vertsToCopy [i].y)); else extraPoints.Add(new TriangulationPoint(vertsToCopy [i].x, vertsToCopy [i].y)); } Polygon _polygon = new Polygon(p2); // this is how to add more points _polygon.AddSteinerPoints (extraPoints); P2T.Triangulate(_polygon); if (spr == null) { bound = new Vector3((float)(_polygon.Bounds.MaxX - _polygon.Bounds.MinX),(float)(_polygon.Bounds.MaxY - _polygon.Bounds.MinY),0 ) ; } int idx = 0; foreach (DelaunayTriangle triangle in _polygon.Triangles) { Vector3 v = new Vector3(); foreach (TriangulationPoint p in triangle.Points) { v = new Vector3((float)p.X, (float)p.Y,0); if(!resultsLocal.Contains(v)) { resultsLocal.Add(v); resultsTriIndexesLocal.Add(idx); Vector2 newUv = new Vector2(((v.x-(float)_polygon.Bounds.MinX) /bound.x) , ((v.y-(float)_polygon.Bounds.MinY) /bound.y) ); if (spr != null) { newUv = new Vector2 ((v.x / bound.x) + 0.5f, (v.y / bound.y) + 0.5f); newUv.x *= rec.width/ spr.texture.width; newUv.y *= rec.height/ spr.texture.height; newUv.x += (rec.x)/ spr.texture.width; newUv.y += (rec.y) / spr.texture.height; SpriteMetaData[] smdArray = textureImporter.spritesheet; Vector2 pivot = new Vector2(.0f,.0f);; for (int k = 0; k < smdArray.Length; k++) { if (smdArray[k].name == spr.name) { switch(smdArray[k].alignment) { case(0): smdArray[k].pivot = Vector2.zero; break; case(1): smdArray[k].pivot = new Vector2(0f,1f) -new Vector2(.5f,.5f); break; case(2): smdArray[k].pivot = new Vector2(0.5f,1f) -new Vector2(.5f,.5f); break; case(3): smdArray[k].pivot = new Vector2(1f,1f) -new Vector2(.5f,.5f); break; case(4): smdArray[k].pivot = new Vector2(0f,.5f) -new Vector2(.5f,.5f); break; case(5): smdArray[k].pivot = new Vector2(1f,.5f) -new Vector2(.5f,.5f); break; case(6): smdArray[k].pivot = new Vector2(0f,0f) -new Vector2(.5f,.5f); break; case(7): smdArray[k].pivot = new Vector2(0.5f,0f) -new Vector2(.5f,.5f); break; case(8): smdArray[k].pivot = new Vector2(1f,0f) -new Vector2(.5f,.5f); break; case(9): smdArray[k].pivot -= new Vector2(.5f,.5f); break; } pivot = smdArray[k].pivot ; } } if(textureImporter.spriteImportMode == SpriteImportMode.Single) pivot = textureImporter.spritePivot-new Vector2(.5f,.5f); newUv.x += ((pivot.x)*rec.width)/ spr.texture.width; newUv.y += ((pivot.y)*rec.height)/ spr.texture.height; } uvsLocal.Add(newUv); normalsLocal.Add(new Vector3(0,0,-1)); idx++; } else { resultsTriIndexesLocal.Add(resultsLocal.LastIndexOf(v)); } } } for (int j = resultsTriIndexesLocal.Count-1; j >=0; j--) { resultsTriIndexesReversedLocal.Add(resultsTriIndexesLocal[j]); } results.AddRange(resultsLocal); resultsTriIndexes.AddRange(resultsTriIndexesLocal); resultsTriIndexesReversed.AddRange(resultsTriIndexesReversedLocal); uvs.AddRange(uvsLocal); normals.AddRange(normalsLocal); resultsLocal.Clear(); resultsTriIndexesLocal.Clear(); resultsTriIndexesReversedLocal.Clear(); uvsLocal.Clear(); normalsLocal.Clear(); finalVertices = results.ToArray(); finalNormals = normals.ToArray(); finalUvs= uvs.ToArray(); finalTriangles = resultsTriIndexesReversed.ToArray(); mesh.vertices = finalVertices; mesh.triangles = finalTriangles; mesh.uv = finalUvs; mesh.normals = finalNormals; mesh = calculateMeshTangents (mesh); return mesh; }
public static Npck ChangeTextureImages(EmguImage[] images, int[] frames, Palette palOut, Npck original) { // Get an original texture file to get images and the texture to modify long start = original[0].Position; Btx0 oriTexture = new Btx0(original[0]); original[0].Position = start; Btx0 newTexture = new Btx0(original[0]); original[0].Position = start; // Create importer and remove all images TextureImporter importer = new TextureImporter(newTexture); importer.RemoveImages(); // Add images from arguments or original texture if not presents. List<int> frameList = frames.ToList(); for (int i = 0; i < oriTexture.NumTextures; i++) { int idx = frameList.IndexOf(i); // Set quantization to original palette or argument palette Color[] originalPalette = oriTexture.GetPalette(i).GetPalette(0); if (idx != -1 && palOut != null) importer.Quantization = new FixedPaletteQuantization(palOut.GetPalette(idx)); else importer.Quantization = new FixedPaletteQuantization(originalPalette); // Keep original color format and name string name = oriTexture.GetTextureName(i); importer.Format = oriTexture.GetImage(i).Format; // Keep original unknown values int[] texUnks = oriTexture.GetTextureUnknowns(i); int[] palUnks = oriTexture.GetPaletteUnknowns(i); // Import :D if (idx != -1) importer.AddImage(images[idx], name, texUnks, palUnks, originalPalette); else importer.AddImage(oriTexture.CreateBitmap(i), name, texUnks, palUnks); } // Write the new texture file MemoryStream textureStream = new MemoryStream(); newTexture.Write(textureStream); textureStream.Position = 0; // Create a copy of the NPCK from the original Npck npck = new Npck(); npck.AddSubfile(textureStream); for (int i = 1; i < 6; i++) npck.AddSubfile(original[i]); return npck; }
void OnPreprocessTexture() { if (!s_Initialized) { return; } string guid = AssetDatabase.AssetPathToGUID(assetPath); if (s_SpriteMeshToTextureCache.ContainsValue(guid)) { TextureImporter textureImporter = (TextureImporter)assetImporter; SerializedObject textureImporterSO = new SerializedObject(textureImporter); SerializedProperty textureImporterSprites = textureImporterSO.FindProperty("m_SpriteSheet.m_Sprites"); foreach (KeyValuePair <string, string> pair in s_SpriteMeshToTextureCache) { if (pair.Value == guid) { SpriteMesh spriteMesh = LoadSpriteMesh(AssetDatabase.GUIDToAssetPath(pair.Key)); SpriteMeshData spriteMeshData = SpriteMeshUtils.LoadSpriteMeshData(spriteMesh); if (spriteMesh && spriteMeshData && spriteMesh.sprite && spriteMeshData.vertices.Length > 0) { if (textureImporter.spriteImportMode == SpriteImportMode.Multiple) { SerializedProperty spriteProp = null; int i = 0; string name = ""; while (i < textureImporterSprites.arraySize && name != spriteMesh.sprite.name) { spriteProp = textureImporterSprites.GetArrayElementAtIndex(i); name = spriteProp.FindPropertyRelative("m_Name").stringValue; ++i; } if (name == spriteMesh.sprite.name) { Rect textureRect = SpriteMeshUtils.CalculateSpriteRect(spriteMesh, 5); spriteProp.FindPropertyRelative("m_Rect").rectValue = textureRect; spriteProp.FindPropertyRelative("m_Alignment").intValue = 9; spriteProp.FindPropertyRelative("m_Pivot").vector2Value = Vector2.Scale(spriteMeshData.pivotPoint - textureRect.position, new Vector2(1f / textureRect.size.x, 1f / textureRect.size.y)); } } else { int width = 0; int height = 0; SpriteMeshUtils.GetSpriteTextureSize(spriteMesh.sprite, ref width, ref height); textureImporterSO.FindProperty("m_Alignment").intValue = 9; textureImporterSO.FindProperty("m_SpritePivot").vector2Value = Vector2.Scale(spriteMeshData.pivotPoint, new Vector2(1f / width, 1f / height)); } } } } textureImporterSO.ApplyModifiedProperties(); } }
//检查纹理是否被设置成了Readable private bool CheckRadable(Texture texture, TextureImporter importer, ref CheckItem item) { item.isReadable = importer.isReadable; return(!item.isReadable); }
//Force Refresh void Refresh() { textureAtlas = Resources.Load(atlasName) as Texture2D; AtlasMat = Resources.Load(atlasMatName, typeof(Material)) as Material; //Setup for first times if (textureAtlas == null || AtlasMat == null) { if (!Directory.Exists(Application.dataPath + "/Resources")) { if (debug) { Debug.Log("Created Resources Folder"); } AssetDatabase.CreateFolder("Assets", "Resources"); AssetDatabase.Refresh(); } if (!File.Exists(Application.dataPath + "/Resources/" + atlasName + ".png")) { ResetTextureAtlas(); if (debug) { Debug.Log("Created Texture Atlas"); } } TextureImporter textureImporter = (TextureImporter)TextureImporter.GetAtPath("Assets/Resources/" + atlasName + ".png"); textureImporter.isReadable = true; textureImporter.SaveAndReimport(); if (!File.Exists(Application.dataPath + "/Resources/" + atlasMatName)) { if (debug) { Debug.Log("Created the Texture Atlas Material"); } Material mat = new Material(Shader.Find("Standard")); mat.mainTexture = Resources.Load(atlasName) as Texture2D; AssetDatabase.CreateAsset(mat, "Assets/Resources/" + atlasMatName + ".mat"); AssetDatabase.Refresh(); } textureAtlas = Resources.Load(atlasName) as Texture2D; AtlasMat = Resources.Load(atlasMatName, typeof(Material)) as Material; } //Initialize CreateStyles(); colorPaletteLength = 0; workTex = new Texture2D(textureAtlas.width, textureAtlas.height); gameObject = Selection.activeObject as GameObject; gameObjectEditor = Editor.CreateEditor(gameObject); renderer = gameObject.GetComponent <Renderer>(); if (gameObject.GetComponent <SkinnedMeshRenderer>() != null) { mesh = gameObject.GetComponent <SkinnedMeshRenderer>().sharedMesh; } else { mesh = gameObject.GetComponent <MeshFilter>().sharedMesh; } //Count color palette for (int i = 0; i < textureAtlas.width * textureAtlas.height / 16; i++) { if (textureAtlas.GetPixel((2 + 4 * (i % textureAtlas.width)), (2 + 4 * (4 * i / textureAtlas.width))) == bgColor) { break; } else { colorPaletteLength++; } } //Building the palette that is writable workTex.SetPixels(0, 0, workTex.width, workTex.height, textureAtlas.GetPixels(0, 0, textureAtlas.width, textureAtlas.height)); //If the object has a mesh, calculate the color picker if (mesh) { selectedColor = new int[mesh.subMeshCount]; prevSelected = new int[mesh.subMeshCount]; colors = new Texture2D[colorPaletteLength]; for (int i = 0; i < colorPaletteLength; i++) { colors[i] = new Texture2D(colorSize, colorSize); Color[] actualColor = new Color[colorSize * colorSize]; for (int j = 0; j < colorSize * colorSize; j++) { actualColor[j] = textureAtlas.GetPixel((2 + 4 * (i % textureAtlas.width)), (2 + 4 * (4 * i / textureAtlas.width))); } colors[i].SetPixels(0, 0, colors[i].width, colors[i].height, actualColor); colors[i].Apply(); } CheckForUvs(); } //Debug if (debug) { Debug.Log("The length of the color palette is " + colorPaletteLength); } }
static void updateSpriteMetaData(TextureImporter importer, string pathToData) { if (importer.textureType != TextureImporterType.Advanced) { importer.textureType = TextureImporterType.Sprite; } importer.maxTextureSize = 4096; importer.spriteImportMode = SpriteImportMode.Multiple; string[] dataFileContent = File.ReadAllLines(pathToData); int format = 30302; foreach (string row in dataFileContent) { if (row.StartsWith(":format=")) { format = int.Parse(row.Remove(0,8)); } } if (format != 30302) { EditorUtility.DisplayDialog("Please update TexturePacker Importer", "Your TexturePacker Importer is too old, \nplease load a new version from the asset store!", "Ok"); return; } Dictionary<string, SpriteMetaData> existingSprites = new Dictionary<string, SpriteMetaData>(); foreach (SpriteMetaData sprite in importer.spritesheet) { existingSprites.Add(sprite.name, sprite); } List<SpriteMetaData> metaData = new List<SpriteMetaData> (); foreach (string row in dataFileContent) { if (string.IsNullOrEmpty (row) || row.StartsWith ("#") || row.StartsWith (":")) continue; // comment lines start with #, additional atlas properties with : string [] cols = row.Split (';'); if (cols.Length < 7) return; // format error SpriteMetaData smd = new SpriteMetaData (); smd.name = cols [0].Replace ("/", "-"); // unity has problems with "/" in sprite names... float x = float.Parse (cols [1]); float y = float.Parse (cols [2]); float w = float.Parse (cols [3]); float h = float.Parse (cols [4]); float px = float.Parse (cols [5]); float py = float.Parse (cols [6]); smd.rect = new UnityEngine.Rect (x, y, w, h); if (existingSprites.ContainsKey(smd.name)) { SpriteMetaData sprite = existingSprites[smd.name]; smd.pivot = sprite.pivot; smd.alignment = sprite.alignment; #if !UNITY_4_3 // border attribute was introduced with 4.5 (versions <4.3 are not supported at all) smd.border = sprite.border; #endif } if (importPivotPoints || !existingSprites.ContainsKey(smd.name)) { smd.pivot = new UnityEngine.Vector2 (px, py); if (px == 0 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomLeft; else if (px == 0.5 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomCenter; else if (px == 1 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomRight; else if (px == 0 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.LeftCenter; else if (px == 0.5 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.Center; else if (px == 1 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.RightCenter; else if (px == 0 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopLeft; else if (px == 0.5 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopCenter; else if (px == 1 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopRight; else smd.alignment = (int)UnityEngine.SpriteAlignment.Custom; } metaData.Add (smd); } importer.spritesheet = metaData.ToArray(); }
static void MakeTextureCombo(string pathRGB, string suffixRGB, string suffixA, string suffixCombo) { string pathBase = pathRGB.Substring(0, pathRGB.LastIndexOf(suffixRGB)); string pathA = pathBase + suffixA; string pathCombo = pathBase + suffixCombo; Texture2D textureRGB = AssetDatabase.LoadAssetAtPath <Texture2D> (pathRGB); Texture2D textureA = AssetDatabase.LoadAssetAtPath <Texture2D> (pathA); Texture2D textureCombo = AssetDatabase.LoadAssetAtPath <Texture2D> (pathCombo); if (textureRGB != null && textureA != null) { if (textureCombo == null) { if (AssetDatabase.CopyAsset(pathRGB, pathCombo)) { AssetDatabase.Refresh(); textureCombo = AssetDatabase.LoadAssetAtPath <Texture2D> (pathCombo); Debug.Log("Creating " + pathCombo); } else { Debug.LogError("Failed to copy " + pathRGB); } } // Make them readable! TextureImporter tImporterRGB = AssetImporter.GetAtPath(pathRGB) as TextureImporter; tImporterRGB.textureType = TextureImporterType.Advanced; tImporterRGB.isReadable = true; AssetDatabase.ImportAsset(pathRGB); TextureImporter tImporterA = AssetImporter.GetAtPath(pathA) as TextureImporter; tImporterA.textureType = TextureImporterType.Advanced; tImporterA.isReadable = true; AssetDatabase.ImportAsset(pathA); TextureImporter tImporterCombo = AssetImporter.GetAtPath(pathCombo) as TextureImporter; tImporterCombo.textureType = TextureImporterType.Advanced; tImporterCombo.isReadable = true; tImporterCombo.textureFormat = TextureImporterFormat.RGBA32; // tImporterCombo.textureType = TextureImporterType. tImporterCombo.alphaIsTransparency = true; AssetDatabase.ImportAsset(pathCombo); AssetDatabase.Refresh(); // Copy over data. Color32[] dataRGB = textureRGB.GetPixels32(); Color32[] dataA = textureA.GetPixels32(); if (dataRGB.Length != dataA.Length) { Debug.LogWarning("Cannot combine textures of unequal size: " + pathRGB + " and " + pathA); return; } bool hasTransparency = false; Color32[] dataCombo = new Color32[dataRGB.Length]; for (int h = 0; h < dataCombo.Length; h++) { dataCombo [h] = new Color32( dataRGB [h].r, dataRGB [h].g, dataRGB [h].b, dataA [h].r); hasTransparency |= (dataA [h].r != 255); // Have transparency if A not always saturated. } // Set the data for the new texture. textureCombo.SetPixels32(dataCombo); textureCombo.alphaIsTransparency = true; textureCombo.Apply(); // Clean up texture import settings. tImporterRGB.isReadable = false; tImporterRGB.textureType = TextureImporterType.Image; AssetDatabase.ImportAsset(pathRGB); tImporterA.isReadable = false; tImporterA.textureType = TextureImporterType.Image; AssetDatabase.ImportAsset(pathA); File.WriteAllBytes(pathCombo, textureCombo.EncodeToPNG()); tImporterCombo.isReadable = false; tImporterCombo.textureType = TextureImporterType.Image; tImporterCombo.alphaIsTransparency = hasTransparency; tImporterCombo.textureFormat = TextureImporterFormat.AutomaticCompressed; AssetDatabase.ImportAsset(pathCombo); AssetDatabase.Refresh(); } else { Debug.Log("Found diffuse but no matching opacity: " + pathA); } }
public override void OnInspectorGUI() { if (s_Styles == null) { s_Styles = new Styles(); } serializedObject.Update(); GUILayout.Label("All following effects will use LDR color buffers.", EditorStyles.miniBoldLabel); //if (concreteTarget.tonemapping.enabled) //{ // Camera camera = concreteTarget.GetComponent<Camera>(); // if (camera != null && !camera.hdr) // EditorGUILayout.HelpBox("The camera is not HDR enabled. This will likely break the tonemapper.", MessageType.Warning); // else if (!concreteTarget.validRenderTextureFormat) // EditorGUILayout.HelpBox("The input to tonemapper is not in HDR. Make sure that all effects prior to this are executed in HDR.", MessageType.Warning); //} if (concreteTarget.lut.enabled && concreteTarget.lut.texture != null) { if (!concreteTarget.validUserLutSize) { EditorGUILayout.HelpBox("Invalid LUT size. Should be \"height = sqrt(width)\" (e.g. 256x16).", MessageType.Error); } else { // Checks import settings on the lut, offers to fix them if invalid TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(concreteTarget.lut.texture)); #if UNITY_5_5_OR_NEWER bool valid = importer.anisoLevel == 0 && importer.mipmapEnabled == false && importer.sRGBTexture == false && (importer.textureCompression == TextureImporterCompression.Uncompressed); #else bool valid = importer.anisoLevel == 0 && importer.mipmapEnabled == false && importer.linearTexture == true && (importer.textureFormat == TextureImporterFormat.RGB24 || importer.textureFormat == TextureImporterFormat.AutomaticTruecolor); #endif if (!valid) { EditorGUILayout.HelpBox("Invalid LUT import settings.", MessageType.Warning); GUILayout.Space(-32); EditorGUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Fix", GUILayout.Width(60))) { SetLUTImportSettings(importer); AssetDatabase.Refresh(); } GUILayout.Space(8); } EditorGUILayout.EndHorizontal(); GUILayout.Space(11); } } } DrawFields(); serializedObject.ApplyModifiedProperties(); }
private void DrawFields() { foreach (var group in m_GroupFields) { var enabledField = group.Value.FirstOrDefault(x => x.propertyPath == group.Key.Name + ".enabled"); var groupProperty = serializedObject.FindProperty(group.Key.Name); GUILayout.Space(5); bool display = EditorGUIHelper.Header(groupProperty, enabledField); if (!display) { continue; } GUILayout.BeginHorizontal(); { GUILayout.Space(10); GUILayout.BeginVertical(); { GUILayout.Space(3); foreach (var field in group.Value.Where(x => x.propertyPath != group.Key.Name + ".enabled")) { // Special case for the tonemapping curve field //if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) && // field.propertyType == SerializedPropertyType.AnimationCurve && // concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Curve) // continue; // Special case for the neutral tonemapper bool neutralParam = field.name.StartsWith("neutral"); //if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) && // concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Neutral && // neutralParam) // continue; if (neutralParam) { EditorGUILayout.PropertyField(field, new GUIContent(ObjectNames.NicifyVariableName(field.name.Substring(7)))); } else { EditorGUILayout.PropertyField(field); } } // Bake button if (group.Key.FieldType == typeof(TonemappingColorGrading.ColorGradingSettings)) { EditorGUI.BeginDisabledGroup(!enabledField.boolValue); if (GUILayout.Button("Export LUT as PNG", EditorStyles.miniButton)) { string path = EditorUtility.SaveFilePanelInProject("Export LUT as PNG", "LUT.png", "png", "Please enter a file name to save the LUT texture to"); if (!string.IsNullOrEmpty(path)) { Texture2D lut = concreteTarget.BakeLUT(); if (!concreteTarget.isGammaColorSpace) { var pixels = lut.GetPixels(); for (int i = 0; i < pixels.Length; i++) { pixels[i] = pixels[i].linear; } lut.SetPixels(pixels); lut.Apply(); } byte[] bytes = lut.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); DestroyImmediate(lut); AssetDatabase.Refresh(); TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path); SetLUTImportSettings(importer); } } EditorGUI.EndDisabledGroup(); } } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); } }
static void CustomFontDemo() { if (Selection.objects.Length <= 0) { return; } //选择图片 var path = AssetDatabase.GetAssetPath(Selection.objects[0]); Texture sprite = null; TextureImporter setting = null; try { sprite = (Texture)Selection.objects[0]; setting = (TextureImporter)TextureImporter.GetAtPath(path); Debug.Log(setting.spritesheet.Length + ", width: " + sprite.width + ",height: " + sprite.height); } catch { Debug.Log("请选择图片及确认图片是否正确"); } nci = new CharacterInfo[setting.spritesheet.Length]; for (int i = 0; i < setting.spritesheet.Length; i++) { var item = setting.spritesheet[i]; string objname = setting.spritesheet[i].name; string[] split = objname.Split('_'); int index = int.Parse(split[1]); CharacterInfo ci = new CharacterInfo(); ci.index = index; float uvx = item.rect.x / sprite.width; float uvy = item.rect.y / sprite.height; float uvw = item.rect.width / sprite.width; float uvh = item.rect.height / sprite.height; int vertx = 0; float verty = item.rect.height / 2; float vertwidth = item.rect.width; float vertheight = -item.rect.height; ci.uvBottomLeft = new Vector2(uvx, uvy); ci.uvBottomRight = new Vector2(uvx + uvw, uvy); ci.uvTopLeft = new Vector2(uvx, uvy + uvh); ci.uvTopRight = new Vector2(uvx + uvw, uvy + uvh); //Rect uvRect = new Rect(uvx, uvy, uvw, uvh); Rect vertRect = new Rect(vertx, verty, vertwidth, vertheight); ci.minX = (int)vertRect.xMin; ci.minY = (int)vertRect.yMax; ci.maxX = (int)vertRect.xMax; ci.maxY = (int)vertRect.yMin; ci.advance = (int)vertwidth; //以下代码已经是Obsolete //ci.width = item.rect.width; //ci.uv.x = item.rect.x / sprite.width; //ci.uv.y = item.rect.y / sprite.height; //ci.uv.width = item.rect.width / sprite.width; //ci.uv.height = item.rect.height / sprite.height; //ci.vert.x = 0; //ci.vert.y = item.rect.height / 2; //ci.vert.width = item.rect.width; //ci.vert.height = -item.rect.height; nci[i] = ci; //Debug.Log(ci.uv.ToString() + "," + ci.vert.ToString()); } }
//检查纹理贴图是否有packingTag private bool CheckPackingTag(Texture texture, TextureImporter importer, ref CheckItem item) { item.isPackingTag = !string.IsNullOrEmpty(importer.spritePackingTag); return(item.isPackingTag); }
private bool CheckMipMaps(Texture texture, TextureImporter importer, ref CheckItem item) { item.isMipMaps = importer.mipmapEnabled; return(!item.isMipMaps); }
static void ClearPlatformOverrides(string platformName, TextureImporter importer) { //Workaround: without this AssetDatabase.ImportAsset() not working importer.SetPlatformTextureSettings(platformName, 0, 0); importer.ClearPlatformTextureSettings(platformName); }
private static Sprite SaveAsset(PsdExportSettings settings, Texture2D tex, int layer) { string assetPath = GetLayerFilename(settings, layer); // Setup scaling variables float pixelsToUnits = settings.PixelsToUnitSize; // Apply global scaling, if any if (settings.ScaleBy > 0) { tex = ScaleTextureByMipmap(tex, settings.ScaleBy); } PsdExportSettings.LayerSetting layerSetting = settings.layerSettings[layer]; // Then scale by layer scale if (layerSetting.scaleBy != ScaleDown.Default) { // By default, scale by half int scaleLevel = 1; pixelsToUnits = Mathf.RoundToInt(settings.PixelsToUnitSize / 2f); // Setting is actually scale by quarter if (layerSetting.scaleBy == ScaleDown.Quarter) { scaleLevel = 2; pixelsToUnits = Mathf.RoundToInt(settings.PixelsToUnitSize / 4f); } // Apply scaling tex = ScaleTextureByMipmap(tex, scaleLevel); } byte[] buf = tex.EncodeToPNG(); File.WriteAllBytes(assetPath, buf); AssetDatabase.Refresh(); // Load the texture so we can change the type var textureObj = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)); // Get the texture importer for the asset TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(assetPath); // Read out the texture import settings so import pivot point can be changed TextureImporterSettings importSetting = new TextureImporterSettings(); textureImporter.ReadTextureSettings(importSetting); // Set the pivot import setting importSetting.spriteAlignment = (int)settings.Pivot; // But if layer setting has a different pivot, set as new pivot if (settings.Pivot != layerSetting.pivot) { importSetting.spriteAlignment = (int)layerSetting.pivot; } // Pivot settings are the same but custom, set the vector //else if (settings.Pivot == SpriteAlignment.Custom) // importSetting.spritePivot = settings.PivotVector; importSetting.spritePixelsPerUnit = pixelsToUnits; // Set the rest of the texture settings textureImporter.textureType = TextureImporterType.Sprite; textureImporter.spriteImportMode = SpriteImportMode.Single; textureImporter.spritePackingTag = settings.PackingTag; // Write in the texture import settings textureImporter.SetTextureSettings(importSetting); EditorUtility.SetDirty(textureObj); AssetDatabase.WriteImportSettingsIfDirty(assetPath); AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); return((Sprite)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Sprite))); }
// Texture processing Begin public static TextureImporterSettings TextureProcessingBegin(TextureImporter a_rTextureImporter) { Uni2DEditorSpriteAssetPostProcessor.Enabled = false; // If it's the first time Uni2d use this texture // Set the default texture importer settings Texture2D rTexture = AssetDatabase.LoadAssetAtPath(a_rTextureImporter.assetPath, typeof(Texture2D)) as Texture2D; if(Uni2DEditorUtils.ItIsTheFirstTimeWeUseTheTexture(rTexture)) { SetDefaultTextureImporterSettings(a_rTextureImporter); Uni2DEditorUtils.GenerateTextureImportGUID(rTexture); } TextureImporterSettings rTextureImporterSettings = new TextureImporterSettings(); a_rTextureImporter.ReadTextureSettings(rTextureImporterSettings); // Reimport texture as readable and at original size a_rTextureImporter.isReadable = true; a_rTextureImporter.npotScale = TextureImporterNPOTScale.None; a_rTextureImporter.maxTextureSize = 4096; a_rTextureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; if(AssetDatabase.WriteImportSettingsIfDirty(a_rTextureImporter.assetPath)) { AssetDatabase.ImportAsset(a_rTextureImporter.assetPath); AssetDatabase.Refresh(); } return rTextureImporterSettings; }
/// <summary> /// 将Multiply精灵格式图片分割并保存 /// </summary> /// <param name="tex"></param> private static void SplitSprite(Texture2D tex) { if (tex == null) { return; } string assetPath = AssetDatabase.GetAssetPath(tex); tex = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath); TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(assetPath); if (!textureImporter.isReadable) { textureImporter.isReadable = true; AssetDatabase.ImportAsset(assetPath); } if (textureImporter.textureType == TextureImporterType.Sprite && textureImporter.spriteImportMode == SpriteImportMode.Multiple) { string spritename = assetPath.Remove(0, 7).Replace('/', '_'); if (spritename.Contains(".")) { int indexOfDot = spritename.LastIndexOf('.'); spritename = spritename.Remove(indexOfDot, spritename.Length - indexOfDot); } spritename += " "; string finalFilePath; int summaryLength = textureImporter.spritesheet.Length; for (int i = 0; i < summaryLength; i++) { SpriteMetaData data = textureImporter.spritesheet[i]; int pivotPosX = (int)(data.pivot.x * data.rect.width + data.rect.xMin); int pivotPosY = (int)(data.pivot.y * data.rect.height + data.rect.yMin); int realWidth = (int)(2 * (Mathf.Max(Mathf.Abs(data.rect.xMax - pivotPosX), Mathf.Abs(data.rect.xMin - pivotPosX)))); int realHeight = (int)(2 * (Mathf.Max(Mathf.Abs(data.rect.yMax - pivotPosY), Mathf.Abs(data.rect.yMin - pivotPosY)))); Texture2D texture2d = new Texture2D(realWidth, realHeight); texture2d.name = spritename + data.name; finalFilePath = savingFolderPath + "/" + texture2d.name + ".png"; ShowProgress(finalFilePath, i / (float)summaryLength); Color colorTemp; int texInSpriteX; int texInSpriteY; for (int x = 0; x < realWidth; x++) { for (int y = 0; y < realHeight; y++) { colorTemp = Color.clear; texInSpriteX = x - realWidth / 2 + pivotPosX; texInSpriteY = y - realHeight / 2 + pivotPosY; if (texInSpriteX >= data.rect.xMin && texInSpriteX <= data.rect.xMax && texInSpriteY >= data.rect.yMin && texInSpriteY <= data.rect.yMax) { colorTemp = tex.GetPixel(texInSpriteX, texInSpriteY); } texture2d.SetPixel(x, y, colorTemp); } } texture2d.Apply(); if (File.Exists(finalFilePath)) { //UnityEngine.Debug.Log(finalFilePath + " 替换"); File.Delete(finalFilePath); } using (FileStream fs = new FileStream(finalFilePath, FileMode.Create)) { byte[] datas = texture2d.EncodeToPNG(); fs.Write(datas, 0, datas.Length); } pngCounting++; } } }
public void ImportDdsCubemapDxt1() { var importer = new TextureImporter(); var context = new TestImporterContext(intermediateDirectory, outputDirectory); var content = importer.Import("Assets/Textures/SampleCube64DXT1Mips.dds", context); Assert.NotNull(content); Assert.AreEqual(content.Faces.Count, 6); for (int f = 0; f < 6; ++f) { CheckDdsFace(content, f); } SurfaceFormat format; Assert.True(content.Faces[0][0].TryGetFormat(out format)); Assert.AreEqual(format, SurfaceFormat.Dxt1); // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions try { Directory.Delete(intermediateDirectory, true); Directory.Delete(outputDirectory, true); } catch (DirectoryNotFoundException) { } }
private bool IsEqual(TextureImporter target) { TextureImporter reference = referenceImporter as TextureImporter; UnityEngine.Assertions.Assert.IsNotNull(reference); if (target.anisoLevel != reference.anisoLevel) { return(false); } if (target.borderMipmap != reference.borderMipmap) { return(false); } if (target.compressionQuality != reference.compressionQuality) { return(false); } if (target.convertToNormalmap != reference.convertToNormalmap) { return(false); } if (target.fadeout != reference.fadeout) { return(false); } if (target.filterMode != reference.filterMode) { return(false); } if (target.generateCubemap != reference.generateCubemap) { return(false); } if (target.generateMipsInLinearSpace != reference.generateMipsInLinearSpace) { return(false); } if (target.grayscaleToAlpha != reference.grayscaleToAlpha) { return(false); } if (target.heightmapScale != reference.heightmapScale) { return(false); } if (target.isReadable != reference.isReadable) { return(false); } if (target.lightmap != reference.lightmap) { return(false); } if (target.linearTexture != reference.linearTexture) { return(false); } if (target.maxTextureSize != reference.maxTextureSize) { return(false); } if (target.mipMapBias != reference.mipMapBias) { return(false); } if (target.mipmapEnabled != reference.mipmapEnabled) { return(false); } if (target.mipmapFadeDistanceEnd != reference.mipmapFadeDistanceEnd) { return(false); } if (target.mipmapFadeDistanceStart != reference.mipmapFadeDistanceStart) { return(false); } if (target.mipmapFilter != reference.mipmapFilter) { return(false); } if (target.normalmap != reference.normalmap) { return(false); } if (target.normalmapFilter != reference.normalmapFilter) { return(false); } if (target.npotScale != reference.npotScale) { return(false); } // target.qualifiesForSpritePacking is read only if (target.spriteBorder != reference.spriteBorder) { return(false); } if (target.spriteImportMode != reference.spriteImportMode) { return(false); } if (target.spritePackingTag != reference.spritePackingTag) { return(false); } if (target.spritePivot != reference.spritePivot) { return(false); } if (target.spritePixelsPerUnit != reference.spritePixelsPerUnit) { return(false); } // spritesheet { if (target.spritesheet.Length != reference.spritesheet.Length) { return(false); } for (int i = 0; i < target.spritesheet.Length; i++) { if (target.spritesheet[i].alignment != reference.spritesheet[i].alignment) { return(false); } if (target.spritesheet[i].border != reference.spritesheet[i].border) { return(false); } if (target.spritesheet[i].name != reference.spritesheet[i].name) { return(false); } if (target.spritesheet[i].pivot != reference.spritesheet[i].pivot) { return(false); } if (target.spritesheet[i].rect != reference.spritesheet[i].rect) { return(false); } } } if (target.textureFormat != reference.textureFormat) { return(false); } if (target.textureType != reference.textureType) { return(false); } if (target.wrapMode != reference.wrapMode) { return(false); } return(true); }
private void NormalMapCreator() { GUILayout.Label("Normal Map Creator", bigLabel); GUILayout.Space(20); GUILayout.Label("Select the folder where new Normal Maps will be saved when the Create Normal Map button of the asset component is pressed (URP only)", EditorStyles.boldLabel); HandleSaveFolderEditorPref("All1ShaderNormals", "Assets/AllIn1SpriteShader/Textures/NormalMaps", "Normal Maps"); GUILayout.Space(20); GUILayout.Label("Assign a sprite you want to create a normal map from. Choose the normal map settings and press the 'Create And Save Normal Map' button", EditorStyles.boldLabel); targetNormalImage = (Texture2D)EditorGUILayout.ObjectField("Target Image", targetNormalImage, typeof(Texture2D), false, GUILayout.MaxWidth(225)); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Normal Strenght:", GUILayout.MaxWidth(150)); normalStrenght = EditorGUILayout.Slider(normalStrenght, 1f, 20f, GUILayout.MaxWidth(400)); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Normal Smoothing:", GUILayout.MaxWidth(150)); normalSmoothing = EditorGUILayout.IntSlider(normalSmoothing, 0, 3, GUILayout.MaxWidth(400)); } EditorGUILayout.EndHorizontal(); if (isComputingNormals == 0) { if (targetNormalImage != null) { if (GUILayout.Button("Create And Save Normal Map")) { isComputingNormals = 1; return; } } else { GUILayout.Label("Add a Target Image to use this feature", EditorStyles.boldLabel); } } else { GUILayout.Label("Normal Map is currently being created, be patient", EditorStyles.boldLabel, GUILayout.Height(40)); Repaint(); isComputingNormals++; if (isComputingNormals > 5) { string assetPath = AssetDatabase.GetAssetPath(targetNormalImage); var tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (tImporter != null) { tImporter.isReadable = true; tImporter.SaveAndReimport(); } Texture2D normalToSave = CreateNormalMap(targetNormalImage, normalStrenght, normalSmoothing); string path = EditorUtility.SaveFilePanel("Save texture as PNG", PlayerPrefs.GetString("All1ShaderNormals"), "normalMap_1.png", "png"); if (path.Length != 0) { byte[] pngData = normalToSave.EncodeToPNG(); if (pngData != null) { File.WriteAllBytes(path, pngData); } AssetDatabase.Refresh(); if (path.IndexOf("Assets/") >= 0) { string subPath = path.Substring(path.IndexOf("Assets/")); TextureImporter importer = AssetImporter.GetAtPath(subPath) as TextureImporter; if (importer != null) { Debug.Log("Normal Map saved inside the project: " + subPath); importer.filterMode = FilterMode.Bilinear; importer.textureType = TextureImporterType.NormalMap; importer.wrapMode = TextureWrapMode.Repeat; importer.SaveAndReimport(); } } else { Debug.Log("Gradient saved outside the project: " + path); } } isComputingNormals = 0; } } GUILayout.Label("*This process will freeze the editor for some seconds, larger images will take longer", EditorStyles.boldLabel); }
static void CheckStaticCommonIssues() { if (OVRManager.IsUnityAlphaOrBetaVersion()) { AddFix("General", OVRManager.UnityAlphaOrBetaVersionWarningMessage, null, null); } if (QualitySettings.anisotropicFiltering != AnisotropicFiltering.Enable && QualitySettings.anisotropicFiltering != AnisotropicFiltering.ForceEnable) { AddFix("Optimize Aniso", "Anisotropic filtering is recommended for optimal image sharpness and GPU performance.", delegate(UnityEngine.Object obj, bool last, int selected) { // Ideally this would be multi-option: offer Enable or ForceEnable. QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable; }, null, "Fix"); } #if UNITY_ANDROID int recommendedPixelLightCount = 1; #else int recommendedPixelLightCount = 3; #endif if (QualitySettings.pixelLightCount > recommendedPixelLightCount) { AddFix("Optimize Pixel Light Count", "For GPU performance set no more than " + recommendedPixelLightCount + " pixel lights in Quality Settings (currently " + QualitySettings.pixelLightCount + ").", delegate(UnityEngine.Object obj, bool last, int selected) { QualitySettings.pixelLightCount = recommendedPixelLightCount; }, null, "Fix"); } #if false // Should we recommend this? Seems to be mutually exclusive w/ dynamic batching. if (!PlayerSettings.graphicsJobs) { AddFix("Optimize Graphics Jobs", "For CPU performance, please use graphics jobs.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.graphicsJobs = true; }, null, "Fix"); } #endif #if UNITY_2017_2_OR_NEWER if ((!PlayerSettings.MTRendering || !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android))) #else if ((!PlayerSettings.MTRendering || !PlayerSettings.mobileMTRendering)) #endif { AddFix("Optimize MT Rendering", "For CPU performance, please enable multithreaded rendering.", delegate(UnityEngine.Object obj, bool last, int selected) { #if UNITY_2017_2_OR_NEWER PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Standalone, true); PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true); #else PlayerSettings.MTRendering = PlayerSettings.mobileMTRendering = true; #endif }, null, "Fix"); } #if UNITY_ANDROID if (!PlayerSettings.use32BitDisplayBuffer) { AddFix("Optimize Display Buffer Format", "We recommend to enable use32BitDisplayBuffer.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.use32BitDisplayBuffer = true; }, null, "Fix"); } #endif #if UNITY_2017_3_OR_NEWER && !UNITY_ANDROID if (!PlayerSettings.VROculus.dashSupport) { AddFix("Enable Dash Integration", "We recommend to enable Dash Integration for better user experience.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.VROculus.dashSupport = true; }, null, "Fix"); } if (!PlayerSettings.VROculus.sharedDepthBuffer) { AddFix("Enable Depth Buffer Sharing", "We recommend to enable Depth Buffer Sharing for better user experience on Oculus Dash.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.VROculus.sharedDepthBuffer = true; }, null, "Fix"); } #endif BuildTargetGroup target = EditorUserBuildSettings.selectedBuildTargetGroup; var tier = UnityEngine.Rendering.GraphicsTier.Tier1; var tierSettings = UnityEditor.Rendering.EditorGraphicsSettings.GetTierSettings(target, tier); if ((tierSettings.renderingPath == RenderingPath.DeferredShading || tierSettings.renderingPath == RenderingPath.DeferredLighting)) { AddFix("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate(UnityEngine.Object obj, bool last, int selected) { tierSettings.renderingPath = RenderingPath.Forward; UnityEditor.Rendering.EditorGraphicsSettings.SetTierSettings(target, tier, tierSettings); }, null, "Use Forward"); } if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass) { AddFix("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.stereoRenderingPath = StereoRenderingPath.Instancing; }, null, "Fix"); } if (LightmapSettings.lightmaps.Length > 0 && LightmapSettings.lightmapsMode != LightmapsMode.NonDirectional) { AddFix("Optimize Lightmap Directionality", "Switching from directional lightmaps to non-directional lightmaps can save a small amount of GPU time.", delegate(UnityEngine.Object obj, bool last, int selected) { LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional; }, null, "Switch to non-directional lightmaps"); } if (Lightmapping.realtimeGI) { AddFix("Disable Realtime GI", "Disabling real-time global illumination can improve GPU performance.", delegate(UnityEngine.Object obj, bool last, int selected) { Lightmapping.realtimeGI = false; }, null, "Set Lightmapping.realtimeGI = false."); } var lights = GameObject.FindObjectsOfType <Light>(); for (int i = 0; i < lights.Length; ++i) { #if UNITY_2017_3_OR_NEWER if (lights [i].type != LightType.Directional && !lights [i].bakingOutput.isBaked && IsLightBaked(lights[i])) #else if (lights[i].type != LightType.Directional && !lights[i].isBaked && IsLightBaked(lights[i])) #endif { AddFix("Unbaked Lights", "The following lights in the scene are marked as Baked, but they don't have up to date lightmap data. Generate the lightmap data, or set it to auto-generate, in Window->Lighting->Settings.", null, lights[i], null); } if (lights[i].shadows != LightShadows.None && !IsLightBaked(lights[i])) { AddFix("Optimize Shadows", "For CPU performance, consider disabling shadows on realtime lights.", delegate(UnityEngine.Object obj, bool last, int selected) { Light thisLight = (Light)obj; thisLight.shadows = LightShadows.None; }, lights[i], "Set \"Shadow Type\" to \"No Shadows\""); } } var sources = GameObject.FindObjectsOfType <AudioSource>(); if (sources.Length > 16) { List <AudioSource> playingAudioSources = new List <AudioSource>(); foreach (var audioSource in sources) { if (audioSource.isPlaying) { playingAudioSources.Add(audioSource); } } if (playingAudioSources.Count > 16) { // Sort playing audio sources by priority playingAudioSources.Sort(delegate(AudioSource x, AudioSource y) { return(x.priority.CompareTo(y.priority)); }); for (int i = 16; i < playingAudioSources.Count; ++i) { AddFix("Optimize Audio Source Count", "For CPU performance, please disable all but the top 16 AudioSources.", delegate(UnityEngine.Object obj, bool last, int selected) { AudioSource audioSource = (AudioSource)obj; audioSource.enabled = false; }, playingAudioSources[i], "Disable"); } } } var clips = GameObject.FindObjectsOfType <AudioClip>(); for (int i = 0; i < clips.Length; ++i) { if (clips[i].loadType == AudioClipLoadType.DecompressOnLoad) { AddFix("Audio Loading", "For fast loading, please don't use decompress on load for audio clips", delegate(UnityEngine.Object obj, bool last, int selected) { AudioClip thisClip = (AudioClip)obj; if (selected == 0) { SetAudioLoadType(thisClip, AudioClipLoadType.CompressedInMemory, last); } else { SetAudioLoadType(thisClip, AudioClipLoadType.Streaming, last); } }, clips[i], "Change to Compressed in Memory", "Change to Streaming"); } if (clips[i].preloadAudioData) { AddFix("Audio Preload", "For fast loading, please don't preload data for audio clips.", delegate(UnityEngine.Object obj, bool last, int selected) { SetAudioPreload(clips[i], false, last); }, clips[i], "Fix"); } } if (Physics.defaultContactOffset < 0.01f) { AddFix("Optimize Contact Offset", "For CPU performance, please don't use default contact offset below 0.01.", delegate(UnityEngine.Object obj, bool last, int selected) { Physics.defaultContactOffset = 0.01f; }, null, "Fix"); } if (Physics.sleepThreshold < 0.005f) { AddFix("Optimize Sleep Threshold", "For CPU performance, please don't use sleep threshold below 0.005.", delegate(UnityEngine.Object obj, bool last, int selected) { Physics.sleepThreshold = 0.005f; }, null, "Fix"); } if (Physics.defaultSolverIterations > 8) { AddFix("Optimize Solver Iterations", "For CPU performance, please don't use excessive solver iteration counts.", delegate(UnityEngine.Object obj, bool last, int selected) { Physics.defaultSolverIterations = 8; }, null, "Fix"); } var materials = Resources.FindObjectsOfTypeAll <Material>(); for (int i = 0; i < materials.Length; ++i) { if (materials[i].shader.name.Contains("Parallax") || materials[i].IsKeywordEnabled("_PARALLAXMAP")) { AddFix("Optimize Shading", "For GPU performance, please don't use parallax-mapped materials.", delegate(UnityEngine.Object obj, bool last, int selected) { Material thisMaterial = (Material)obj; if (thisMaterial.IsKeywordEnabled("_PARALLAXMAP")) { thisMaterial.DisableKeyword("_PARALLAXMAP"); } if (thisMaterial.shader.name.Contains("Parallax")) { var newName = thisMaterial.shader.name.Replace("-ParallaxSpec", "-BumpSpec"); newName = newName.Replace("-Parallax", "-Bump"); var newShader = Shader.Find(newName); if (newShader) { thisMaterial.shader = newShader; } else { Debug.LogWarning("Unable to find a replacement for shader " + materials[i].shader.name); } } }, materials[i], "Fix"); } } var renderers = GameObject.FindObjectsOfType <Renderer>(); for (int i = 0; i < renderers.Length; ++i) { if (renderers[i].sharedMaterial == null) { AddFix("Instanced Materials", "Please avoid instanced materials on renderers.", null, renderers[i]); } } var overlays = GameObject.FindObjectsOfType <OVROverlay>(); if (overlays.Length > 4) { AddFix("Optimize VR Layer Count", "For GPU performance, please use 4 or fewer VR layers.", delegate(UnityEngine.Object obj, bool last, int selected) { for (int i = 4; i < OVROverlay.instances.Length; ++i) { OVROverlay.instances[i].enabled = false; } }, null, "Fix"); } var splashScreen = PlayerSettings.virtualRealitySplashScreen; if (splashScreen != null) { if (splashScreen.filterMode != FilterMode.Trilinear) { AddFix("Optimize VR Splash Filtering", "For visual quality, please use trilinear filtering on your VR splash screen.", delegate(UnityEngine.Object obj, bool last, int EditorSelectedRenderState) { var assetPath = AssetDatabase.GetAssetPath(splashScreen); var importer = (TextureImporter)TextureImporter.GetAtPath(assetPath); importer.filterMode = FilterMode.Trilinear; AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); }, null, "Fix"); } if (splashScreen.mipmapCount <= 1) { AddFix("Generate VR Splash Mipmaps", "For visual quality, please use mipmaps with your VR splash screen.", delegate(UnityEngine.Object obj, bool last, int EditorSelectedRenderState) { var assetPath = AssetDatabase.GetAssetPath(splashScreen); var importer = (TextureImporter)TextureImporter.GetAtPath(assetPath); importer.mipmapEnabled = true; AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); }, null, "Fix"); } } }
public override void OnInspectorGUI() { // We won't just use default inspector because we want to show some of the params conditionally based on cache type // First show standard 'Script' field GUI.enabled = false; EditorGUILayout.PropertyField(serializedObject.FindProperty("m_Script")); GUI.enabled = true; // Next expose cache type and refresh mode var typeProp = serializedObject.FindProperty("_type"); EditorGUILayout.PropertyField(typeProp); var cacheType = (OceanDepthCache.OceanDepthCacheType)typeProp.intValue; if (cacheType == OceanDepthCache.OceanDepthCacheType.Realtime) { // Only expose the following if real-time cache type EditorGUILayout.PropertyField(serializedObject.FindProperty("_refreshMode")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_layers")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_resolution")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_cameraMaxTerrainHeight")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_forceAlwaysUpdateDebug")); } else { // Only expose saved cache if non-real-time EditorGUILayout.PropertyField(serializedObject.FindProperty("_savedCache")); } // Draw rest of inspector fields DrawPropertiesExcluding(serializedObject, _propertiesToExclude); // Apply inspector changes serializedObject.ApplyModifiedProperties(); var playing = EditorApplication.isPlaying; var dc = target as OceanDepthCache; var isOnDemand = cacheType == OceanDepthCache.OceanDepthCacheType.Realtime && dc.RefreshMode == OceanDepthCache.OceanDepthCacheRefreshMode.OnDemand; var isBakeable = cacheType == OceanDepthCache.OceanDepthCacheType.Realtime && (!isOnDemand || dc.CacheTexture != null); if ((!playing || isOnDemand) && dc.Type != OceanDepthCache.OceanDepthCacheType.Baked && GUILayout.Button("Populate cache")) { dc.PopulateCache(updateComponents: true); } if (isBakeable && GUILayout.Button("Save cache to file")) { var rt = dc.CacheTexture; RenderTexture.active = rt; Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGBAHalf, false); tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); RenderTexture.active = null; byte[] bytes; bytes = tex.EncodeToEXR(Texture2D.EXRFlags.OutputAsFloat); string path = dc.SavedCache ? AssetDatabase.GetAssetPath(dc.SavedCache) : $"Assets/OceanDepthCache_{Guid.NewGuid()}.exr"; System.IO.File.WriteAllBytes(path, bytes); AssetDatabase.ImportAsset(path); TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; ti.textureType = TextureImporterType.SingleChannel; ti.sRGBTexture = false; ti.alphaSource = TextureImporterAlphaSource.None; ti.alphaIsTransparency = false; ti.SaveAndReimport(); Debug.Log("Cache saved to " + path, AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(path)); } ShowValidationMessages(); }
private void GradientCreator() { GUILayout.Label("Gradient Creator", bigLabel); GUILayout.Space(20); GUILayout.Label("This feature can be used to create textures for the Color Ramp Effect", EditorStyles.boldLabel); EditorGUILayout.GradientField("Gradient", gradient, GUILayout.Height(25)); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Texture Size:", GUILayout.MaxWidth(145)); textureSizes = (TextureSizes)EditorGUILayout.EnumPopup(textureSizes, GUILayout.MaxWidth(200)); } EditorGUILayout.EndHorizontal(); int textureSize = (int)textureSizes; Texture2D gradTex = new Texture2D(textureSize, 1, TextureFormat.RGBA32, false); for (int i = 0; i < textureSize; i++) { gradTex.SetPixel(i, 0, gradient.Evaluate((float)i / (float)textureSize)); } gradTex.Apply(); GUILayout.Space(20); GUILayout.Label("Select the folder where new Gradient Textures will be saved", EditorStyles.boldLabel); HandleSaveFolderEditorPref("All1ShaderGradients", "Assets/AllIn1SpriteShader/Textures/GradientTextures", "Gradient"); string prefSavedPath = PlayerPrefs.GetString("All1ShaderGradients") + "/"; if (Directory.Exists(prefSavedPath)) { EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Gradient Texture Filtering: ", GUILayout.MaxWidth(170)); gradientFiltering = (FilterMode)EditorGUILayout.EnumPopup(gradientFiltering, GUILayout.MaxWidth(200)); } EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Save Gradient Texture")) { string path = EditorUtility.SaveFilePanel("Save texture as PNG", prefSavedPath, "gradientTexture_1.png", "png"); if (path.Length != 0) { byte[] pngData = gradTex.EncodeToPNG(); if (pngData != null) { File.WriteAllBytes(path, pngData); } AssetDatabase.Refresh(); if (path.IndexOf("Assets/") >= 0) { string subPath = path.Substring(path.IndexOf("Assets/")); TextureImporter importer = AssetImporter.GetAtPath(subPath) as TextureImporter; if (importer != null) { Debug.Log("Gradient saved inside the project: " + subPath); importer.filterMode = gradientFiltering; importer.SaveAndReimport(); } } else { Debug.Log("Gradient saved outside the project: " + path); } } } } }
public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) { List <Entry> entries = new List <Entry>(); foreach (int instanceID in textureImporterInstanceIDs) { TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; TextureFormat textureFormat; ColorSpace colorSpace; int compressionQuality; if (ti == null) { continue; } ti.ReadTextureImportInstructions(target, out textureFormat, out colorSpace, out compressionQuality); TextureImporterSettings tis = new TextureImporterSettings(); ti.ReadTextureSettings(tis); Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray(); foreach (Sprite sprite in sprites) { //在这里设置每个图集的参数 Entry entry = new Entry(); entry.sprite = sprite; if (ti.spritePackingTag == "atlasmainex" || ti.spritePackingTag == "atlasaliasex") { entry.settings.format = TextureFormat.RGBA32; } else { #if HighDefinition entry.settings.format = TextureFormat.RGBA32; #else entry.settings.format = TextureFormat.RGBA4444; #endif } entry.settings.colorSpace = colorSpace; entry.settings.compressionQuality = 100; entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear; entry.settings.maxWidth = 2048; entry.settings.maxHeight = 2048; entry.atlasName = ParseAtlasName(ti.spritePackingTag); entry.packingMode = GetPackingMode(ti.spritePackingTag, tis.spriteMeshType); entries.Add(entry); } Resources.UnloadAsset(ti); } // First split sprites into groups based on atlas name var atlasGroups = from e in entries group e by e.atlasName; foreach (var atlasGroup in atlasGroups) { int page = 0; // Then split those groups into smaller groups based on texture settings var settingsGroups = from t in atlasGroup group t by t.settings; foreach (var settingsGroup in settingsGroups) { string atlasName = atlasGroup.Key; if (settingsGroups.Count() > 1) { atlasName += string.Format(" (Group {0})", page); } job.AddAtlas(atlasName, settingsGroup.Key); foreach (Entry entry in settingsGroup) { job.AssignToAtlas(atlasName, entry.sprite, entry.packingMode, SpritePackingRotation.None); } ++page; } } }
public static void Map(RuntimePlatform platform, BuildTarget buildTarget) { string prefabRoot = "Assets/Game/Res/map"; List <string> prefabList = new List <string>(); FindPrefab(prefabRoot, prefabList); string[] dependencies = AssetDatabase.GetDependencies(prefabList.ToArray()); List <string> imageExts = new List <string>(new string[] { ".jpg", ".png", ".tga", ".psd" }); List <string> filterExts = new List <string>(new string[] { ".cs", ".js", ".shader" }); Dictionary <string, List <string> > packerDict = new Dictionary <string, List <string> >(); List <string> otherList = new List <string>(); for (int i = 0; i < dependencies.Length; i++) { string item = dependencies[i]; if (prefabList.IndexOf(item) == -1) { string ext = Path.GetExtension(item); if (imageExts.IndexOf(ext) != -1) { TextureImporter importer = TextureImporter.GetAtPath(item) as TextureImporter; if (importer.textureType == TextureImporterType.Sprite && !string.IsNullOrEmpty(importer.spritePackingTag)) { List <string> list = new List <string>(); if (!packerDict.TryGetValue(importer.spritePackingTag, out list)) { list = new List <string>(); packerDict.Add(importer.spritePackingTag, list); } list.Add(item); } else { otherList.Add(item); } } else if (filterExts.IndexOf(ext) == -1) { otherList.Add(item); } } } AssetBundleBuild[] builds = new AssetBundleBuild[prefabList.Count + otherList.Count + packerDict.Count]; int index = 0; for (int i = 0; i < prefabList.Count; i++) { builds[index] = new AssetBundleBuild(); string assetBundleName = prefabList[i].Replace(prefabRoot + "/", "").ToLower(); assetBundleName = PathUtil.ChangeExtension(assetBundleName, EXT); builds[index].assetBundleName = assetBundleName; builds[index].assetNames = new string[] { prefabList[i] }; index++; } for (int i = 0; i < otherList.Count; i++) { builds[index] = new AssetBundleBuild(); string assetBundleName = otherList[i].Replace(prefabRoot + "/", "").ToLower(); assetBundleName = PathUtil.ChangeExtension(assetBundleName, EXT); builds[index].assetBundleName = assetBundleName; builds[index].assetNames = new string[] { otherList[i] }; index++; } foreach (KeyValuePair <string, List <string> > kvp in packerDict) { builds[index] = new AssetBundleBuild(); string assetBundleName = kvp.Key.ToLower(); assetBundleName = PathUtil.ChangeExtension(assetBundleName, EXT); builds[index].assetBundleName = assetBundleName; builds[index].assetNames = kvp.Value.ToArray(); index++; } string outPath = GetOutRoot(platform, isStreamAssetsPath) + "map"; PathUtil.CheckPath(outPath, false); BuildPipeline.BuildAssetBundles(outPath, builds, BuildAssetBundleOptions.None, buildTarget); AssetDatabase.Refresh(); }
// DO THE ACTUAL SAVE public static void saveParametricObject(AXParametricObject po, bool withInputSubparts, string filepathname) { //Debug.Log(filepathname); //EditorUtility.DisplayDialog("Archimatix Library", "Saving to Library: This may take a few moments.", "Ok"); po.readIntoLibraryFromRelativeAXOBJPath = ArchimatixUtils.getRelativeFilePath(filepathname); Library.recentSaveFolder = System.IO.Path.GetDirectoryName(filepathname); // If this head po has a grouperKey, lose it! // This is because when it is later instantiated, // that grouper may not exist or may not be the desired place for this. po.grouperKey = null; // gather relations as you go... List <AXRelation> rels = new List <AXRelation>(); // BUILD JSON STRING StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.Append("\"parametric_objects\":["); sb.Append(JSONSerializersAX.ParametricObjectAsJSON(po)); // gather rels foreach (AXParameter p in po.parameters) { foreach (AXRelation rr in p.relations) { if (!rels.Contains(rr)) { rels.Add(rr); } } } // SUB NODES if (withInputSubparts) { // GATHER SUB_NODES //Debug.Log("Start gather"); po.gatherSubnodes(); //Debug.Log("End gather"); foreach (AXParametricObject spo in po.subnodes) { //Debug.Log("-- " + spo.Name); sb.Append(',' + JSONSerializersAX.ParametricObjectAsJSON(spo)); // gather rels foreach (AXParameter p in spo.parameters) { foreach (AXRelation rr in p.relations) { if (!rels.Contains(rr)) { rels.Add(rr); } } } } } sb.Append("]"); // add relations to json string thecomma; // RELATIONS if (rels != null && rels.Count > 0) { sb.Append(", \"relations\": ["); // begin parametric_objects thecomma = ""; foreach (AXRelation rr in rels) { sb.Append(thecomma + rr.asJSON()); thecomma = ", "; } sb.Append("]"); } sb.Append("}"); // *** SAVE AS ASSET *** // Since we have added the newItem to the live library, // generating this new file will not force a recreation of the library from the raw JSON file. File.WriteAllText(filepathname, sb.ToString()); // THUMBNAIL TO PNG if (po.is2D()) { Library.cache2DThumbnail(po); } else { Thumbnail.BeginRender(); Thumbnail.render(po, true); Thumbnail.EndRender(); } //string thumb_filename = System.IO.Path.ChangeExtension(filepathname, ".png"); string filename = System.IO.Path.GetFileNameWithoutExtension(filepathname); string prefix = (po.is2D()) ? "zz-AX-2DLib-" : "zz-AX-3DLib-"; string thumb_filename = System.IO.Path.ChangeExtension(filepathname, ".jpg"); thumb_filename = thumb_filename.Replace(filename, prefix + filename); byte[] bytes = po.thumbnail.EncodeToJPG(); //File.WriteAllBytes(libraryFolder + "data/"+ po.Name + ".png", bytes); File.WriteAllBytes(thumb_filename, bytes); //AssetDatabase.Refresh(); string thumbnailRelativePath = ArchimatixUtils.getRelativeFilePath(thumb_filename); //Debug.Log(path); AssetDatabase.ImportAsset(thumbnailRelativePath); TextureImporter importer = AssetImporter.GetAtPath(thumbnailRelativePath) as TextureImporter; if (importer != null) { importer.textureType = TextureImporterType.GUI; importer.maxTextureSize = 256; #if UNITY_5_5_OR_NEWER importer.textureCompression = TextureImporterCompression.Uncompressed; #else importer.textureFormat = TextureImporterFormat.AutomaticTruecolor; #endif } AssetDatabase.WriteImportSettingsIfDirty(thumbnailRelativePath); // Save the recent path to prefs EditorPrefs.SetString("LastLibraryPath", System.IO.Path.GetDirectoryName(filepathname)); EditorUtility.DisplayDialog("Archimatix Library", "ParametricObject saved to " + System.IO.Path.GetDirectoryName(thumbnailRelativePath) + " as " + filename, "Great, thanks!"); Texture2D tex = (Texture2D)AssetDatabase.LoadAssetAtPath(thumbnailRelativePath, typeof(Texture2D)); LibraryItem newItem = new LibraryItem(po); newItem.icon = tex; ArchimatixEngine.library.addLibraryItemToList(newItem); ArchimatixEngine.library.sortLibraryItems(); ArchimatixEngine.saveLibrary(); AssetDatabase.Refresh(); //Debug.Log("yo 2"); //ArchimatixEngine.library.readLibraryFromFiles(); }
private void RefreshLUTLibrary(string[] guids) { foreach (string guid in guids) { string path = AssetDatabase.GUIDToAssetPath(guid); if (Path.GetExtension(path).ToUpper() != ".PNG") { continue; } TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter; if (importer == null) { continue; } bool sizeCheck = (importer.maxTextureSize == 1024); bool filterCheck = (importer.filterMode == FilterMode.Bilinear) || (importer.filterMode == ( FilterMode )(-1)); bool linearCheck = importer.linearTexture; bool mipCheck = !importer.mipmapEnabled; bool anisoCheck = (importer.anisoLevel == 0); bool formatCheck = (importer.textureFormat == TextureImporterFormat.AutomaticTruecolor); bool wrapCheck = (importer.wrapMode == TextureWrapMode.Clamp); bool typeCheck = (importer.textureType == TextureImporterType.Advanced); if (sizeCheck && filterCheck && linearCheck && mipCheck && anisoCheck && formatCheck && wrapCheck && typeCheck) { // strong candidate; final filter at draw string subfolder; if (path.StartsWith("Assets/")) { subfolder = path.Substring(("Assets/").Length); } else { subfolder = path; } int subfolderEndIndex = subfolder.LastIndexOfAny(new char[] { '/', '\\' }); string category; if (subfolderEndIndex > 0) { category = subfolder.Substring(0, subfolderEndIndex).Replace("/", " / "); } else { category = "Miscellaneous"; } if (!string.IsNullOrEmpty(category)) { HashSet <string> categorySet = null; if (!m_categories.TryGetValue(category, out categorySet)) { categorySet = new HashSet <string>(); m_categories.Add(category, categorySet); } if (!categorySet.Contains(path)) { categorySet.Add(path); } } } } }
void Start() { /* - We set the empty texture to the inputTex (this might create a copy by reference problem) - We set the renderer of the gameobject this script is attached to, to the texture (input texture) - We set the pix array of Colors to the texture of the texture (input texture) */ /* - This is not used really/anymore - We create a TextureImporter which looks at a specific picture for when chaning its settings. - The idea is to automatically change the settings of a picture but failed. - Sets the settings to "Advanced", EncodeRGB to "off", Read/Write enabled, disable mipMap, compression to RGBA32, FilterMode to Point, and remove N^2 Scale. */ importer = AssetImporter.GetAtPath("Assets/Resources/16.png") as TextureImporter; importerSettings = new TextureImporterSettings(); importerSettings.rgbm = TextureImporterRGBMMode.Off; importer.SetTextureSettings(importerSettings); importer.textureType = TextureImporterType.Advanced; importer.isReadable = true; importer.mipmapEnabled = false; importer.textureFormat = TextureImporterFormat.RGBA32; importer.filterMode = FilterMode.Point; importer.npotScale = TextureImporterNPOTScale.None; texture = new Texture2D(inputTex.width, inputTex.height, TextureFormat.RGBA32, false); Color[,] image = PreProcessing.Instance.GetPixels2D(inputTex); image = PreProcessing.Instance.threshGrey(image); image = PreProcessing.Instance.threshRGB(image); image = PreProcessing.Instance.RGBErodeBlack(image); image = PreProcessing.Instance.spawnDetection(image); image = PreProcessing.Instance.batteryDetection(image); image = PreProcessing.Instance.LaserBlobExtraction(image); image = PreProcessing.Instance.laserDetection(image); image = PreProcessing.Instance.goalDetection(image); PreProcessing.Instance.SetPixels2D(image, texture); this.GetComponent<Renderer>().material.mainTexture = texture; /* - Both of our 2D arrays of integers take the height and width of the image pixels - The array of tags gets 10 pixels worth of padding, otherwise it will go out of bounds later */ int pixIndexCounter = 0; int[] pixIndexX; int[] pixIndexY; for (int w = 1; w < texture.width; w++) { for (int h = 1; h < texture.height; h++) { if (image[w, h].r == 0f) { pixIndexCounter++; } } } pixIndexX = new int[pixIndexCounter]; pixIndexY = new int[pixIndexCounter]; int counter3 = 0; for (int w = 1; w < texture.width; w++) { for (int h = 1; h < texture.height; h++) { if (image[w, h].r == 0f) { pixIndexY[counter3] = h; pixIndexX[counter3] = w; counter3++; } } } /* - We create empty GameObjects based on how many cubes there are divided by 1000. - Then we create 1 more assigned for the last cubes that did not come in 1000 - These are the parents of the cubes. */ parents = new GameObject[(pixIndexCounter / 1000) + 1]; for (int p = 0; p < parents.Length; p++) { parents[p] = (GameObject)Instantiate(Resources.Load("walls")); parents[p].name = "Parent"; } int parentCounter = 0; int countTo1000 = 0; for (int h = 0; h < pixIndexY.Length; h++) { GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.position = new Vector3(pixIndexX[h], 12.4f, pixIndexY[h]); cube.transform.localScale = new Vector3(1, 25, 1); cube.transform.parent = parents[parentCounter].transform; countTo1000++; if (countTo1000 == 1000) { parentCounter++; countTo1000 = 0; } } /* - */ for (int p = 0; p < parents.Length; p++) { parents[p].GetComponent<MeshFilter>().mesh = parents[p].GetComponent<Mesh>(); parents[p].AddComponent<combineMesh>(); } /* - Destroys all the "children" meaning that we delete all individual cubes after they all have went through MeshCombine() */ for (int p = 0; p < parents.Length; p++) { foreach (Transform child in parents[p].transform) { GameObject.Destroy(child.gameObject); } } }
private void ResourcesList() { LibaryResourceSetting _resourseSetting = Resources.Load <LibaryResourceSetting>("ResourceLibarySetting"); if (_resourseSetting == null) { return; } string path = AssetDatabase.GetAssetPath(_resourseSetting); LibaryResourceSetting resourseSetting = AssetDatabase.LoadAssetAtPath <LibaryResourceSetting>(path); Dictionary <string, Dictionary <string, ResourceSettingStateObj> > msgDict = resourseSetting.GetSettingMessage(); resourseSetting.Clear(); List <string> listRes = ResLibaryTool.GetAllLocalResourceDirs(Application.dataPath); List <string> ret = new List <string>(); for (int i = 0; i < listRes.Count; i++) { List <string> list = ResLibaryTool.GetAllSubDirs(listRes[i]); if (list != null) { ret.AddRange(list); } } ret.AddRange(listRes); Debug.Log("ret:" + ret.Count); for (int i = 0; i < ret.Count; i++) { string resDir = ret[i]; if (string.IsNullOrEmpty(resDir) || !ResLibaryTool.DirExistResource(resDir)) { continue; } string[] files = System.IO.Directory.GetFiles(resDir); for (int j = 0; j < files.Length; j++) { string resfile = files[j]; string extension = Path.GetExtension(resfile); if (!ResLibaryConfig.ResourceExts.Contains(extension)) { continue; } resfile = ResLibaryTool.GetAssetRelativePath(resfile); int index = resfile.IndexOf("Resources/", StringComparison.CurrentCultureIgnoreCase); if (index < 0) { continue; } string filePath = resfile.Substring(index); filePath = filePath.Replace("Resources/", ""); if (Path.HasExtension(filePath)) { filePath = filePath.Replace(extension, ""); } UnityEngine.Object obj = Resources.Load(filePath); if (!ResLibaryConfig.ExistType.ContainsValue(obj.GetType().Name)) { continue; } if (obj.GetType().Name == ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Texture2D]) { TextureImporter textureImporter = TextureImporter.GetAtPath(resfile) as TextureImporter; if (textureImporter.textureType == TextureImporterType.Sprite) { Dictionary <string, ResourceSettingStateObj> sDict = null; msgDict.TryGetValue(ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Sprite], out sDict); UnityEngine.Object[] sprs = AssetDatabase.LoadAllAssetsAtPath(resfile); for (int k = 0; k < sprs.Length; k++) { ResourceSettingStateObj settingStateObjs = new ResourceSettingStateObj(); settingStateObjs.m_Name = sprs[k].name; settingStateObjs.m_Path = filePath + "/" + sprs[k].name; settingStateObjs.m_Type = ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Sprite]; if (sprs[k].GetType().Name == ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Sprite]) { if (sDict != null && sDict.ContainsKey(sprs[k].name)) { resourseSetting.AddResToLibary(sDict[sprs[k].name]); continue; } resourseSetting.AddResToLibary(settingStateObjs); } else { Dictionary <string, ResourceSettingStateObj> sDictT = null; msgDict.TryGetValue(ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Texture2D], out sDictT); if (sDictT != null && sDictT.ContainsKey(sprs[k].name)) { resourseSetting.AddResToLibary(sDictT[sprs[k].name]); continue; } settingStateObjs.m_Path = filePath; settingStateObjs.m_Type = ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Texture2D]; resourseSetting.AddResToLibary(settingStateObjs); } } } else { Dictionary <string, ResourceSettingStateObj> sDict = null; msgDict.TryGetValue(ResLibaryConfig.ExistType[LibaryTypeEnum.LibaryType_Texture2D], out sDict); if (sDict != null && sDict.ContainsKey(obj.name)) { resourseSetting.AddResToLibary(sDict[obj.name]); continue; } ResourceSettingStateObj settingStateObj = new ResourceSettingStateObj(); settingStateObj.m_Name = obj.name; settingStateObj.m_Path = filePath; settingStateObj.m_Type = obj.GetType().Name; settingStateObj.m_ExistStatus = AssetExistStatusEnum.Quote; resourseSetting.AddResToLibary(settingStateObj); } } else { Dictionary <string, ResourceSettingStateObj> sDict = null; msgDict.TryGetValue(obj.GetType().Name, out sDict); if (sDict != null && sDict.ContainsKey(obj.name)) { resourseSetting.AddResToLibary(sDict[obj.name]); continue; } ResourceSettingStateObj settingStateObj = new ResourceSettingStateObj(); settingStateObj.m_Name = obj.name; settingStateObj.m_Path = filePath; settingStateObj.m_Type = obj.GetType().Name; settingStateObj.m_ExistStatus = AssetExistStatusEnum.Quote; resourseSetting.AddResToLibary(settingStateObj); } } } AssetDatabase.ImportAsset(path); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); }
void SetMaskImportSettings(TextureImporter importer) { #if UNITY_5_5_OR_NEWER importer.textureType = TextureImporterType.SingleChannel; //importer.alphaUsage = TextureImporterAlphaUsage.FromGrayScale; importer.alphaSource = TextureImporterAlphaSource.FromGrayScale; importer.textureCompression = TextureImporterCompression.Uncompressed; #else importer.textureType = TextureImporterType.Advanced; importer.grayscaleToAlpha = true; importer.textureFormat = TextureImporterFormat.Alpha8; #endif importer.anisoLevel = 0; importer.mipmapEnabled = false; importer.wrapMode = TextureWrapMode.Clamp; importer.SaveAndReimport(); }
public void drawOverviewGUI() { NGUIEditorTools.DrawHeader("文件详情"); using (new EditorGUILayout.HorizontalScope()) { GUILayout.Label("筛选:"); selectAssetType = EditorGUILayout.Popup(selectAssetType, AssetAllTypes); GUILayout.FlexibleSpace(); if (GUILayout.Button("关闭MipMaps", GUILayout.Width(100F))) { List <TextureBean> _textures = new List <TextureBean>(); for (int i = 0; i < assetList.Count; i++) { if (selectAssetType != 0 && !assetList[i].AssetDesc.Equals(AssetAllTypes[selectAssetType])) { continue; } if (!assetList[i].MipMaps) { continue; } _textures.Add(assetList[i]); } for (int i = 0; i < _textures.Count; i++) { EditorUtility.DisplayProgressBar("Hold On", "正在自动处理...", i / (float)_textures.Count); TextureImporter texImp = AssetImporter.GetAtPath(_textures[i].FilePath) as TextureImporter; texImp.mipmapEnabled = false; _textures[i].MipMaps = false; } EditorUtility.ClearProgressBar(); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } if (GUILayout.Button("刷新", GUILayout.Width(80))) { findAllTextures(); } GUILayout.Space(10); } GUILayout.Space(5); GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f)); if (GUILayout.Toggle(false, "名称", "ButtonLeft", GUILayout.MaxWidth(200f))) { sortName *= -1; assetList.Sort((x, y) => x.Name.CompareTo(y.Name) * sortName); } GUILayout.Toggle(false, "资源类型", "ButtonMid", GUILayout.MinWidth(100F)); if (GUILayout.Toggle(false, "宽度", "ButtonMid", GUILayout.MinWidth(80f))) { sortWidth *= -1; assetList.Sort((x, y) => x.Width.CompareTo(y.Width) * sortWidth); } if (GUILayout.Toggle(false, "高度", "ButtonMid", GUILayout.MinWidth(80f))) { sortHeight *= -1; assetList.Sort((x, y) => x.Height.CompareTo(y.Height) * sortHeight); } GUILayout.Toggle(false, "MipMaps", "ButtonMid", GUILayout.MinWidth(100f)); if (GUILayout.Toggle(false, "MaxSize", "ButtonMid", GUILayout.MinWidth(80F))) { sortMaxSize *= -1; assetList.Sort((x, y) => x.MaxSize.CompareTo(y.MaxSize) * sortMaxSize); } GUILayout.Toggle(false, "压缩格式", "ButtonMid", GUILayout.MinWidth(100F)); if (GUILayout.Toggle(false, "内存消耗", "ButtonRight", GUILayout.MinWidth(100F))) { sortMemorySize *= -1; assetList.Sort((x, y) => x.MemorySize.CompareTo(y.MemorySize) * sortMemorySize); } GUILayout.Space(10); GUILayout.EndHorizontal(); scrollPos = GUILayout.BeginScrollView(scrollPos); int index = 0; for (int i = 0; i < assetList.Count; i++) { if (selectAssetType != 0 && !assetList[i].AssetDesc.Equals(AssetAllTypes[selectAssetType])) { continue; } GUI.backgroundColor = index % 2 == 1 ? Color.white : new Color(0.8f, 0.8f, 0.8f); GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f)); GUI.backgroundColor = Color.white; drawRow(index, assetList[i]); GUILayout.EndHorizontal(); index++; } GUILayout.EndScrollView(); }
public Mesh CreateMeshFromVerts(Vector3[] vertsToCopy, Mesh mesh, List<int> pathSplitIds, Transform SpriteGO = null) { Sprite spr = new Sprite(); Rect rec = new Rect(); Vector3 bound = Vector3.zero; TextureImporter textureImporter = new TextureImporter(); if(SpriteGO !=null && SpriteGO.GetComponent<SpriteRenderer>() && SpriteGO.GetComponent<SpriteRenderer>().sprite) { spr = SpriteGO.GetComponent<SpriteRenderer>().sprite; rec = spr.rect; bound = SpriteGO.GetComponent<Renderer>().bounds.max- SpriteGO.GetComponent<Renderer>().bounds.min ; textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(spr)) as TextureImporter; } //Create triangle.NET geometry TriangleNet.Geometry.InputGeometry geometry = new TriangleNet.Geometry.InputGeometry(vertsToCopy.Length); //Add vertices foreach (Vector3 p in vertsToCopy) { geometry.AddPoint(p.x,p.y); } //Add segments int prevEnd = 0; for (int i=0;i<vertsToCopy.Length-1;i++) { if (!pathSplitIds.Contains (i+1)) { geometry.AddSegment (i, i + 1); //Debug.Log ("joining " + i + " to " + (i + 1)); } else { geometry.AddSegment (i, prevEnd); prevEnd = i + 1; } } if (pathSplitIds.Count <= 1) { //Debug.Log ("joining " + (vertsToCopy.Length - 1) + " to 0"); geometry.AddSegment(vertsToCopy.Length - 1, 0); } //Triangulate, refine and smooth TriangleNet.Mesh triangleNetMesh = new TriangleNet.Mesh(); triangleNetMesh.Triangulate(geometry); //transform vertices Vector3[] vertices = new Vector3[triangleNetMesh.Vertices.Count]; Vector2[] uvs = new Vector2[triangleNetMesh.Vertices.Count]; Vector3[] normals = new Vector3[triangleNetMesh.Vertices.Count]; int idx = 0; foreach(TriangleNet.Data.Vertex v in triangleNetMesh.Vertices) { vertices[idx] = new Vector3( (float)v.X, (float)v.Y, 0 ); normals[idx]=new Vector3(0,0,-1); if (SpriteGO != null && SpriteGO.GetComponent<SpriteRenderer>() ) { Vector2 newUv = new Vector2 (((float)v.X / bound.x) + 0.5f , ((float)v.Y / bound.y) + 0.5f); newUv.x *= rec.width / spr.texture.width; newUv.y *= rec.height / spr.texture.height; //Debug.Log(spr.textureRectOffset); newUv.x += (rec.x) / spr.texture.width; newUv.y += (rec.y) / spr.texture.height; SpriteMetaData[] smdArray = textureImporter.spritesheet; Vector2 pivot = new Vector2 (.0f, .0f); ; for (int i = 0; i < smdArray.Length; i++) { if (smdArray [i].name == spr.name) { switch (smdArray [i].alignment) { case(0): smdArray [i].pivot = Vector2.zero; break; case(1): smdArray [i].pivot = new Vector2 (0f, 1f) - new Vector2 (.5f, .5f); break; case(2): smdArray [i].pivot = new Vector2 (0.5f, 1f) - new Vector2 (.5f, .5f); break; case(3): smdArray [i].pivot = new Vector2 (1f, 1f) - new Vector2 (.5f, .5f); break; case(4): smdArray [i].pivot = new Vector2 (0f, .5f) - new Vector2 (.5f, .5f); break; case(5): smdArray [i].pivot = new Vector2 (1f, .5f) - new Vector2 (.5f, .5f); break; case(6): smdArray [i].pivot = new Vector2 (0f, 0f) - new Vector2 (.5f, .5f); break; case(7): smdArray [i].pivot = new Vector2 (0.5f, 0f) - new Vector2 (.5f, .5f); break; case(8): smdArray [i].pivot = new Vector2 (1f, 0f) - new Vector2 (.5f, .5f); break; case(9): smdArray [i].pivot -= new Vector2 (.5f, .5f); break; } pivot = smdArray [i].pivot; } } if (textureImporter.spriteImportMode == SpriteImportMode.Single) pivot = textureImporter.spritePivot - new Vector2 (.5f, .5f); newUv.x += ((pivot.x) * rec.width) / spr.texture.width; newUv.y += ((pivot.y) * rec.height) / spr.texture.height; uvs [idx] = newUv; } idx++; } //transform triangles int[] triangles = new int[triangleNetMesh.Triangles.Count*3]; idx = 0; foreach (TriangleNet.Data.Triangle t in triangleNetMesh.Triangles) { triangles[idx++] = t.P1; triangles[idx++] = t.P0; triangles[idx++] = t.P2; } mesh.vertices = vertices; mesh.triangles = triangles; mesh.uv = uvs; mesh.normals = normals; return mesh; }
void OnGUI() { GUILayout.Space(20); GUILayout.BeginHorizontal(); replaceRedundantTextures = EditorGUILayout.Toggle("Replace redundant", replaceRedundantTextures); GUILayout.Space(20); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); processOpacity = EditorGUILayout.Toggle("Process opacity", processOpacity); GUILayout.Space(20); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Assign textures")) { float timeBegin = Time.realtimeSinceStartup; List <string> skipMaterialList = new List <string>(); redundantTextureAmount = 0; assignedTextureAmount = 0; //Get all textures in the entire project. List <string> texturePathsList = GetTextures(); Debug.Log(texturePathsList.Count + " textures found."); bool[] uniqueTextures = TagUniqueTextures(texturePathsList); //Get all the game objects in the scene. GameObject[] gameObjects = FindObjectsOfType(typeof(GameObject)) as GameObject[]; //Loop through the game objects for (int i = 0; i < gameObjects.Length; i++) { if (gameObjects[i].GetComponent <Renderer>() != null) { //Get the materials on a mesh (can be more than one). Material[] materials = gameObjects[i].GetComponent <Renderer>().sharedMaterials; for (int matIndex = 0; matIndex < materials.Length; matIndex++) { Material material = materials[matIndex]; if (material != null) { //Has the material been processed before and is it unique? bool skipMaterial = IsSkipMaterial(skipMaterialList, material); if (!skipMaterial) { //Find the matching texture folder for the object. string folder = FindObjectTextureFolder(gameObjects[i]); //A folder with textures for the object is found. if (folder != "") { //Longest execution time. bool textureFound = AssignFolderTexturesToObject(gameObjects[i], folder); if (textureFound) { //Are all textures for the object unique? bool unique = AreAllObjectTexturesUnique(gameObjects[i], folder, texturePathsList, uniqueTextures); if (unique) { //This material has been processed and its textures are unique, so skip it next time. skipMaterialList.Add(material.name); } else { //Do this after assigning the textures because making the material unique changes the //name, causing name matching to fail. MakeMaterialUnique(gameObjects[i]); } } //The textures for the object are not found in the folder, so they might be elsewhere in the project. //In this case it is safe to assume the textures are unique. else { //Assign the textures to the material of the object, trying all textures in the project. AssignTexturePathListToObject(gameObjects[i], material, matIndex, texturePathsList); skipMaterialList.Add(material.name); } } //Texture folder not found. //In this case it is safe to assume the textures are unique. else { //Assign the textures to the material of the object, trying all textures in the project. AssignTexturePathListToObject(gameObjects[i], material, matIndex, texturePathsList); skipMaterialList.Add(material.name); } } } } } } Debug.Log(redundantTextureAmount + " redundant textures replaced with a color or value."); Debug.Log(assignedTextureAmount + " textures assigned."); float timeEnd = Time.realtimeSinceStartup; PrintTimeDifference(timeBegin, timeEnd); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Assign to selected object")) { float timeBegin = Time.realtimeSinceStartup; redundantTextureAmount = 0; assignedTextureAmount = 0; GameObject selectedObject = null; List <string> texturePathsList = GetTextures(); //Get the selected game objects. UnityEngine.Object[] objects = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel); //An object is selected and textures are available. if ((objects.Length != 0) && (texturePathsList.Count >= 1)) { Debug.Log(texturePathsList.Count + " textures found."); //Get the selected object. if (objects[0] is GameObject) { selectedObject = (GameObject)objects[0]; Material[] materials = selectedObject.GetComponent <Renderer>().sharedMaterials; for (int matIndex = 0; matIndex < materials.Length; matIndex++) { Material material = materials[matIndex]; if (material != null) { bool textureFound = AssignTexturePathListToObject(selectedObject, material, matIndex, texturePathsList); if (textureFound) { //Do this after assigning the textures because making the material unique changes the //name, causing name matching to fail. MakeMaterialUnique(selectedObject); } else { Debug.Log("No matching textures found for material " + material.name); } } } } } if (objects.Length == 0) { Debug.Log("Select an object first."); } Debug.Log(redundantTextureAmount + " redundant textures replaced with a color or value."); Debug.Log(assignedTextureAmount + " textures assigned."); float timeEnd = Time.realtimeSinceStartup; PrintTimeDifference(timeBegin, timeEnd); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Make material unique")) { //Get the selected game object. UnityEngine.Object[] objects = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel); //An object is selected. if (objects.Length != 0) { if (objects[0] is GameObject) { //Get the selected object. GameObject selectedObject = (GameObject)objects[0]; MakeMaterialUnique(selectedObject); } } else { Debug.Log("Select an object first."); } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (GUILayout.Button("Crunch")) { float timeBegin = Time.realtimeSinceStartup; List <string> texturePathsList = GetTextures(); //Loop through all the textures. for (int i = 0; i < texturePathsList.Count; i++) { TextureImporter importer = AssetImporter.GetAtPath(texturePathsList[i]) as TextureImporter; importer.crunchedCompression = true; importer.compressionQuality = 100; //Apply the texture importer settings. AssetDatabase.WriteImportSettingsIfDirty(texturePathsList[i]); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); } float timeEnd = Time.realtimeSinceStartup; PrintTimeDifference(timeBegin, timeEnd); } GUILayout.Space(20); GUILayout.EndHorizontal(); }
static void updateSpriteMetaData (TextureImporter importer, string pathToData) { string nom = pathToData; string pattern = @"[^/]+$"; Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = rgx.Matches(nom); nom = matches[ 0 ].Value.Replace( ".tpsheet", "" ); int textureWidth = 0; int textureHeight = 0; BorderTextureData scriptableObj = ScriptableObject.CreateInstance<BorderTextureData>(); scriptableObj.idName = nom; scriptableObj.names = new List<string>(); scriptableObj.rects = new List<Rect>(); scriptableObj.names.Add( "64" ); scriptableObj.rects.Add( new Rect( 0, 0, 0, 0 ) ); // if (importer.textureType != TextureImporterType.Advanced) { importer.textureType = TextureImporterType.Sprite; } importer.maxTextureSize = 4096; importer.spriteImportMode = SpriteImportMode.Multiple; string[] dataFileContent = File.ReadAllLines(pathToData); int format = 30302; foreach (string row in dataFileContent) { if (row.StartsWith(":format=")) { format = int.Parse(row.Remove(0,8)); } else if( row.StartsWith("#SZW ")) textureWidth = int.Parse( row.Replace( "#SZW", "" ) ); else if( row.StartsWith("#SZH ")) textureHeight = int.Parse( row.Replace( "#SZH", "" ) ); } if (format != 30302) { EditorUtility.DisplayDialog("Please update TexturePacker Importer", "Your TexturePacker Importer is too old, \nplease load a new version from the asset store!", "Ok"); return; } List<SpriteMetaData> metaData = new List<SpriteMetaData> (); foreach (string row in dataFileContent) { if (string.IsNullOrEmpty (row) || row.StartsWith ("#") || row.StartsWith (":")) continue; // comment lines start with #, additional atlas properties with : string [] cols = row.Split (';'); if (cols.Length < 7) return; // format error SpriteMetaData smd = new SpriteMetaData (); smd.name = cols [0].Replace ("/", "-"); // unity has problems with "/" in sprite names... float x = float.Parse (cols [1]); float y = float.Parse (cols [2]); float w = float.Parse (cols [3]); float h = float.Parse (cols [4]); float px = float.Parse (cols [5]); float py = float.Parse (cols [6]); smd.rect = new UnityEngine.Rect (x, y, w, h); smd.pivot = new UnityEngine.Vector2 (px, py); scriptableObj.names.Add( smd.name ); scriptableObj.rects.Add( smd.rect ); if (px == 0 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomLeft; else if (px == 0.5 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomCenter; else if (px == 1 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomRight; else if (px == 0 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.LeftCenter; else if (px == 0.5 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.Center; else if (px == 1 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.RightCenter; else if (px == 0 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopLeft; else if (px == 0.5 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopCenter; else if (px == 1 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopRight; else smd.alignment = (int)UnityEngine.SpriteAlignment.Custom; metaData.Add (smd); } scriptableObj.textureWidth = textureWidth; scriptableObj.textureHeight = textureHeight; AssetDatabase.CreateAsset( scriptableObj, "Assets/CivGrid/Borders/" + nom + ".asset" ); AssetDatabase.SaveAssets(); EditorUtility.FocusProjectWindow(); Selection.activeObject = scriptableObj; // assign the scriptable object here importer.spritesheet = metaData.ToArray(); }
void AssignTexture(GameObject selectedObject, Material material, int matIndex, Texture2D texture, string texturePath, string textureExtension) { Color32[] pixelArray = null; bool rgbaSame = false; bool metalSame = false; bool smoothnessSame = false; Color32 rgbaColor; float metallicValue; float smoothnessValue; TextureImporter importer = AssetImporter.GetAtPath(texturePath) as TextureImporter; //Set the maximum texture size. importer.maxTextureSize = maxTextureSize; if (replaceRedundantTextures || processOpacity) { //Set the texture to readable to enable GetPixels. Note that the texture will consume much more memory //because of this. Set it to non-readable when done. importer.isReadable = true; //Apply the texture importer settings. AssetDatabase.WriteImportSettingsIfDirty(texturePath); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); //Convert the texture to an array of colors. pixelArray = texture.GetPixels32(); } switch (textureExtension) { case albedoExtension: if (replaceRedundantTextures == true) { IsRGBASame(out rgbaSame, out rgbaColor, pixelArray); if (rgbaSame) { //Remove texture. material.SetTexture(albedoTextureID, null); //Set a uniform color. material.SetColor(albedoColorID, rgbaColor); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && (rgbaSame == false))) { //Assign the texture material.SetTexture(albedoTextureID, texture); //This is important, otherwise the texture will look wrong if a texture is used). material.SetColor(albedoColorID, Color.white); assignedTextureAmount++; } if (processOpacity) { bool alphaPresent = IsAlphaPresent(pixelArray); if (alphaPresent) { SetTransparent(material); } else { SetOpaque(material); } } break; case metallicExtension: if (replaceRedundantTextures == true) { //The metallic texture contains both a metallic and smoothness value. IsMetallicSame(out metalSame, out metallicValue, pixelArray); IsSmoothnessSame(out smoothnessSame, out smoothnessValue, pixelArray); if (metalSame && smoothnessSame) { //Remove texture. material.SetTexture(metallicTextureID, null); //Set the metal slider. material.SetFloat(metallicSliderID, metallicValue); //Set the smoothness slider. material.SetFloat(smoothnessSliderID, smoothnessValue); material.DisableKeyword(metallicKeyword); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && !(metalSame && smoothnessSame))) { material.EnableKeyword(metallicKeyword); material.SetTexture(metallicTextureID, texture); assignedTextureAmount++; } break; case specularExtension: if (replaceRedundantTextures == true) { //The specular texture contains both a specular and smoothness value. IsRGBASame(out rgbaSame, out rgbaColor, pixelArray); IsSmoothnessSame(out smoothnessSame, out smoothnessValue, pixelArray); if (rgbaSame && smoothnessSame) { //Remove texture. material.SetTexture(specularTextureID, null); //Set the specular color. material.SetColor(specularColorID, rgbaColor); //Set the smoothness slider. material.SetFloat(smoothnessSliderID, smoothnessValue); material.DisableKeyword(specularKeyword); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && !(rgbaSame && smoothnessSame))) { material.EnableKeyword(specularKeyword); material.SetTexture(specularTextureID, texture); assignedTextureAmount++; } break; case normalExtension: if (replaceRedundantTextures == true) { IsRGBASame(out rgbaSame, out rgbaColor, pixelArray); if (rgbaSame) { //Remove texture. material.SetTexture(normalTextureID, null); material.DisableKeyword(normalKeyword); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && (rgbaSame == false))) { material.EnableKeyword(normalKeyword); //A normal map should be marked as a normal map. importer.textureType = TextureImporterType.NormalMap; AssetDatabase.WriteImportSettingsIfDirty(texturePath); material.SetTexture(normalTextureID, texture); assignedTextureAmount++; UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); } break; case heightExtension: if (replaceRedundantTextures == true) { IsRGBASame(out rgbaSame, out rgbaColor, pixelArray); if (rgbaSame) { //Remove texture. material.SetTexture(heightTextureID, null); material.DisableKeyword(heightKeyword); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && (rgbaSame == false))) { material.EnableKeyword(heightKeyword); material.SetTexture(heightTextureID, texture); assignedTextureAmount++; } break; case occlusionExtension: if (replaceRedundantTextures == true) { IsRGBASame(out rgbaSame, out rgbaColor, pixelArray); if (rgbaSame) { //Remove texture. material.SetTexture(occlusionTextureID, null); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && (rgbaSame == false))) { material.SetTexture(occlusionTextureID, texture); assignedTextureAmount++; } break; case emissionExtension: if (replaceRedundantTextures == true) { IsRGBASame(out rgbaSame, out rgbaColor, pixelArray); if (rgbaSame) { //The emission shader keyword has to be enabled even if no texture is used, //otherwise the shader won't refresh. material.EnableKeyword(emissionKeyword); //Remove texture. material.SetTexture(emissionTextureID, null); material.SetColor(emissionColorID, rgbaColor); redundantTextureAmount++; } } if ((replaceRedundantTextures == false) || ((replaceRedundantTextures == true) && (rgbaSame == false))) { material.EnableKeyword(emissionKeyword); material.SetTexture(emissionTextureID, texture); assignedTextureAmount++; //This is important, otherwise the texture will look wrong if a texture is used). material.SetColor(emissionColorID, Color.white); } break; default: break; } selectedObject.GetComponent <Renderer>().sharedMaterials[matIndex] = material; if (replaceRedundantTextures || processOpacity) { //Set the texture to non-readable again, to free up memory. importer.isReadable = false; AssetDatabase.WriteImportSettingsIfDirty(texturePath); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); } }
// Texture processing End public static void SetDefaultTextureImporterSettings(TextureImporter a_rTextureImporter) { //Debug.Log("Set Deafult Importer Settings"); a_rTextureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; }
//================================================================================ // 関数 //================================================================================ /// <summary> /// 指定された TextureImporter に設定を適用します /// </summary> public void Apply(TextureImporter importer) { var settings = new UnityEditor.TextureImporterSettings(); importer.ReadTextureSettings(settings); if (m_textureType.IsOverride) { settings.textureType = m_textureType.Value; } if (m_textureShape.IsOverride) { settings.textureShape = m_textureShape.Value; } if (m_spritePixelsPerUnit.IsOverride) { settings.spritePixelsPerUnit = m_spritePixelsPerUnit.Value; } if (m_spriteMeshType.IsOverride) { settings.spriteMeshType = m_spriteMeshType.Value; } if (m_spriteExtrude.IsOverride) { settings.spriteExtrude = m_spriteExtrude.Value; } if (m_spriteAlignment.IsOverride) { settings.spriteAlignment = ( int )m_spriteAlignment.Value; } if (m_spritePivot.IsOverride) { settings.spritePivot = m_spritePivot.Value; } if (m_spriteGenerateFallbackPhysicsShape.IsOverride) { settings.spriteGenerateFallbackPhysicsShape = m_spriteGenerateFallbackPhysicsShape.Value; } if (m_sRGBTexture.IsOverride) { settings.sRGBTexture = m_sRGBTexture.Value; } if (m_alphaSource.IsOverride) { settings.alphaSource = m_alphaSource.Value; } if (m_alphaIsTransparency.IsOverride) { settings.alphaIsTransparency = m_alphaIsTransparency.Value; } if (m_npotScale.IsOverride) { settings.npotScale = m_npotScale.Value; } if (m_readable.IsOverride) { settings.readable = m_readable.Value; } if (m_streamingMipmaps.IsOverride) { settings.streamingMipmaps = m_streamingMipmaps.Value; } if (m_streamingMipmapsPriority.IsOverride) { settings.streamingMipmapsPriority = m_streamingMipmapsPriority.Value; } if (m_mipmapEnabled.IsOverride) { settings.mipmapEnabled = m_mipmapEnabled.Value; } if (m_borderMipmap.IsOverride) { settings.borderMipmap = m_borderMipmap.Value; } if (m_mipmapFilter.IsOverride) { settings.mipmapFilter = m_mipmapFilter.Value; } if (m_mipMapsPreserveCoverage.IsOverride) { settings.mipMapsPreserveCoverage = m_mipMapsPreserveCoverage.Value; } if (m_alphaTestReferenceValue.IsOverride) { settings.alphaTestReferenceValue = m_alphaTestReferenceValue.Value; } if (m_fadeOut.IsOverride) { settings.fadeOut = m_fadeOut.Value; } if (m_mipmapFadeDistanceStart.IsOverride) { settings.mipmapFadeDistanceStart = m_mipmapFadeDistanceStart.Value; } if (m_mipmapFadeDistanceEnd.IsOverride) { settings.mipmapFadeDistanceEnd = m_mipmapFadeDistanceEnd.Value; } if (m_wrapMode.IsOverride) { settings.wrapMode = m_wrapMode.Value; } if (m_filterMode.IsOverride) { settings.filterMode = m_filterMode.Value; } if (m_aniso.IsOverride) { settings.aniso = m_aniso.Value; } if (m_defaultSettings != null) { var platformSettings = importer.GetPlatformTextureSettings("DefaultTexturePlatform"); m_defaultSettings.Apply(platformSettings); importer.SetPlatformTextureSettings(platformSettings); } if (m_standaloneSettings != null) { var platformSettings = importer.GetPlatformTextureSettings("Standalone"); m_standaloneSettings.Apply(platformSettings); importer.SetPlatformTextureSettings(platformSettings); } if (m_iPhoneSettings != null) { var platformSettings = importer.GetPlatformTextureSettings("iPhone"); platformSettings.overridden = true; m_iPhoneSettings.Apply(platformSettings); importer.SetPlatformTextureSettings(platformSettings); } if (m_androidSettings != null) { var platformSettings = importer.GetPlatformTextureSettings("Android"); m_androidSettings.Apply(platformSettings); importer.SetPlatformTextureSettings(platformSettings); } if (m_webGLSettings != null) { var platformSettings = importer.GetPlatformTextureSettings("WebGL"); m_webGLSettings.Apply(platformSettings); importer.SetPlatformTextureSettings(platformSettings); } importer.SetTextureSettings(settings); // TextureImporterSettings は Sprite Mode のパラメータを持っていないため // TextureImporter で設定する必要がある // また、Sprite Mode は SetTextureSettings の後に設定しないと反映されないので // SetTextureSettings の後に設定するようにしています if (m_spriteImportMode.IsOverride) { importer.spriteImportMode = m_spriteImportMode.Value; } }
// Texture processing End public static void TextureProcessingEnd(TextureImporter a_rTextureImporter, TextureImporterSettings a_rTextureImporterSettings) { if(a_rTextureImporter != null) { a_rTextureImporter.SetTextureSettings(a_rTextureImporterSettings); if(AssetDatabase.WriteImportSettingsIfDirty(a_rTextureImporter.assetPath)) { AssetDatabase.ImportAsset(a_rTextureImporter.assetPath); AssetDatabase.Refresh(); } } Uni2DEditorSpriteAssetPostProcessor.Enabled = true; }
public override ParticleDesignerProcessorResult Process(ParticleDesignerContent input, ContentProcessorContext context) { logger = context.Logger; var result = new ParticleDesignerProcessorResult(); // check for an embedded tiff texture if (input.emitterConfig.texture.data != null) { context.Logger.LogMessage("pex file has an embedded tiff. Extracting now."); using (var memoryStream = new MemoryStream(Convert.FromBase64String(input.emitterConfig.texture.data), writable: false)) { using (var stream = new GZipStream(memoryStream, CompressionMode.Decompress)) { const int size = 4096; byte[] buffer = new byte[size]; using (var memory = new MemoryStream()) { int count = 0; do { count = stream.Read(buffer, 0, size); if (count > 0) { memory.Write(buffer, 0, count); } } while(count > 0); result.textureTiffData = memory.ToArray(); } } } var tempFile = Path.Combine(Path.GetTempPath(), "tempParticleTexture.tif"); File.WriteAllBytes(tempFile, result.textureTiffData); context.Logger.LogMessage("writing tiff to temp file: {0}", tempFile); context.Logger.LogMessage("running TextureImportor on tiff"); var textureImporter = new TextureImporter(); result.texture = textureImporter.Import(tempFile, input.context) as Texture2DContent; result.texture.Name = input.emitterConfig.texture.name; context.Logger.LogMessage("deleting temp file"); File.Delete(tempFile); // process context.Logger.LogMessage("processing TextureContent"); var textureProcessor = new TextureProcessor { GenerateMipmaps = false, TextureFormat = TextureProcessorOutputFormat.Color }; result.texture = (Texture2DContent)textureProcessor.Process(result.texture, context); context.Logger.LogMessage("TextureContent processed"); } else // no tiff data, so let's try loading the texture with the texture name, from the same directory as the particle file { string fileDirectory = Path.GetDirectoryName(input.path); string fullPath = Path.Combine(fileDirectory, input.emitterConfig.texture.name); context.Logger.LogMessage("Looking for texture file at {0}", fullPath); result.texture = context.BuildAndLoadAsset <string, Texture2DContent>(new ExternalReference <string>(fullPath), "TextureProcessor"); context.Logger.LogMessage("Texture file found"); } result.particleEmitterConfig = input.emitterConfig; return(result); }
public void ImportRGBA16Png() { var importer = new TextureImporter(); var context = new TestImporterContext(intermediateDirectory, outputDirectory); var content = importer.Import("Assets/Textures/RGBA16.png", context); Assert.NotNull(content); Assert.AreEqual(content.Faces.Count, 1); Assert.AreEqual(content.Faces[0].Count, 1); Assert.AreEqual(content.Faces[0][0].Width, 126); Assert.AreEqual(content.Faces[0][0].Height, 240); SurfaceFormat format; Assert.True(content.Faces[0][0].TryGetFormat(out format)); Assert.AreEqual(SurfaceFormat.Rgba64, format); // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions try { Directory.Delete(intermediateDirectory, true); Directory.Delete(outputDirectory, true); } catch (DirectoryNotFoundException) { } }
//导出图片资源 public void ExportImage(string path) { LoadDocument(); if (psd2Ui.exportFolder == null) { Debug.Log("导出文件夹为空"); return; } string exportPath = path; if (!Directory.Exists(exportPath)) { Debug.Log("导出文件夹填入错误"); return; } elementMap = new Dictionary<string, PsdElement>(); GenerateElementMap(ref elementMap, psd2Ui.asset.name, psd.Childs); //导出图片进度 var progress = 0f; var section = 1f / elementMap.Count; foreach (var pair in elementMap) { var element = pair.Value; var texturePieces = element.GetAllTexturePieces(); foreach (var piece in texturePieces) { if (piece == null) continue; var filePath = Path.Combine(exportPath + "/", piece.name + ".png"); EditorUtility.DisplayProgressBar("导出图片", piece.name + ".png", progress); if (!File.Exists(filePath)) { File.Create(filePath).Dispose(); } File.WriteAllBytes(filePath, piece.tex.EncodeToPNG()); AssetDatabase.Refresh(); TextureImporter importer = AssetImporter.GetAtPath(filePath) as TextureImporter; if (importer != null) { importer.textureType = TextureImporterType.Sprite; if (piece.is9Image) { if (piece.tex != null) importer.spriteBorder = new Vector4( Mathf.Floor(f: piece.tex.width / 2), Mathf.Floor(f: piece.tex.height / 2), Mathf.Floor(f: piece.tex.width / 2), Mathf.Floor(f: piece.tex.height / 2)); } importer.SaveAndReimport(); } } progress += section; EditorUtility.DisplayProgressBar("导出图片", "", progress); } EditorUtility.ClearProgressBar(); Debug.Log("导出完成"); }
public void ImportDdsMipMap() { //ImportStandard("Assets/Textures/LogoOnly_64px-mipmaps.dds", SurfaceFormat.Color); var importer = new TextureImporter(); var context = new TestImporterContext(intermediateDirectory, outputDirectory); var content = importer.Import("Assets/Textures/LogoOnly_64px-mipmaps.dds", context); Assert.NotNull(content); Assert.AreEqual(content.Faces.Count, 1); CheckDdsFace(content, 0); SurfaceFormat format; Assert.True(content.Faces[0][0].TryGetFormat(out format)); Assert.AreEqual(format, SurfaceFormat.Dxt3); // Clean-up the directories it may have produced, ignoring DirectoryNotFound exceptions try { Directory.Delete(intermediateDirectory, true); Directory.Delete(outputDirectory, true); } catch(DirectoryNotFoundException) { } }
// Access the Texture Importer, make necessary modifications and set up animations. public void Process(string theTexture, string[] parsedWords) { string texturePath = AssetDatabase.GUIDToAssetPath(theTexture); TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(texturePath); importer.spriteImportMode = SpriteImportMode.Multiple; importer.filterMode = FilterMode.Point; // Figure out show many parts of the sprite sheet should exist, then split them up //&&& add debug check for no remainders Texture2D texture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)); int spriteHeight = texture.height; int colCount = texture.width / spriteWidth; int rowCount = texture.height / spriteHeight; // Create the new sprites as metadata attached to the texture List <SpriteMetaData> metas = new List <SpriteMetaData>(); for (int r = 0; r < rowCount; ++r) { for (int c = 0; c < colCount; ++c) { SpriteMetaData meta = new SpriteMetaData(); meta.rect = new Rect(c * spriteWidth, r * spriteHeight, spriteWidth, spriteHeight); meta.name = c + "-" + r; metas.Add(meta); } } // Set the new meta-sprites, then call an update to save. importer.spritesheet = metas.ToArray(); AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate); //Get all the sprites from the texture into an array to use for building Object[] dataToParse = AssetDatabase.LoadAllAssetsAtPath(texturePath); Sprite[] spritesToUse = new Sprite[rowCount * colCount]; int i = 0; foreach (Object o in dataToParse) { if (o.GetType().ToString() == "UnityEngine.Sprite") { spritesToUse[i] = o as Sprite; i++; } } //Move the Asset from the import folder into the Texture Folder, building out folder if possible if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Textures/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2] + "/" + parsedWords[3])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Textures/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Textures/" + parsedWords[0] + "/" + parsedWords[1])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Textures/" + parsedWords[0])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Textures")) { AssetDatabase.CreateFolder("Assets/GameAssets", "Textures"); } AssetDatabase.CreateFolder("Assets/GameAssets/Textures", parsedWords[0]); } AssetDatabase.CreateFolder("Assets/GameAssets/Textures/" + parsedWords[0], parsedWords[1]); } AssetDatabase.CreateFolder("Assets/GameAssets/Textures/" + parsedWords[0] + "/" + parsedWords[1], parsedWords[2]); } AssetDatabase.CreateFolder("Assets/GameAssets/Textures/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2], parsedWords[3]); } AssetDatabase.MoveAsset(texturePath, "Assets/GameAssets/Textures/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2] + "/" + parsedWords[3] + "/" + parsedWords[4] + ".png"); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Animations/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Animations/" + parsedWords[0] + "/" + parsedWords[1])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Animations/" + parsedWords[0])) { if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Animations")) { AssetDatabase.CreateFolder("Assets/GameAssets", "Animations"); } AssetDatabase.CreateFolder("Assets/GameAssets/Animations", parsedWords[0]); } AssetDatabase.CreateFolder("Assets/GameAssets/Animations/" + parsedWords[0], parsedWords[1]); } AssetDatabase.CreateFolder("Assets/GameAssets/Animations/" + parsedWords[0] + "/" + parsedWords[1], parsedWords[2]); } // Create a new animation and mod the settings AnimationClip animation = new AnimationClip(); animation.name = parsedWords[2] + "_" + parsedWords[3] + "_" + parsedWords[4]; animation.frameRate = framerate; EditorCurveBinding spriteBinding = new EditorCurveBinding(); spriteBinding.type = typeof(SpriteRenderer); spriteBinding.path = ""; spriteBinding.propertyName = "m_Sprite"; // Explicitly mod the settings to access loop time AnimationClipSettings animSettings = AnimationUtility.GetAnimationClipSettings(animation); animSettings.loopTime = true; AnimationUtility.SetAnimationClipSettings(animation, animSettings); // Evenly space the sprite Keyframes at times depending on the framerate ObjectReferenceKeyframe[] spriteKeyFrames = new ObjectReferenceKeyframe[spritesToUse.Length]; for (i = 0; i < (spritesToUse.Length); i++) { spriteKeyFrames[i] = new ObjectReferenceKeyframe(); float timingi = (float)i; spriteKeyFrames[i].time = (timingi / framerate); spriteKeyFrames[i].value = spritesToUse[i]; } AnimationUtility.SetObjectReferenceCurve(animation, spriteBinding, spriteKeyFrames); RuntimeAnimatorController controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPathWithClip("Assets/GameAssets/Animations/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2] + "/" + parsedWords[2] + "_" + parsedWords[3] + "_" + parsedWords[4] + "_control.controller", animation); AssetDatabase.CreateAsset(animation, "Assets/GameAssets/Animations/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[2] + "/" + parsedWords[2] + "_" + parsedWords[3] + "_" + parsedWords[4] + "_anim.anim"); // Build a GameObject to house these things, later to use as a prefab GameObject objectToBuild = new GameObject(); objectToBuild.name = parsedWords[0] + "_" + parsedWords[1] + "_" + parsedWords[2]; // Add one of the sprites as the placeholder sprite. SpriteRenderer renderer = objectToBuild.AddComponent <SpriteRenderer>(); renderer.sprite = spritesToUse[0]; // Add our Animation controller Animator animator = objectToBuild.AddComponent <Animator>(); animator.runtimeAnimatorController = controller; // Save the finished object as a prefab if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Prefabs")) { AssetDatabase.CreateFolder("Assets/GameAssets", "Prefabs"); } if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Prefabs/" + parsedWords[0])) { AssetDatabase.CreateFolder("Assets/GameAssets/Prefabs", parsedWords[0]); } if (!AssetDatabase.IsValidFolder("Assets/GameAssets/Prefabs/" + parsedWords[0] + "/" + parsedWords[1])) { string preFolderMap = AssetDatabase.CreateFolder("Assets/GameAssets/Prefabs/" + parsedWords[0], parsedWords[1]); } if (Addressables.LoadResourceLocationsAsync("Assets/GameAssets/Prefabs/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[0] + "_" + parsedWords[1] + "_" + parsedWords[2] + ".prefab", GameObject)) { Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist."); } else { GameObject prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(objectToBuild, "Assets/GameAssets/Prefabs/" + parsedWords[0] + "/" + parsedWords[1] + "/" + parsedWords[0] + "_" + parsedWords[1] + "_" + parsedWords[2] + ".prefab", InteractionMode.UserAction); } // Remove the GameObject and Original Raws and leave the Prefab and processed files Undo.DestroyObjectImmediate(objectToBuild); }
// Texture processing Begin public static TextureImporterSettings TextureProcessingBegin(TextureImporter a_rTextureImporter) { Uni2DAssetPostprocessor.Enabled = false; // If it's the first time Uni2d use this texture // Set the default texture importer settings Texture2D rTexture = AssetDatabase.LoadAssetAtPath(a_rTextureImporter.assetPath, typeof(Texture2D)) as Texture2D; if(Uni2DEditorUtils.ItIsTheFirstTimeWeUseTheTexture(rTexture)) { Uni2DEditorUtils.MarkAsSourceTexture(rTexture); Uni2DEditorUtils.GenerateTextureImportGUID(rTexture); SetDefaultTextureImporterSettings( rTexture, false ); } TextureImporterSettings rTextureImporterSettings = new TextureImporterSettings(); a_rTextureImporter.ReadTextureSettings(rTextureImporterSettings); // Reimport texture as readable and at original size SetDefaultTextureImporterSettings(a_rTextureImporter); if(AssetDatabase.WriteImportSettingsIfDirty(a_rTextureImporter.assetPath)) { AssetDatabase.ImportAsset(a_rTextureImporter.assetPath, ImportAssetOptions.ForceSynchronousImport ); AssetDatabase.Refresh(); } return rTextureImporterSettings; }
static public void UpdateSpriteSlices(Texture texture, Atlas atlas) { string texturePath = AssetDatabase.GetAssetPath(texture.GetInstanceID()); var t = (TextureImporter)TextureImporter.GetAtPath(texturePath); t.spriteImportMode = SpriteImportMode.Multiple; var spriteSheet = t.spritesheet; var sprites = new List <SpriteMetaData>(spriteSheet); FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.NonPublic); var regions = (List <AtlasRegion>)field.GetValue(atlas); int textureHeight = texture.height; char[] FilenameDelimiter = { '.' }; int updatedCount = 0; int addedCount = 0; foreach (var r in regions) { int width, height; if (r.rotate) { width = r.height; height = r.width; } else { width = r.width; height = r.height; } int x = r.x; int y = textureHeight - height - r.y; string pageName = r.page.name.Split(FilenameDelimiter, StringSplitOptions.RemoveEmptyEntries)[0]; string textureName = texture.name; bool pageMatch = string.Equals(pageName, textureName, StringComparison.Ordinal); int spriteIndex = pageMatch ? sprites.FindIndex( (s) => string.Equals(s.name, r.name, StringComparison.Ordinal) ) : -1; bool matchFound = spriteIndex >= 0; if (matchFound) { var s = sprites[spriteIndex]; s.rect = new Rect(x, y, width, height); sprites[spriteIndex] = s; updatedCount++; } else { if (pageMatch) { sprites.Add(new SpriteMetaData { name = r.name, pivot = new Vector2(0.5f, 0.5f), rect = new Rect(x, y, width, height) }); addedCount++; } } } t.spritesheet = sprites.ToArray(); EditorUtility.SetDirty(t); AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate); EditorGUIUtility.PingObject(texture); Debug.Log(string.Format("Applied sprite slices to {2}. {0} added. {1} updated.", addedCount, updatedCount, texture.name)); }
// Texture processing End public static void SetDefaultTextureImporterSettings( TextureImporter a_rTextureImporter, bool a_bIsReadable = true ) { //Debug.Log("Set Default Importer Settings"); a_rTextureImporter.textureType = TextureImporterType.Advanced; a_rTextureImporter.maxTextureSize = 4096; a_rTextureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; a_rTextureImporter.npotScale = TextureImporterNPOTScale.None; a_rTextureImporter.isReadable = a_bIsReadable; a_rTextureImporter.mipmapEnabled = false; a_rTextureImporter.wrapMode = TextureWrapMode.Clamp; }
private void CreateExEnOutput(Texture2DContent input, ContentProcessorContext context) { ExEnFontWriter.CreateOutputDirectory(input.Identity); // Put the processor in a format suitable for outputting to PNG var originalPremultiply = PremultiplyAlpha; var originalFormat = TextureFormat; PremultiplyAlpha = false; TextureFormat = TextureProcessorOutputFormat.Color; // Build normal size: SpriteFontContent spriteFontContent = base.Process(input, context); ExEnFontWriter.WriteTexture(spriteFontContent, false, context, ExEnFontWriter.AssetOutputFilename(input.Identity, context, "-exenfont.png")); ExEnFontWriter.WriteMetrics(spriteFontContent, context, ExEnFontWriter.AssetOutputFilename(input.Identity, context, "-exenfont.exenfont")); // Check for retina size: string pathAt2x = Path.Combine(Path.GetDirectoryName(input.Identity.SourceFilename), Path.GetFileNameWithoutExtension(input.Identity.SourceFilename) + "@2x" + Path.GetExtension(input.Identity.SourceFilename)); if(File.Exists(pathAt2x)) { var textureImporter = new TextureImporter(); var textureAt2x = (Texture2DContent)textureImporter.Import(pathAt2x, null); context.AddDependency(pathAt2x); var spriteFontContentAt2x = base.Process(textureAt2x, context); ExEnFontWriter.WriteTexture(spriteFontContentAt2x, false, context, ExEnFontWriter.AssetOutputFilename(input.Identity, context, "*****@*****.**")); ExEnFontWriter.WriteMetrics(spriteFontContentAt2x, context, ExEnFontWriter.AssetOutputFilename(input.Identity, context, "*****@*****.**")); } PremultiplyAlpha = originalPremultiply; TextureFormat = originalFormat; }
public static bool setTexture(string path) { Texture2D tex = AssetDatabase.LoadAssetAtPath <Texture2D> (path); if (tex == null) { return(false); } TextureImporter ti = TextureImporter.GetAtPath(path) as TextureImporter; if (ti == null) { return(false); } TextureImporterPlatformSettings tips = ti.GetPlatformTextureSettings(platform); // Debug.Log (tips.format); switch (tips.format) { case TextureImporterFormat.ETC_RGB4: if (isPot(tex)) { return(false); } else { return(doSetTexture(path, ti, tips, tex)); } case TextureImporterFormat.ETC2_RGB4: case TextureImporterFormat.ETC2_RGBA8: case TextureImporterFormat.ETC2_RGB4_PUNCHTHROUGH_ALPHA: if (isPot(tex) || multipleOf4(tex)) { return(false); } else { return(doSetTexture(path, ti, tips, tex)); } case TextureImporterFormat.PVRTC_RGB2: case TextureImporterFormat.PVRTC_RGB4: case TextureImporterFormat.PVRTC_RGBA2: case TextureImporterFormat.PVRTC_RGBA4: if (isPot(tex)) { return(false); } else { return(doSetTexture(path, ti, tips, tex)); } case TextureImporterFormat.ASTC_RGBA_10x10: case TextureImporterFormat.ASTC_RGBA_12x12: case TextureImporterFormat.ASTC_RGBA_4x4: case TextureImporterFormat.ASTC_RGBA_5x5: case TextureImporterFormat.ASTC_RGBA_6x6: case TextureImporterFormat.ASTC_RGBA_8x8: case TextureImporterFormat.ASTC_RGB_10x10: case TextureImporterFormat.ASTC_RGB_12x12: case TextureImporterFormat.ASTC_RGB_4x4: case TextureImporterFormat.ASTC_RGB_5x5: case TextureImporterFormat.ASTC_RGB_6x6: case TextureImporterFormat.ASTC_RGB_8x8: return(false); case TextureImporterFormat.RGB16: case TextureImporterFormat.RGBA16: case TextureImporterFormat.RGBAHalf: return(false); case TextureImporterFormat.RGBA32: case TextureImporterFormat.RGB24: return(doSetTexture(path, ti, tips, tex)); case TextureImporterFormat.Automatic: #if UNITY_IPHONE || UNITY_IOS if (isPot(tex)) { return(false); } else { return(doSetTexture(path, ti, tips, tex)); } #elif UNITY_ANDROID if (isPot(tex) || multipleOf4(tex)) { return(false); } else { return(doSetTexture(path, ti, tips, tex)); } #endif default: Debug.LogError("some case not cased===" + path + "===" + tips.format.ToString()); return(false); } return(false); }
static void updateSpriteMetaData(TextureImporter importer, string pathToData) { importer.textureType = TextureImporterType.Sprite; importer.maxTextureSize = 4096; importer.spriteImportMode = SpriteImportMode.Multiple; List<SpriteMetaData> metaData = new List<SpriteMetaData> (); foreach (string row in File.ReadAllLines(pathToData)) { if (string.IsNullOrEmpty (row) || row.StartsWith ("#")) continue; // comment lines start with # string [] cols = row.Split (';'); if (cols.Length != 7) return; // format error SpriteMetaData smd = new SpriteMetaData (); smd.name = cols [0]; float x = float.Parse (cols [1]); float y = float.Parse (cols [2]); float w = float.Parse (cols [3]); float h = float.Parse (cols [4]); float px = float.Parse (cols [5]); float py = float.Parse (cols [6]); smd.rect = new UnityEngine.Rect (x, y, w, h); smd.pivot = new UnityEngine.Vector2 (px, py); if (px == 0 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomLeft; else if (px == 0.5 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomCenter; else if (px == 1 && py == 0) smd.alignment = (int)UnityEngine.SpriteAlignment.BottomRight; else if (px == 0 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.LeftCenter; else if (px == 0.5 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.Center; else if (px == 1 && py == 0.5) smd.alignment = (int)UnityEngine.SpriteAlignment.RightCenter; else if (px == 0 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopLeft; else if (px == 0.5 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopCenter; else if (px == 1 && py == 1) smd.alignment = (int)UnityEngine.SpriteAlignment.TopRight; else smd.alignment = (int)UnityEngine.SpriteAlignment.Custom; metaData.Add (smd); } if (metaData.Count == 0) return; if (importer.spritesheet == null || importer.spritesheet.Length == 0) { // replace a blank spritesheet importer.spritesheet = metaData.ToArray (); } else { // merge into an existing spritesheet Dictionary<string,SpriteMetaData> importedSprites = new Dictionary<string, SpriteMetaData> (); foreach (var smd in metaData) { importedSprites [smd.name] = smd; } // track what has been merged HashSet<string> merged = new HashSet<string> (); List<SpriteMetaData> existingSprites = new List<SpriteMetaData> (importer.spritesheet); // default struct to replace deleted sprites SpriteMetaData deletedSMD = new SpriteMetaData (); deletedSMD.rect = new UnityEngine.Rect (0, 0, 1, 1); // maintain indices for (int i = 0; i < existingSprites.Count; ++i) { if (importedSprites.ContainsKey (existingSprites [i].name)) { existingSprites [i] = importedSprites [existingSprites [i].name]; merged.Add (existingSprites [i].name); } else if (existingSprites [i].name.StartsWith ("DELETED_")) { string origName = existingSprites [i].name.Remove (0, 8); if (importedSprites.ContainsKey (origName)) { existingSprites [i] = importedSprites [origName]; merged.Add (origName); } } else { deletedSMD.name = "DELETED_" + existingSprites [i].name; existingSprites [i] = deletedSMD; } } // anything not merged is appended foreach (var smd in metaData) { if (!merged.Contains (smd.name)) { existingSprites.Add (smd); } } importer.spritesheet = existingSprites.ToArray (); } }
bool IsPowerOfTow(TextureImporter importer, out int width, out int height) { object[] args = new object[2] { 0, 0 }; MethodInfo mi = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance); mi.Invoke(importer, args); width = (int)args[0]; height = (int)args[1]; return Mathf.IsPowerOfTwo(width) && Mathf.IsPowerOfTwo(height); }
// Prepares Texture public static void SetDefaultAtlasTextureImportSettings(TextureImporter a_rTextureImporter) { a_rTextureImporter.textureType = TextureImporterType.Advanced; a_rTextureImporter.maxTextureSize = 4096; a_rTextureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; a_rTextureImporter.mipmapEnabled = false; a_rTextureImporter.isReadable = false; }
void OnGUI() { int i, j; ResetManager();//Remakes game objects require to operate. e = Event.current; //Gets current event (mouse move, repaint, keyboard press, etc) if(renameId != -1 && (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter)) { renameId = -1; } if(cmTileSets == null) //Check to make certain there is actually a tileset in the resources/tileset folder. { EditorGUILayout.LabelField("No tilesets found. Retrying."); OnEnable(); }else{ string[] names = new string[cmTileSets.Length]; //Gets the name of the tilesets into a useable list for(i = 0; i < cmTileSets.Length; i++) { try { names[i] = cmTileSets[i].name; } catch(System.Exception ex) { Debug.Log ("There was an error getting the names of the files. We'll try to reload the tilesets. If this continues to show, please close the script and try remimporting and check your images."); Debug.Log ("Full system error: " + ex.Message); OnEnable(); } } //Mode variable to swith between major features. string[] mode = {"Tile Painter", "Help Video"};//, "Pad Tileset"};// Pad tileset not finished yet, removed to allow for earlier release. You can try it out if you want, but is has issues with larger images and places tiles in the wrong order. curMode = GUILayout.Toolbar(curMode, mode); if(curMode == 0) { //If in standard paint mode, display the proper gui elements for the user to use. EditorGUILayout.BeginHorizontal(); int tmpInt = EditorGUILayout.Popup("Tileset", cmSelectedTileSet, names); if(GUILayout.Button("Reload")) { OnEnable(); } EditorGUILayout.EndHorizontal(); string[] tools = {"Paint", "Erase", "Box Paint"}; //curTool = EditorGUILayout.Popup("Tool", curTool, tools); EditorGUILayout.BeginHorizontal(GUILayout.Width(position.width)); //Causes an error on editor load if the window is visible. //This seems to be a problem with how the gui is drawn the first //loop of the script. It only happens the once, and I can't figure //out why. I've been trying for literally weeks and still can't //find an answer. This is the only known bug, but it doesn't //stop the functionality of the script in any way, and only serves //as an annoying message on unity load or this script being //recompiled. Sorry for this bug. I am looking for a way to remove //this error, but I really am stummped as to why it's happening //and I just can not find an answer online. EditorGUILayout.LabelField("Tool",GUILayout.Width(50)); GUILayout.FlexibleSpace(); curTool = GUILayout.Toolbar(curTool, tools); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Paint With Collider",GUILayout.Width(150)); makeCollider = EditorGUILayout.Toggle(makeCollider); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Highlight Current Layer",GUILayout.Width(150)); highlightLayer = EditorGUILayout.Toggle(highlightLayer, GUILayout.Width(25)); highlightColor = EditorGUILayout.ColorField(highlightColor); EditorGUILayout.EndHorizontal(); if(tmpInt != cmSelectedTileSet) //Forces selection of first tileset if none are selected. { LoadTileset(tmpInt); } cmSelectedTileSet = tmpInt; //sets the selected tileset value i = 0; int columnCount = Mathf.RoundToInt((position.width)/38)-2; //figures out how many columns are required for the tileset j = 0; int current = 0; tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition,false,true,GUILayout.Width(position.width)); //creates scrollbox area for tiles inside of the current tileset. GUILayout.BeginHorizontal(); //Initializing first row for(int q = 0; q < cmSprites.Length; q++) { Sprite child = cmSprites[q]; //for every tile inside the currently selected tileset, add a tile try { if(child.texture.name == names[cmSelectedTileSet] && child.name != names[cmSelectedTileSet]) { //if it's the tiles inside the image, not the entire image Rect newRect = new Rect( child.rect.x/child.texture.width, child.rect.y/child.texture.height, child.rect.width/child.texture.width, child.rect.height/child.texture.height );//gets the x and y position in pixels of where the image is. Used later for display. if(GUILayout.Button("", GUILayout.Width(34), GUILayout.Height(34))) { //draw a clickable button if (cmSelectedTile != null && !e.control) { //empty the selected tile list if control isn't held. Allows multiselect of tiles. cmSelectedTile.Clear(); cmCurSprite.Clear(); } cmSelectedTile.Add(current); //Adds clicked on tile to list of selected tiles. cmCurSprite.Add(cmCurSprites[current]); } GUI.DrawTextureWithTexCoords(new Rect(5+(j*38), 4+(i*37), 32, 32), child.texture, newRect ,true); //draws tile base on pixels gotten at the beginning of the loop if(cmSelectedTile != null && cmSelectedTile.Contains(current)) { //if the current tile is inside of the list of selected tiles, draw a highlight indicator over the button. if(cmSelectedColor == null) { cmSelectedColor = new Texture2D(1,1); cmSelectedColor.alphaIsTransparency = true; cmSelectedColor.filterMode = FilterMode.Point; cmSelectedColor.SetPixel(0,0, new Color(.5f,.5f,1f,.5f)); cmSelectedColor.Apply(); } GUI.DrawTexture(new Rect(5+(j*38), 4+(i*37), 32, 32), cmSelectedColor,ScaleMode.ScaleToFit,true); } if(j < columnCount) { j++; }else{ // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons j = 0; i++; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); } current++; } }catch(System.Exception ex){ if(ex.Message.StartsWith("IndexOutOfRangeException")) { Debug.Log("Tileset index was out of bounds, reloading and trying again."); OnEnable(); return; } } } GUILayout.EndHorizontal(); //finish the drawing of tiles EditorGUILayout.EndScrollView(); //Display all of the layers. May be put into a foldout for if there are too many layers. Haven't decided yet. GUILayout.Label("Layers:"); if(GUILayout.Button("Add Layer")) { AddLayer(); } String[] minusPlus = {"-", "+", "x", "r"}; ResetLayers(); layers = ResortLayers(layers);//Sort the layers based on their sorting order instead of name int destroyFlag = -1; for(i = 0; i < layers.Count; i++) { //iterates through layers and displays gui for options. EditorGUILayout.BeginHorizontal(); RectOffset tmpPadding = GUI.skin.button.padding; GUI.skin.button.padding = new RectOffset(3,3,3,3); if(layers[i].gameObject.activeSelf) { if(GUILayout.Button(texVisible,GUILayout.Width(15), GUILayout.Height(15))) { layers[i].gameObject.SetActive(false); } }else{ if(GUILayout.Button(texHidden,GUILayout.Width(15), GUILayout.Height(15))) { layers[i].gameObject.SetActive(true); } } GUI.skin.button.padding = tmpPadding; if(i == selectedLayer) { //if selected layer, draw checked checkbox to show it's selected if(i != renameId) { EditorGUILayout.ToggleLeft(layers[i].name + " - " + layers[i].GetComponent<SpriteRenderer>().sortingOrder,true); }else{ layers[i].name = EditorGUILayout.TextField(layers[i].name); } }else{ //if not the selected layer, and is clicked, set it as the selected layer if(i != renameId) { if(EditorGUILayout.ToggleLeft(layers[i].name + " - " + layers[i].GetComponent<SpriteRenderer>().sortingOrder,false)) { selectedLayer = i; } }else{ layers[i].name = EditorGUILayout.TextField(layers[i].name); } } //sets pressed value to -1 if nothing is pressed. int pressed = GUILayout.Toolbar(-1, minusPlus); switch(pressed) { case 0: if(i > 0) { //moves layer and all tiles in it to move away from the camera, and moves the layer above it toward the camera. layers[i-1].GetComponent<SpriteRenderer>().sortingOrder += 1; int upLayer = layers[i-1].GetComponent<SpriteRenderer>().sortingOrder; foreach(SpriteRenderer sr in layers[i-1].GetComponentsInChildren<SpriteRenderer>()) { sr.sortingOrder = upLayer; } //layers[i].GetComponent<SpriteRenderer>().sortingOrder -= 1; int downLayer = layers[i].GetComponent<SpriteRenderer>().sortingOrder -= 1; foreach(SpriteRenderer sr in layers[i].GetComponentsInChildren<SpriteRenderer>()) { sr.sortingOrder = downLayer; } selectedLayer = i-1; } layers = ResortLayers(layers); break; case 1: if(i < layers.Count-1) { //moves layer and all tiles in it to move toward the camera, and moves the layer above it away from the camera. layers[i+1].GetComponent<SpriteRenderer>().sortingOrder -= 1; int upLayer = layers[i+1].GetComponent<SpriteRenderer>().sortingOrder; foreach(SpriteRenderer sr in layers[i+1].GetComponentsInChildren<SpriteRenderer>()) { sr.sortingOrder = upLayer; } //layers[i].GetComponent<SpriteRenderer>().sortingOrder += 1; int downLayer = layers[i].GetComponent<SpriteRenderer>().sortingOrder += 1; foreach(SpriteRenderer sr in layers[i].GetComponentsInChildren<SpriteRenderer>()) { sr.sortingOrder = downLayer; } selectedLayer = i+1; } layers = ResortLayers(layers); break; case 2: //deletes the layer game object, which also deletes all the children destroyFlag = i; break; case 3: if(renameId == -1) { renameId = i; }else{ renameId = -1; } break; default: //do nothing if a button wasn't pressed (required or I get errors T_T) break; } EditorGUILayout.EndHorizontal(); //end the layer gui } if(selectedLayer <= layers.Count-1 && selectedLayer > 0) { //double check to make certain a layer of some sort is selected and is in valid range curLayer = layers[selectedLayer].gameObject; } if(selectedLayer <= layers.Count-1 && layers[selectedLayer] != null) { ResetHighlight(layers[selectedLayer].gameObject, highlightLayer); curLayer = layers[selectedLayer].gameObject; }else{ if(layers.Count-1 > 0 && layers[selectedLayer] != null) { curLayer = layers[selectedLayer].gameObject; }else{ } } if(destroyFlag != -1) { DestroyImmediate(layers[destroyFlag].gameObject); return; //Breaks method to not have errors down the line. Forces reload of tilesets to keep inside the bounds of the array. } destroyFlag = -1; }else if(curMode == 1){ curMode = 0; Application.OpenURL("https://www.youtube.com/watch?v=mxy9HdNM-is"); return; }else if(curMode == 2){ int tmpInt = EditorGUILayout.Popup("Tileset", cmSelectedTileSet, names); if(tmpInt != cmSelectedTileSet) //Forces selection of first tileset if none are selected. { LoadTileset(tmpInt); } cmSelectedTileSet = tmpInt; //sets the selected tileset value GUILayout.BeginHorizontal(); GUILayout.Label("Grid Size X", GUILayout.Width(200)); gridSizeX = EditorGUILayout.IntField(gridSizeX); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Grid Size Y", GUILayout.Width(200)); gridSizeY = EditorGUILayout.IntField(gridSizeY); GUILayout.EndHorizontal(); /*GUILayout.BeginHorizontal(); GUILayout.Label("Pad Size X", GUILayout.Width(200)); padSizeX = EditorGUILayout.IntField(padSizeX); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Pad Size Y", GUILayout.Width(200)); padSizeY = EditorGUILayout.IntField(padSizeY); GUILayout.EndHorizontal();*/ if(GUILayout.Button("Generate New Texture")) { List<Rect> listOfNewSlices = new List<Rect>(); Texture2D curTileSet = Resources.Load<Texture2D>("Tilesets/" + cmTileSets[cmSelectedTileSet].name);//cmTileSets[cmSelectedTileSet]; int newWidth = (int)(curTileSet.width+(padSizeX*2*(curTileSet.width/gridSizeX))); int newHeight = (int)(curTileSet.height+(((curTileSet.height/gridSizeY))*(padSizeY*2))); Texture2D newTileSet = new Texture2D(newWidth,newHeight); Debug.Log("Generated new tile image with a size of " + newTileSet.width + ", " + newTileSet.height); // Debug.Log("Tilecount: " + (int)(curTileSet.width/gridSizeX) + ", " + (int)(curTileSet.height/gridSizeY)); for(j = 0; j < (int)(curTileSet.width/gridSizeX); j++) { for(i = 0 ; i < (int)(curTileSet.height/gridSizeY); i++) { //Copies old image tiles to new image with padding. try{ newTileSet.SetPixels( ((j*gridSizeX)+(j*padSizeX*2))+padSizeX, ((i*gridSizeY)+(i*padSizeY*2))+padSizeY, gridSizeX, gridSizeY, curTileSet.GetPixels( j*gridSizeX, i*gridSizeY, gridSizeX, gridSizeY)); Debug.Log(i*32); //LeftSide /*newTileSet.SetPixels( (j*gridSizeX)+(j*padSizeX*2)+padSizeX-1, (i*gridSizeY)+(i*padSizeY*2), 1, gridSizeY, curTileSet.GetPixels( j*gridSizeX, i*gridSizeY, 1, gridSizeY)); //RightSide newTileSet.SetPixels( (j*gridSizeX)+(j*padSizeX*2)+padSizeX + gridSizeX, (i*gridSizeY)+(i*padSizeY*2), 1, gridSizeY, curTileSet.GetPixels( (j*gridSizeX)+gridSizeX-1, i*gridSizeY, 1, gridSizeY)); //BottomSide newTileSet.SetPixels( (j*gridSizeX)+(j*padSizeX*2)+padSizeX, (i*gridSizeY)+(i*padSizeY*2)-1, gridSizeX, 1, curTileSet.GetPixels( j*gridSizeX, i*gridSizeY, gridSizeX, 1)); //TopSide newTileSet.SetPixels( (j*gridSizeX)+(j*padSizeX*2)+padSizeX, (i*gridSizeY)+(i*padSizeY*2)+gridSizeY, gridSizeX, 1, curTileSet.GetPixels( (j*gridSizeX), (i*gridSizeY)+gridSizeY-1, gridSizeX, 1));*/ listOfNewSlices.Add(new Rect( ((i*gridSizeY)+(i*padSizeY*2))+padSizeY, ((j*gridSizeX)+(j*padSizeX*2))+padSizeX, gridSizeX, gridSizeY)); //Debug.Log("Drawing tile " + i + ", " + j + " at " + ((i*padSizeX)+(i*gridSizeX)) + ", " + ((j*padSizeY)+(j*gridSizeY)) + " from " + i*gridSizeX + ", " + j*gridSizeY); }catch(System.Exception ex) { Debug.Log("ERROR: " + ex.Message); if(0==0) { } } } } newTileSet.Apply(); //listOfNewSlices.Add(new Rect(0,newTileSet.height-gridSizeX,100,100)); Debug.Log("Image generation completed, generating slices."); /*FileStream fs = new FileStream(Application.dataPath + "/Resources/Tilesets/" + curTileSet.name + "_padded.png", FileMode.Append); BinaryWriter bw = new BinaryWriter(fs); bw.Write(newTileSet.EncodeToPNG()); bw.Close(); fs.Close();*/ //AssetDatabase.CreateAsset(newTileSet.EncodeToPNG(), "Assets/Resources/Tilesets/" + curTileSet.name + "_padded.png"); bool isWriting = true; while(isWriting) { File.WriteAllBytes(Application.dataPath + "/Resources/Tilesets/" + curTileSet.name + "_padded.png", newTileSet.EncodeToPNG()); isWriting = false; } AssetDatabase.Refresh(); TextureImporter ti = new TextureImporter(); ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(Resources.Load<Texture>("Tilesets/" + curTileSet.name + "_padded"))); TextureImporterType type = new TextureImporterType(); type = TextureImporterType.Sprite; ti.textureType = type; ti.spritePixelsPerUnit = gridSizeX; ti.spriteImportMode = SpriteImportMode.Multiple; ti.filterMode = FilterMode.Point; List<SpriteMetaData> spriteData = new List<SpriteMetaData>();//[listOfNewSlices.Count+1]; //listOfNewSlices.Reverse(); for(i = 0; i < listOfNewSlices.Count; i++) { float alpha = 0; foreach(Color pixel in newTileSet.GetPixels((int)listOfNewSlices[i].x, (int)listOfNewSlices[i].y, (int)listOfNewSlices[i].width, (int)listOfNewSlices[i].height)) { alpha += pixel.a; } if(alpha > 0) { listOfNewSlices[i] = new Rect(listOfNewSlices[i].x, listOfNewSlices[i].y, listOfNewSlices[i].width, listOfNewSlices[i].height); SpriteMetaData tmpSpriteData = new SpriteMetaData(); tmpSpriteData.rect = listOfNewSlices[i]; tmpSpriteData.name = curTileSet.name + "_padded_" + i;// ti.spritesheet.GetLength(0); tmpSpriteData.alignment = 0; tmpSpriteData.pivot = new Vector2(gridSizeX/2,gridSizeY/2); spriteData.Add(tmpSpriteData); }else{ listOfNewSlices.RemoveAt(i); //spriteData.RemoveAt(i); i--; } } ti.spritesheet = spriteData.ToArray(); Debug.Log("Finished generating new padded tileset. Pausing thread to update file."); System.Threading.Thread.Sleep(4000);//Added to allow for saving and reimporting image in unity. Required to run without error. OnEnable(); } if(GUILayout.Button("Regenerate to Original File")) { } } } }
private GLexTexture(Texture2D texture) : base() { mTexture = texture; mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL); // texture need to be readable for export if (!mImporter.isReadable) { Debug.LogWarning("GLexTexture.Construct: Setting texture " + Name + " as Readable, or export will fail!"); mImporter.isReadable = true; AssetDatabase.ImportAsset(OriginalURL); mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL); } if (IsARGB32orRGB24) { _dataBytes = mTexture.EncodeToPNG(); } else { _dataBytes = new JPGEncoder(mTexture, GLexConfig.JPEGQuality).GetBytes(); } _dataBinaryKeystring = NamesUtil.GenerateBinaryId(_dataBytes, GLex.Instance.UserName); mTextures.Add(this); }
public TextureExportData(Texture t) { this.t = t; if (IsImage) { ti = (TextureImporter)AssetImporter.GetAtPath (Path); // Those settings are not applied, only updated in the UI which is very confusing :( // ti.isReadable = true; // ti.textureFormat = TextureImporterFormat.ARGB32; } }
void SetLUTImportSettings(TextureImporter importer) { #if UNITY_5_5_OR_NEWER importer.textureType = TextureImporterType.Default; importer.sRGBTexture = false; importer.textureCompression = TextureImporterCompression.Uncompressed; #else importer.textureType = TextureImporterType.Advanced; importer.linearTexture = true; importer.textureFormat = TextureImporterFormat.RGB24; #endif importer.anisoLevel = 0; importer.mipmapEnabled = false; importer.SaveAndReimport(); }