LoadImage() приватный метод

private LoadImage ( byte data ) : bool
data byte
Результат bool
Пример #1
1
    /*	The only necessary method - follows two step process outlined above
     *	Returns album art as a new texture
     */
    public Texture getAlbumArtAsTexture(GameObject audioHolder, FileInfo f)
    {
        Texture2D albumArt = new Texture2D (1, 1); //empty texture holder

        foreach (Transform file in audioHolder.transform.parent) { //loads all files from current directory - will not result in massive searches because we only pass files until an album container is created
            if (file.gameObject.name.EndsWith(".jpg") || file.gameObject.name.EndsWith(".png")) { //pull album art from images found in directory
                byte[] bytes = System.IO.File.ReadAllBytes(file.gameObject.name); //pull byte stream from image file
                albumArt.LoadImage(bytes); //load byte stream into new texture
                return albumArt;
            }
            else {
                if (file.name != "AlbumTitle") {//scrape album art from music file data
                    TagLib.File tagFile = TagLib.File.Create(file.name);
                    if (tagFile.Tag.Pictures.Length == 0) {
                        return null; //default texture
                    }
                    TagLib.IPicture albumPic = tagFile.Tag.Pictures [0];
                    MemoryStream stream = new MemoryStream (albumPic.Data.Data);
                    byte[] tagBytes;
                    byte[] buffer = new byte[16 * 1024];
                    using (MemoryStream ms = new MemoryStream()) { //read image data into new stream
                        int read;
                        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {
                            ms.Write(buffer, 0, read);
                        }
                        tagBytes = ms.ToArray();
                    }
                    albumArt.LoadImage (tagBytes); //convert stream data into new texture
                    return albumArt;
                }
            }
        }

        return null;
    }
Пример #2
1
    /// <summary>
    /// Reads from the provided file name all parameters and data for a
    /// heightmap.  If the data for the heightmap does not exist, then
    /// no data is written to the provided texture.
    /// </summary>
    /// <param name='fileName'>
    /// The file name.  This can be relative or fully-qualified.
    /// </param>
    /// <param name='no'>
    /// The <see cref="NormalOptions" /> that will store read-in parameters.
    /// </param>
    /// <param name='co'>
    /// The <see cref="CloudOptions" /> that will store read-in parameters for
    /// <see cref="CloudFractal" />.
    /// </param>
    /// <param name='wo'>
    /// The <see cref="WorleyOptions" />  that will store read-in parameters for
    /// <see cref="WorleyNoise" />.
    /// </param>
    /// <param name='tex'>
    /// The <code>Texture2D</code> containing the heightmap data.
    /// </param>
    public static void Read(string fileName, ref NormalOptions no,
	                        ref CloudOptions co, ref VoronoiOptions vo,
							ref Texture2D tex)
    {
        using(BinaryReader r = new BinaryReader(File.OpenRead(fileName)))
        {
            no.size = r.ReadInt32();
            no.seed = r.ReadInt32();
            no.cloudInf = r.ReadSingle();
            no.voronoiInf = r.ReadSingle();
            no.useThermalErosion = r.ReadBoolean();
            no.useHydroErosion = r.ReadBoolean();
            no.showSeams = r.ReadBoolean();

            co.upperLeftStart = r.ReadSingle();
            co.lowerLeftStart = r.ReadSingle();
            co.lowerRightStart = r.ReadSingle();
            co.upperRightStart = r.ReadSingle();

            vo.metric = (DistanceFunctions.DistanceMetric)r.ReadInt32();
            vo.combiner = (CombinerFunctions.CombineFunction)r.ReadInt32();
            vo.numberOfFeaturePoints = r.ReadInt32();
            vo.numberOfSubregions = r.ReadInt32();
            vo.multiplier = r.ReadSingle();

            tex.Resize(no.size, no.size);
            int bLeft = (int)(r.BaseStream.Length - r.BaseStream.Position);
            if(bLeft > 0)
                tex.LoadImage(r.ReadBytes(bLeft));
        }
    }
Пример #3
0
    public static Texture2D GetTextureFromStream(Stream stream)
    {
        Texture2D texture = null;

        if (stream != null)
        {
            texture = new Texture2D(1, 1);

            if (stream is MemoryStream)
                texture.LoadImage(((MemoryStream)stream).ToArray());
            else
            {
                byte[] buffer = new byte[16384];

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int bytesRead;

                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                        memoryStream.Write(buffer, 0, bytesRead);

                    texture.LoadImage(memoryStream.ToArray());
                }
            }
        }

        return texture;
    }
Пример #4
0
		public void Update()
		{
			if (buttonAppLaunch == null)
			{
				if (ApplicationLauncher.Ready)
				{
					if (texAppLaunch == null)
					{
						texAppLaunch = new Texture2D(38, 38, TextureFormat.RGBA32, false);
						texAppLaunch.LoadImage(System.IO.File.ReadAllBytes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "applaunch.png")));
					}

					buttonAppLaunch = ApplicationLauncher.Instance.AddModApplication(
						ExtendHeap,
						ExtendHeap,
						null,
						null,
						null,
						null,
						ApplicationLauncher.AppScenes.ALWAYS,
						texAppLaunch
						);

					buttonAppLaunch.SetFalse(false);
				}
				else
				{
					Trace("ApplicationLauncher is not ready in Update");
				}
			}
		}
Пример #5
0
 private void LoadJPGTextures(ZipFile pk3)
 {
     foreach (Texture tex in Textures)
     {
         // The size of the new Texture2D object doesn't matter. It will be replaced (including its size) with the data from the .jpg texture that's getting pulled from the pk3 file.
         if (pk3.ContainsEntry(tex.Name + ".jpg"))
         {
             Texture2D readyTex = new Texture2D(4, 4);
             var entry = pk3 [tex.Name + ".jpg"];
             using (var stream = entry.OpenReader())
             {
                 var ms = new MemoryStream();
                 entry.Extract(ms);
                 readyTex.LoadImage(ms.GetBuffer());
             }
             
             readyTex.name = tex.Name;
             readyTex.filterMode = FilterMode.Trilinear;
             readyTex.Compress(true);
             
             if (readyTextures.ContainsKey(tex.Name))
             {
                 Debug.Log("Updating texture with name " + tex.Name);
                 readyTextures [tex.Name] = readyTex;
             } else
                 readyTextures.Add(tex.Name, readyTex);
         }
     }
 }
    // Go get the Wwise Logo from the Wwise installation folder
    void FetchWwiseLogo()
    {
        // Pre-fetch the wwise logo
        string logoPath = Path.Combine(Application.dataPath, "Wwise\\Gizmos\\wwise_white_on_gray.png");
        logoPath = logoPath.Replace('\\', Path.DirectorySeparatorChar);
        m_Logo = new Texture2D(4, 4);
        try
        {
            FileStream fs = new FileStream(logoPath, FileMode.Open, FileAccess.Read);
            byte[] imageData = new byte[fs.Length];
            fs.Read(imageData, 0, (int)fs.Length);
            m_Logo.LoadImage(imageData);

            // Get the Wwise version as well
            string[] newVersionTxtLines = System.IO.File.ReadAllLines(Application.dataPath + "/Wwise/Version.txt");
            m_newIntegrationVersion = newVersionTxtLines[4].Split(' ')[4];
			if(m_newIntegrationVersion[m_newIntegrationVersion.Length-1] == '0') 
				m_newIntegrationVersion = m_newIntegrationVersion.Remove(m_newIntegrationVersion.Length-2);

        }
        catch (Exception)
        {
            // Fail silentely, not too bad if we can't show the image...
        }
    }
Пример #7
0
        /** Loads a bitmap resources from a dll.
         *  @param string resourceName - The name of the bitmap file in the dll.
         *  @param int width  - The width for the returning texture2D.
         *  @param int height - The height for the returning texture2D.
         *  @returns Texture2D - The resource texture.*/
        public static Texture2D LoadBitmap( string resourceName, int width, int height)
        {
            // Check if a local resource is accessible.
            Texture2D texture = (Texture2D)Resources.Load(resourceName);
            if (texture != null)
            {
                // if a local resource exists return it.
                return texture;
            }

            // Load data resource from the dll.
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream stream = assembly.GetManifestResourceStream("klock." + resourceName);

               /* string[] mrn = assembly.GetManifestResourceNames();
            foreach (string s in mrn)
            {
                Debug.Log(s);
            }*/

            // Create new texture. And load the resource data in it.
            texture = new Texture2D(width, height, TextureFormat.ARGB32, false);
            texture.LoadImage( ReadToEnd(stream) );

            // If texture has no data. Anything goes wrong.
            if (texture == null)
            {
                Debug.LogError("Missing Dll resource: " + resourceName);
            }
            if (stream != null) stream.Close();

            return texture;
        }
Пример #8
0
    // Description:  Loads the image to the background
    // PRE:          The user has selected a file to be uploaded as the background
    // POST:         The background the user selected will apear in the scene behind all other gameobjects
    public void LoadImage()
    {
        byte[] fileData;

        SpriteRenderer defaultBg = Camera.main.GetComponentInChildren<SpriteRenderer>();
        SpriteRenderer userBg = GameObject.Find("UserBackgroundImage").GetComponent<SpriteRenderer>();
        this.m_textPath = this.m_textPath.Replace('\\', '/');                                                               // Unity only likes forward slashes
        Texture2D newTexture = new Texture2D((int)defaultBg.sprite.rect.height, (int)defaultBg.sprite.rect.width);

        fileData = File.ReadAllBytes(this.m_textPath);                                                                     // Read the bytes of the image in raw
        newTexture.LoadImage(fileData);                                                                                     // Load image from byte data

        userBg.sprite = Sprite.Create(newTexture,
                                        new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0.5f, 0.5f), defaultBg.sprite.pixelsPerUnit);

        // The following code scales the image to the camera size
        transform.localScale = new Vector3(1, 1, 1);

        float width = userBg.sprite.bounds.size.x;
        float height = userBg.sprite.bounds.size.y;

        float worldScreenHeight = Camera.main.orthographicSize * 2f + 1;
        float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width + 1;

        Vector3 imgScale = new Vector3(1f, 1f, 1f);

        imgScale.x = worldScreenWidth / width;
        imgScale.y = worldScreenHeight / height;

        // Apply change
        userBg.transform.localScale = imgScale;
    }
    void Start()
    {
        crossHairs = new Texture2D(16,16);
        crossHairs.LoadImage(crossHairsRaw.bytes);

        LockCursor();
    }
        public void ClickSave()
        {
            InitialConfigLoader loader = new InitialConfigLoader();
            InitialConfigurations config = loader.loadInitialConfig();

            List<BarrierConfigurations> newBarrierConfig = new List<BarrierConfigurations>();

            for(int i = 0 ; i < config.barrierConfig.Count ; i++)
            {
                string GOname = "BarrierSkin " + i;
                var skinitem = barrierMenu.transform.Find("Panel").Find("Scroll Rect").Find("Content Panel").Find(GOname).Find("Panel");

                BarrierConfigurations barrieritem = new BarrierConfigurations();

                barrieritem.name = skinitem.Find("TextName").GetComponent<Text>().text;
                barrieritem.width = float.Parse(skinitem.Find("InputField_Thickness").GetComponent<InputField>().text);
                barrieritem.height = float.Parse(skinitem.Find("InputField_Height").GetComponent<InputField>().text);
                barrieritem.Path = materialPaths[i];
                if(isTextureChanged[i])
                {
                    Material mat = (Material)Resources.Load(barrieritem.Path);
                    byte[] fileData = File.ReadAllBytes(texturePaths[i]);
                    Texture2D tex = new Texture2D(2, 2);
                    tex.LoadImage(fileData);
                    mat.mainTexture = tex;
                    mat.mainTextureScale = new Vector2(5, 1);
                }
            }

            config.barrierConfig = newBarrierConfig;
            loader.saveInitialConfig(Path.Combine(Application.persistentDataPath, "ConfigFiles/initialConfig.xml"), config);

            barrierMenu.SetActive(false);
        }
Пример #11
0
 void Start()
 {
     //ExchangeData.search = "Las Vegas";
     searchTerm = ExchangeData.search;
     string name = searchTerm.ToLower();
     name = name.Replace(' ', '_');
     Debug.Log(name);
     string dataPath = Application.dataPath;
     Debug.Log(dataPath);
     string directory = "/storage/emulated/0/teamX/" + name;
     //string directory = "C:/Users/Abhishek/Desktop/teamX/" + name;
     Debug.Log(directory);
     int i = 1;
     foreach (string file in Directory.GetFiles(directory, "*.jpg"))
     {
         Debug.Log(file);
         Texture2D tex = new Texture2D(2, 2);
         byte[] fileData = File.ReadAllBytes(file);
         tex.LoadImage(fileData);
         foreach (Transform child in transform)
         {
             if (child.gameObject.name == "image" + i)
             {
                 child.gameObject.GetComponent<Renderer>().material.mainTexture = tex;
             }
         }
         i++;
     }
 }
Пример #12
0
	internal void getFiles()
	{
		if (System.IO.Directory.Exists(myPath))
		{
			DirectoryInfo dir = new DirectoryInfo(myPath);
			Debug.Log("Looking for files in dir: "+myPath);
			
			FileInfo[] info = dir.GetFiles("*."+extention);
			
			// Get number of files, and set the length for the texture2d array
			int totalFiles =  info.Length;
			slides = new Texture2D[totalFiles];
			
			int i = 0;
			
			//Read all found files
			foreach (FileInfo f in info)
			{
				string filePath = f.Directory + "/" + f.Name;
				Debug.Log("["+i+"] file found: "+filePath);
				
				var bytes     = System.IO.File.ReadAllBytes(filePath);
				var tex         = new Texture2D(1, 1);
				
				tex.LoadImage(bytes);
				slides[i] = tex;
				
				i++;
			}
		}
		else
		{
			Debug.Log ("Directory DOES NOT exist! ");
		}
	}
    public bool AddTypeElement(System.Xml.Linq.XElement elemtype)
    {
        if (store == null) //nowhere to put the image.
        {
            Debug.LogError("Texture Storage is Null: " + elemtype);
            return false;
        }

        XAttribute fileAtt = elemtype.Attribute("file");
        if (fileAtt == null)
        {
            Debug.LogError("No file attribute in " + elemtype);
            //Add error message here
            return false;
        }
        string filePath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), fileAtt.Value);
        filePath = Path.GetFullPath(filePath);

        if (!File.Exists(filePath))
        {
            Debug.LogError("File not found: " + filePath);
            return false;
        }

        byte[] fileData = File.ReadAllBytes(filePath);

        Texture2D tex = new Texture2D(2,2);
        tex.LoadImage(fileData);

        tex.name = filePath;

        storageIndex = store.AddTexture(tex);
        return true;
    }
Пример #14
0
    //Where the magic happens
    public void BuildGame()
    {
        //Figure out the name of the game from the directory title
        var directoryName = directory.Name;
        //Replace the underscores and dashes with blank spaces
        var name = directoryName.Replace('_', ' ');
        name = name.Replace('-', ' ');

        //No author stuff just yet
        string author = null;

        // Load the screenshot from the games directory as a Texture2D
        var screenshotTex = new Texture2D(1024, 768);
        screenshotTex.LoadImage(File.ReadAllBytes(Path.Combine(directory.FullName, directory.Name + ".png")));

        // Turn the Texture2D into a sprite
        var screenshot = Sprite.Create(screenshotTex, new Rect(0, 0, screenshotTex.width, screenshotTex.height), new Vector2(0.5f, 0.5f));

        //Find the .exe in the directory and save a reference
        var executablePath = Path.Combine(directory.FullName, directory.Name + ".exe");

        this.name = name;
        this.author = author;
        this.screenshot = screenshot;
        this.executablePath = executablePath;

        Debug.Log ("Game Built! Name: " + name + " Screenshot: " + screenshot.name + " exe path: " + executablePath);
    }
Пример #15
0
 private Texture2D loadIcon(string path)
 {
     Texture2D result = new Texture2D(1, 1);
         result.LoadImage(System.IO.File.ReadAllBytes(PATH+path));
     result.Apply();
     return result;
 }
Пример #16
0
    void LateUpdate()
    {
        takeHiResShot |= Input.GetKeyDown("joystick button 0");
        if (takeHiResShot)
        {
            if (photos.Count >= 5)
            {
                Debug.Log("Too many photos, not saving");
                takeHiResShot = false;
                return;
            }

            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
            camera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camera.targetTexture = null;
            RenderTexture.active = null; // JC: added to avoid errors
            Destroy(rt);
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName(resWidth, resHeight);

            photos.Add(bytes);
            takeHiResShot = false;
            Debug.Log(string.Format("Added screenshot to memory. {0} photos in total now.", photos.Count));

            Texture2D texture = new Texture2D(resWidth, resHeight);
            texture.LoadImage(bytes);
        }
    }
Пример #17
0
        private void AddFilter()
        {
            //Loads the RealChute parachutes icon
            Texture2D normal = new Texture2D(32, 32), selected = new Texture2D(32, 32);
            normal.LoadImage(File.ReadAllBytes(Path.Combine(RCUtils.pluginDataURL, "FilterIcon.png")));
            selected.LoadImage(File.ReadAllBytes(Path.Combine(RCUtils.pluginDataURL, "FilterIcon_selected.png")));
            Icon icon = new Icon("RC_Parachutes", normal, selected);

            //Adds the Parachutes filter to the Filter by Function category
            PartCategorizer.Category filterByFunction = PartCategorizer.Instance.filters
                .Find(f => f.button.categoryName == "Filter by Function");
            PartCategorizer.AddCustomSubcategoryFilter(filterByFunction, "Parachutes", icon,
                p => p.moduleInfos.Any(m => m.moduleName == "RealChute" || m.moduleName == "Parachute"));

            //Sets the buttons in the Filter by Module category
            List<PartCategorizer.Category> modules = PartCategorizer.Instance.filters
                .Find(f => f.button.categoryName == "Filter by Module").subcategories;
            modules.Remove(modules.Find(m => m.button.categoryName == "Procedural Chute"));
            modules.Select(m => m.button).Single(b => b.categoryName == "RealChute").SetIcon(icon);

            //Apparently needed to make sure the buttons in Filter by Function show when the editor is loaded
            RUIToggleButtonTyped button = filterByFunction.button.activeButton;
            button.SetFalse(button, RUIToggleButtonTyped.ClickType.FORCED);
            button.SetTrue(button, RUIToggleButtonTyped.ClickType.FORCED);
        }
    // Use this for initialization
    void Start()
    {
        // Initialize cubemap texture
        Texture2D tex = new Texture2D(3600, 600, TextureFormat.RGB24, false);

        var bytes = System.IO.File.ReadAllBytes(filepath);
        tex.LoadImage(bytes);
        GetComponent<Renderer>().material.mainTexture = tex;

        /*
        // Find cubemap window and get dimensions
        //System.IntPtr desktopHwnd = FindWindowEx(GetDesktopWindow(), IntPtr.Zero, "Progman", "Program Manager");
        System.IntPtr hwnd = FindWindow(null, "Right 3D Widget");
        var rect = new Rectangle(0,15,700,700);
        //var rect = new Rectangle();
        GetWindowRect(hwnd, ref rect);

        // Save window capture
        var bmp = new Bitmap(rect.Width, rect.Height);
        System.Drawing.Graphics memoryGraphics = System.Drawing.Graphics.FromImage(bmp);
        IntPtr dc = memoryGraphics.GetHdc();
        PrintWindow(hwnd, dc, 0);
        memoryGraphics.ReleaseHdc(dc);

        // Save image to memory stream
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Seek(0, System.IO.SeekOrigin.Begin);

        // Load image and apply to cube
        tex.LoadImage(ms.ToArray());
        GetComponent<Renderer>().material.mainTexture = tex;
        //*/
    }
  private static Texture2D GetIcon(string name)
  {
    var tex = new Texture2D(16, 16);
    string base64Str;
    switch (name)
    {
      case  "up":
        base64Str = IconUp;
        break;
      case "down":
        base64Str = IconDown;
        break;      
      case "mirror":
        base64Str = IconMirror;
        break;
      case "new":
        base64Str = IconNew;
        break;
      case "trash":
        base64Str = IconTrash;
        break;
      default:
        base64Str = IconUp;
        break;
    }

    var bytes = Convert.FromBase64String(base64Str);
    tex.LoadImage(bytes);
    return tex;
  }
 static public int LoadImage(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Byte[]         a1;
             checkArray(l, 2, out a1);
             var ret = self.LoadImage(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Byte[]         a1;
             checkArray(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             var ret = self.LoadImage(a1, a2);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #21
0
	public void updatePostableImages() {
		foreach (Transform child in transform) {
			Destroy (child.gameObject);
		}


		#if UNITY_EDITOR
		//  Make sure pictures are loaded into resources
		AssetDatabase.Refresh();
		#endif

		DirectoryInfo dir = new DirectoryInfo(pathToUploadQueue);
		FileInfo[] info = dir.GetFiles("*.png");
		foreach (FileInfo photoFile in info) {
			string filename = photoFile.Name;

			GameObject curPicture = (GameObject)Instantiate (newPicture);
			Texture2D pic = new Texture2D (2, 2);
			byte[] bytes = File.ReadAllBytes (pathToUploadQueue + filename);
			pic.LoadImage (bytes);
			RawImage rawImage = (RawImage) curPicture.GetComponent<RawImage> ();
			rawImage.texture = pic;
			curPicture.GetComponent<RawImage> ().name = filename.Replace (".png", "");
			curPicture.transform.SetParent (this.transform, false);
			curNames.Add (curPicture);
		}
	}
        public static UITextureAtlas LoadThumbnailsTextureAtlas(string name)
        {
            UITextureAtlas atlas;
            if (sm_atlases.TryGetValue(name, out atlas))
                return atlas;

            Shader shader = Shader.Find("UI/Default UI Shader");
            if (shader == null)
            {
                Debug.Log("Cannot find UI Shader. Using default thumbnails.");
                return null;
            }

            byte[] bytes;
            if (!FileManager.GetTextureBytes(name + ".png", FileManager.Folder.UI, out bytes))
            {
                Debug.Log("Cannot find UI Atlas file. Using default thumbnails.");
                return null;
            }

            Texture2D atlasTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
            atlasTexture.LoadImage(bytes);
            FixTransparency(atlasTexture);

            Material atlasMaterial = new Material(shader);
            atlasMaterial.mainTexture = atlasTexture;

            atlas = ScriptableObject.CreateInstance<UITextureAtlas>();
            atlas.name = "Traffic++ " + name;
            atlas.material = atlasMaterial;

            sm_atlases[name] = atlas;

            return atlas;
        }
Пример #23
0
 public void Start()
 {
     tex = new Texture2D(2, 2);
     byte[] pngBytes = new byte[] {
         0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52,
         0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x40,0x08,0x00,0x00,0x00,0x00,0x8F,0x02,0x2E,
         0x02,0x00,0x00,0x01,0x57,0x49,0x44,0x41,0x54,0x78,0x01,0xA5,0x57,0xD1,0xAD,0xC4,
         0x30,0x08,0x83,0x81,0x32,0x4A,0x66,0xC9,0x36,0x99,0x85,0x45,0xBC,0x4E,0x74,0xBD,
         0x8F,0x9E,0x5B,0xD4,0xE8,0xF1,0x6A,0x7F,0xDD,0x29,0xB2,0x55,0x0C,0x24,0x60,0xEB,
         0x0D,0x30,0xE7,0xF9,0xF3,0x85,0x40,0x74,0x3F,0xF0,0x52,0x00,0xC3,0x0F,0xBC,0x14,
         0xC0,0xF4,0x0B,0xF0,0x3F,0x01,0x44,0xF3,0x3B,0x3A,0x05,0x8A,0x41,0x67,0x14,0x05,
         0x18,0x74,0x06,0x4A,0x02,0xBE,0x47,0x54,0x04,0x86,0xEF,0xD1,0x0A,0x02,0xF0,0x84,
         0xD9,0x9D,0x28,0x08,0xDC,0x9C,0x1F,0x48,0x21,0xE1,0x4F,0x01,0xDC,0xC9,0x07,0xC2,
         0x2F,0x98,0x49,0x60,0xE7,0x60,0xC7,0xCE,0xD3,0x9D,0x00,0x22,0x02,0x07,0xFA,0x41,
         0x8E,0x27,0x4F,0x31,0x37,0x02,0xF9,0xC3,0xF1,0x7C,0xD2,0x16,0x2E,0xE7,0xB6,0xE5,
         0xB7,0x9D,0xA7,0xBF,0x50,0x06,0x05,0x4A,0x7C,0xD0,0x3B,0x4A,0x2D,0x2B,0xF3,0x97,
         0x93,0x35,0x77,0x02,0xB8,0x3A,0x9C,0x30,0x2F,0x81,0x83,0xD5,0x6C,0x55,0xFE,0xBA,
         0x7D,0x19,0x5B,0xDA,0xAA,0xFC,0xCE,0x0F,0xE0,0xBF,0x53,0xA0,0xC0,0x07,0x8D,0xFF,
         0x82,0x89,0xB4,0x1A,0x7F,0xE5,0xA3,0x5F,0x46,0xAC,0xC6,0x0F,0xBA,0x96,0x1C,0xB1,
         0x12,0x7F,0xE5,0x33,0x26,0xD2,0x4A,0xFC,0x41,0x07,0xB3,0x09,0x56,0xE1,0xE3,0xA1,
         0xB8,0xCE,0x3C,0x5A,0x81,0xBF,0xDA,0x43,0x73,0x75,0xA6,0x71,0xDB,0x7F,0x0F,0x29,
         0x24,0x82,0x95,0x08,0xAF,0x21,0xC9,0x9E,0xBD,0x50,0xE6,0x47,0x12,0x38,0xEF,0x03,
         0x78,0x11,0x2B,0x61,0xB4,0xA5,0x0B,0xE8,0x21,0xE8,0x26,0xEA,0x69,0xAC,0x17,0x12,
         0x0F,0x73,0x21,0x29,0xA5,0x2C,0x37,0x93,0xDE,0xCE,0xFA,0x85,0xA2,0x5F,0x69,0xFA,
         0xA5,0xAA,0x5F,0xEB,0xFA,0xC3,0xA2,0x3F,0x6D,0xFA,0xE3,0xAA,0x3F,0xEF,0xFA,0x80,
         0xA1,0x8F,0x38,0x04,0xE2,0x8B,0xD7,0x43,0x96,0x3E,0xE6,0xE9,0x83,0x26,0xE1,0xC2,
         0xA8,0x2B,0x0C,0xDB,0xC2,0xB8,0x2F,0x2C,0x1C,0xC2,0xCA,0x23,0x2D,0x5D,0xFA,0xDA,
         0xA7,0x2F,0x9E,0xFA,0xEA,0xAB,0x2F,0xDF,0xF2,0xFA,0xFF,0x01,0x1A,0x18,0x53,0x83,
         0xC1,0x4E,0x14,0x1B,0x00,0x00,0x00,0x00,0x49,0x45,0x4E,0x44,0xAE,0x42,0x60,0x82,
     };
     tex.LoadImage(pngBytes);
 }
    static int LoadImage(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(byte[])))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                bool   o    = obj.LoadImage(arg0);
                LuaDLL.lua_pushboolean(L, o);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(byte[]), typeof(bool)))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                bool   arg1 = LuaDLL.lua_toboolean(L, 3);
                bool   o    = obj.LoadImage(arg0, arg1);
                LuaDLL.lua_pushboolean(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.LoadImage"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Пример #25
0
        private void addIIfilter()
        {
            //Loading Textures
            Texture2D unselected = new Texture2D(32, 32);
            Texture2D selected = new Texture2D(32, 32);
            Texture2D unselectedLegacy = new Texture2D(32, 32);
            Texture2D selectedLegacy = new Texture2D(32, 32);

            unselected.LoadImage(File.ReadAllBytes("GameData/ImpossibleInnovations/Plugins/PluginData/SmallLogo.png"));
            selected.LoadImage(File.ReadAllBytes("GameData/ImpossibleInnovations/Plugins/PluginData/SmallLogoON.png"));
            RUI.Icons.Selectable.Icon filterIcon = new RUI.Icons.Selectable.Icon("II_filter_icon", unselected, selected); //Defining filterIcon

            unselectedLegacy.LoadImage(File.ReadAllBytes("GameData/ImpossibleInnovations/Plugins/PluginData/SmallLogoGrey.png"));
            selectedLegacy.LoadImage(File.ReadAllBytes("GameData/ImpossibleInnovations/Plugins/PluginData/SmallLogoGreyON.png"));
            RUI.Icons.Selectable.Icon filterIconLegacy = new RUI.Icons.Selectable.Icon("II_filter_icon_legacy", unselectedLegacy, selectedLegacy); //Defining filterIconLegacy

            PartCategorizer.Category IIfilter = PartCategorizer.AddCustomFilter("Impossible Innovations", filterIcon, Color.white);

            //filters for all II parts
            PartCategorizer.AddCustomSubcategoryFilter(IIfilter, "All Impossible Innovations Parts", filterIcon, o => o.manufacturer == "Impossible Innovations" && !o.title.Contains("(LEGACY)"));
            PartCategorizer.AddCustomSubcategoryFilter(IIfilter, "Tanks", filterIcon, p => p.resourceInfos.Exists(q => q.resourceName == "Deuterium" || q.resourceName == "Tritium") && p.manufacturer == "Impossible Innovations");
            PartCategorizer.AddCustomSubcategoryFilter(IIfilter, "Engines", filterIcon, r => r.title.Contains("Fusion Engine") && r.manufacturer == "Impossible Innovations");
            PartCategorizer.AddCustomSubcategoryFilter(IIfilter, "CL-20 Boosters", filterIcon, s => s.resourceInfos.Exists(t => t.resourceName == "CL-20") && s.manufacturer == "Impossible Innovations");
            PartCategorizer.AddCustomSubcategoryFilter(IIfilter, "Ionized Wings", filterIcon, u => u.title.Contains("Ionized") && !u.title.Contains("(LEGACY)") && u.manufacturer == "Impossible Innovations");
            PartCategorizer.AddCustomSubcategoryFilter(IIfilter, "Legacy Parts", filterIconLegacy, v => v.title.Contains("(LEGACY)") && v.manufacturer == "Impossible Innovations");
        }
Пример #26
0
		/// <summary>
		/// Creates a new Texture2D from an embedded resource.
		/// </summary>
		/// <param name="resource">The location of the resource in the assembly.</param>
		/// <param name="width">The width of the texture.</param>
		/// <param name="height">The height of the texture.</param>
		/// <returns></returns>
		public static Texture2D FromResource (string resource, int width, int height) {
			var tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
			var iconStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource).ReadToEnd();
			tex.LoadImage(iconStream);
			tex.Apply();
			return tex;
		}
 public StateFundingApplicationLauncher()
 {
     View = new StateFundingHubView ();
       Texture2D Image = new Texture2D (2, 2);
       Image.LoadImage (File.ReadAllBytes ("GameData/StateFunding/assets/cashmoney.png"));
       ApplicationLauncherButton Button = ApplicationLauncher.Instance.AddModApplication (onTrue, onFalse, onHover, onHoverOut, onEnable, onDisable, ApplicationLauncher.AppScenes.SPACECENTER, Image);
 }
Пример #28
0
        // Initialize all custom GUI textures.
        static TextureResources()
        {
            warnIcon = new Texture2D(20, 20, TextureFormat.ARGB32, false);
            warnIcon.name = "SortingView_WarnIcon";
            warnIcon.hideFlags = HideFlags.HideAndDontSave;
            warnIcon.LoadImage(Convert.FromBase64String(warnIconEncode));

            contentBackGround0 = new Texture2D(24, 18, TextureFormat.ARGB32, false);
            contentBackGround0.name = "SortingView_ContentBackGround0";
            contentBackGround0.hideFlags = HideFlags.HideAndDontSave;
            contentBackGround0.LoadImage(Convert.FromBase64String(contentBackGroundEncode0));

            contentBackGround1 = new Texture2D(24, 18, TextureFormat.ARGB32, false);
            contentBackGround1.name = "SortingView_ContentBackGround1";
            contentBackGround1.hideFlags = HideFlags.HideAndDontSave;
            contentBackGround1.LoadImage(Convert.FromBase64String(contentBackGroundEncode1));

            layerBackGround = new Texture2D(64, 32, TextureFormat.ARGB32, false);
            layerBackGround.name = "SortingView_LayerBackGround";
            layerBackGround.hideFlags = HideFlags.HideAndDontSave;
            layerBackGround.LoadImage(Convert.FromBase64String(layerBackGroundEncode));

            layerBackGroundLight = new Texture2D(64, 32, TextureFormat.ARGB32, false);
            layerBackGroundLight.name = "SortingView_LayerBackGroundLight";
            layerBackGroundLight.hideFlags = HideFlags.HideAndDontSave;
            layerBackGroundLight.LoadImage(Convert.FromBase64String(layerBackGroundLightEncode));

            verticalMoveIcon = new Texture2D(20, 20, TextureFormat.ARGB32, false);
            verticalMoveIcon.name = "SortingView_VerticalMoveIcon";
            verticalMoveIcon.hideFlags = HideFlags.HideAndDontSave;
            verticalMoveIcon.LoadImage(Convert.FromBase64String(verticalMoveIconEncode));
        }
Пример #29
0
        /// <summary>
        /// This method is called when loading the tile.
        /// </summary>
        /// <param name="tile">Reference to tile</param>
        private void OnStartDownloadTile(OnlineMapsTile tile)
        {
            // Get local path.
            string path = GetTilePath(tile);

            // If the tile is cached.
            if (File.Exists(path))
            {
                // Load tile texture from cache.
                Texture2D tileTexture = new Texture2D(256, 256);
                tileTexture.LoadImage(File.ReadAllBytes(path));
                tileTexture.wrapMode = TextureWrapMode.Clamp;

                // Send texture to map.
                if (OnlineMaps.instance.target == OnlineMapsTarget.texture)
                {
                    tile.ApplyTexture(tileTexture);
                    OnlineMaps.instance.buffer.ApplyTile(tile);
                }
                else
                {
                    tile.texture = tileTexture;
                    tile.status = OnlineMapsTileStatus.loaded;
                }

                // Redraw map.
                OnlineMaps.instance.Redraw();
            }
            else
            {
                // If the tile is not cached, download tile with a standard loader.
                OnlineMaps.instance.StartDownloadTile(tile);
            }
        }
Пример #30
0
		/// <summary>
		/// Adds the button to the KSP toolbar.
		/// </summary>
		public void Add () {
//			_logger.Trace("Add");
			if (_button != null) {
				_logger.Debug("Button already added");
				return;
			}

			var texture = new Texture2D(38, 38, TextureFormat.ARGB32, false);
			
			var iconStream = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("ScienceChecklist.icons.icon.png").ReadToEnd ();
			
			texture.LoadImage(iconStream);
			texture.Apply();
			
//			_logger.Info("Adding button");
			_button = ApplicationLauncher.Instance.AddModApplication(
				OnToggleOn,
				OnToggleOff,
				null,
				null,
				null,
				null,
				ApplicationLauncher.AppScenes.SPACECENTER |
				ApplicationLauncher.AppScenes.FLIGHT |
				ApplicationLauncher.AppScenes.MAPVIEW |
				ApplicationLauncher.AppScenes.VAB |
				ApplicationLauncher.AppScenes.SPH |
				ApplicationLauncher.AppScenes.TRACKSTATION,
				texture);
		}
Пример #31
0
	public Texture2D ResolveMap(string map_name, object map_reference_value)
	{
		//for now we just get the map

		//create new map filename
		if(!(map_reference_value is MapReference)){
			throw new UnityException("Property is not a map!");
		}

		long handle = (map_reference_value as MapReference).m_nativeHandle;

		byte[] data = MaterialsBinding.m_cache.GetTexture(handle);

		if(data == null)
		{
			data = m_importer.GetMap(map_reference_value as MapReference, width, height);
			MaterialsBinding.m_cache.SetTexture(handle, data);
		}

		Texture2D texture = new Texture2D(width,height);
		texture.LoadImage(data);

		return texture;

	}
Пример #32
0
 public UnityEngine.Texture2D ToUnityType()
 {
     UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(1, 1);
     texture2D.LoadImage(pixels);
     texture2D.Apply();
     return(texture2D);
 }
		public static Texture2D LoadImageFromString(string baseEncodedString)
		{
			Texture2D tex = new Texture2D(2,2);
			if(!string.IsNullOrEmpty(baseEncodedString) && tex.LoadImage(Convert.FromBase64String(baseEncodedString)))
				return tex;
			else return null;
		}
Пример #34
0
 static public int LoadImage(IntPtr l)
 {
     try{
         UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
         System.Byte[]         a1;
         checkType(l, 2, out a1);
         System.Boolean ret = self.LoadImage(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
 static public int LoadImage(IntPtr l)
 {
     try {
         UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
         System.Byte[]         a1;
         checkArray(l, 2, out a1);
         var ret = self.LoadImage(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #36
0
 static int LoadImage(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
         byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
         bool   o    = obj.LoadImage(arg0);
         LuaDLL.lua_pushboolean(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Пример #37
0
        public bool LoadSharedObject()
        {
            var sectorName = GetSectorName(this);

            var colorPath    = Path.Combine(Application.persistentDataPath, "MiniMap/Colors_" + sectorName + ".png");
            var waypointPath = Path.Combine(Application.persistentDataPath, "MiniMap/Waypoints_" + sectorName + ".png");

            if (!File.Exists(colorPath) || !File.Exists(waypointPath))
            {
                return(false);
            }

            var colorBytes    = File.ReadAllBytes(colorPath);
            var waypointBytes = File.ReadAllBytes(waypointPath);

            if (colorBytes == null || waypointBytes == null)
            {
                return(false);
            }

            if (!Texture2D.LoadImage(colorBytes))
            {
                return(false);
            }

            if (!m_WaypointsTexture2D.LoadImage(waypointBytes))
            {
                Texture2D.SetPixels(Enumerable.Repeat(Color.black, Constants.MiniMapSectorSize * Constants.MiniMapSectorSize).ToArray());
                Texture2D.Apply();
                UncommittedPixelChanges = false;
                return(false);
            }

            for (int x = 0; x < Constants.MiniMapSectorSize; x++)
            {
                for (int y = 0; y < Constants.MiniMapSectorSize; y++)
                {
                    var cost = Colors.EightBitFromColor(m_WaypointsTexture2D.GetPixel(x, y));
                    MinCost = Mathf.Min(MinCost, cost);
                    m_Cost[(Constants.MiniMapSectorSize - y - 1) * Constants.MiniMapSectorSize + x] = cost;
                }
            }

            Texture2D.Apply();
            UncommittedPixelChanges = false;
            return(true);
        }
Пример #38
0
        private UnityEngine.Sprite CreateSprite(string filePath, int w = 112, int h = 112)
        {
            filePath = Path.Combine(UnderMod.GetGameDirectory(), "UnderMine_Data", "Managed", "VortexMods", "UnderMod", filePath);
            UnityEngine.Texture2D texture = null;
            byte[] fileData;

            if (File.Exists(filePath))
            {
                fileData = File.ReadAllBytes(filePath);
                texture  = new UnityEngine.Texture2D(w, h);
                texture.LoadImage(fileData);
            }
            else
            {
                API.instance.GetLogger().Error("Could not load texture: " + filePath);
            }

            Sprite sprite = Sprite.Create(texture, new UnityEngine.Rect(0, 0, texture.width, texture.height), new UnityEngine.Vector2(texture.width / 2, texture.height / 2));

            return(sprite);
        }
Пример #39
0
        /// <summary>
        /// Load texture from byte array
        /// </summary>
        /// <param name="p_Bytes">Raw Texture 2D data</param>
        /// <returns></returns>
        public static UnityEngine.Texture2D CreateFromRaw(byte[] p_Bytes)
        {
            if (p_Bytes != null && p_Bytes.Length > 0)
            {
                try
                {
                    var l_Texture = new UnityEngine.Texture2D(2, 2);
                    if (l_Texture.LoadImage(p_Bytes))
                    {
                        return(l_Texture);
                    }
                }
                catch (System.Exception l_Exception)
                {
                    Logger.Instance?.Error("[SDK.Unity][Texture2D.CreateFromRaw] Failed");
                    Logger.Instance?.Error(l_Exception);
                    return(null);
                }
            }

            return(null);
        }
Пример #40
0
        public static TmxImage FromXml(XElement elemImage, string prefix, string postfix)
        {
            TmxImage tmxImage = new TmxImage();

            tmxImage.AbsolutePath = TmxHelper.GetAttributeAsFullPath(elemImage, "source");
            tmxImage.ImageName    = $"{prefix}{Path.GetFileNameWithoutExtension(tmxImage.AbsolutePath)}{postfix}";
            int attributeAsInt  = TmxHelper.GetAttributeAsInt(elemImage, "width", 0);
            int attributeAsInt2 = TmxHelper.GetAttributeAsInt(elemImage, "height", 0);

            tmxImage.Size = new Size(attributeAsInt, attributeAsInt2);
            bool flag = true;

            if (!Settings.IsAutoExporting)
            {
                try
                {
                    if (!tmxImage.Size.IsEmpty)
                    {
                        UnityEngine.Texture2D texture2 = new UnityEngine.Texture2D(tmxImage.Size.Width, tmxImage.Size.Height);


                        //bitmapInfo.AlphaType = SKAlphaType.Unpremul;
                        //bitmapInfo.Width = tmxImage.Size.Width;
                        //bitmapInfo.Height = tmxImage.Size.Height;
                        var v = File.ReadAllBytes(tmxImage.AbsolutePath);
                        //   ImageMagick.MagickImage img = new ImageMagick.MagickImage(v);

                        texture2.LoadImage(v);
                        //texture2.LoadRawTextureData(v);
                        tmxImage.ImageBitmap = texture2;
                        //using (FileStream stream = File.Open(tmxImage.AbsolutePath, FileMode.Open))
                        //{


                        //                      tmxImage.ImageBitmap = SKBitmap.Decode(stream, bitmapInfo);
                        //}
                    }
                    else
                    {
                        UnityEngine.Texture2D texture2 = new UnityEngine.Texture2D(tmxImage.Size.Width, tmxImage.Size.Height);

                        var v = File.ReadAllBytes(tmxImage.AbsolutePath);
                        texture2.LoadImage(v);
                        tmxImage.ImageBitmap = texture2;
                        flag = false;
                    }
                    TmxImage tmxImage2 = tmxImage;
                    tmxImage2.Size = new Size(tmxImage2.ImageBitmap.width, tmxImage.ImageBitmap.height);
                }
                catch (FileNotFoundException inner)
                {
                    throw new TmxException($"Image file not found: {tmxImage.AbsolutePath}", inner);
                }
                catch (Exception ex)
                {
                    Logger.WriteError("Skia Library exception: {0}\n\tStack:\n{1}", ex.Message, ex.StackTrace);
                    Settings.DisablePreviewing();
                }
            }
            tmxImage.TransparentColor = TmxHelper.GetAttributeAsString(elemImage, "trans", "");
            if (!string.IsNullOrEmpty(tmxImage.TransparentColor) && tmxImage.ImageBitmap != null)
            {
                if (flag)
                {
                    Logger.WriteInfo("Removing alpha from transparent pixels.");
                    UnityEngine.Color color = TmxHelper.ColorFromHtml(tmxImage.TransparentColor);
                    color.a = 0;
                    for (int i = 0; i < tmxImage.ImageBitmap.width; i++)
                    {
                        for (int j = 0; j < tmxImage.ImageBitmap.height; j++)
                        {
                            UnityEngine.Color pixel = tmxImage.ImageBitmap.GetPixel(i, j);
                            if (pixel.r == color.r && pixel.g == color.g && pixel.b == color.b)
                            {
                                tmxImage.ImageBitmap.SetPixel(i, j, color);
                            }
                        }
                    }
                }
                else
                {
                    Logger.WriteWarning("Cannot make transparent pixels for viewing purposes. Save tileset with newer verion of Tiled.");
                }
            }
            return(tmxImage);
        }
Пример #41
0
        void CreateGameObjects(Transform parent, byte[] bytes)
        {
            var primitives         = new List <Primitive>(gltf.meshes.Length);
            var meshPrimitiveIndex = new int[gltf.meshes.Length + 1];

            Texture2D[] images = null;

            resources = new List <UnityEngine.Object>();

            if (gltf.images != null)
            {
                images = new Texture2D[gltf.images.Length];
                for (int i = 0; i < images.Length; i++)
                {
                    var img = gltf.images[i];
                    if (img.mimeType == "image/jpeg" || img.mimeType == "image/png")
                    {
                        if (img.bufferView >= 0)
                        {
                            var bufferView = gltf.bufferViews[img.bufferView];
                            var chunk      = binChunks[bufferView.buffer];
                            var imgBytes   = Extractor.CreateBufferViewCopy(bufferView, chunk, bytes);
                            var txt        = new UnityEngine.Texture2D(4, 4);
                            txt.name = string.IsNullOrEmpty(img.name) ? string.Format("glb embed texture {0}", i) : img.name;
                            txt.LoadImage(imgBytes);
                            images[i] = txt;
                            resources.Add(txt);
                        }
                        else
                        if (!string.IsNullOrEmpty(img.uri))
                        {
                            Debug.LogError("Loading from URI not supported");
                        }
                    }
                    else
                    {
                        Debug.LogErrorFormat("Unknown image mime type {0}", img.mimeType);
                    }
                }
            }

            if (gltf.materials != null)
            {
                materials = new UnityEngine.Material[gltf.materials.Length];
                for (int i = 0; i < materials.Length; i++)
                {
                    materials[i] = materialGenerator.GenerateMaterial(gltf.materials[i], gltf.textures, images, resources);
                }
            }

            //foreach( var mesh in gltf.meshes ) {
            for (int meshIndex = 0; meshIndex < gltf.meshes.Length; meshIndex++)
            {
                var mesh = gltf.meshes[meshIndex];
                meshPrimitiveIndex[meshIndex] = primitives.Count;

                foreach (var primitive in mesh.primitives)
                {
                    // index
                    var accessor   = gltf.accessors[primitive.indices];
                    var bufferView = gltf.bufferViews[accessor.bufferView];
                    var buffer     = bufferView.buffer;

                    GlbBinChunk chunk = binChunks[buffer];
                    Assert.AreEqual(accessor.typeEnum, GLTFAccessorAttributeType.SCALAR);
                    //Assert.AreEqual(accessor.count * GetLength(accessor.typeEnum) * 4 , (int) chunk.length);
                    int[] indices = null;
                    switch (accessor.componentType)
                    {
                    case GLTFComponentType.UnsignedByte:
                        indices = Extractor.GetIndicesUInt8(bytes, accessor.byteOffset + bufferView.byteOffset + chunk.start, accessor.count);
                        break;

                    case GLTFComponentType.UnsignedShort:
                        indices = Extractor.GetIndicesUInt16(bytes, accessor.byteOffset + bufferView.byteOffset + chunk.start, accessor.count);
                        break;

                    case GLTFComponentType.UnsignedInt:
                        indices = Extractor.GetIndicesUInt32(bytes, accessor.byteOffset + bufferView.byteOffset + chunk.start, accessor.count);
                        break;

                    default:
                        Debug.LogErrorFormat("Invalid index format {0}", accessor.componentType);
                        break;
                    }

                    // position
                    int pos = primitive.attributes.POSITION;
                    Assert.IsTrue(pos >= 0);
                    #if DEBUG
                    Assert.AreEqual(GetAccessorTye(gltf.accessors[pos].typeEnum), typeof(Vector3));
#endif
                    var positions = gltf.IsAccessorInterleaved(pos)
                                ? GetAccessorDataInterleaved <Vector3>(pos, ref bytes, Extractor.GetVector3sInterleaved)
                                : GetAccessorData <Vector3>(pos, ref bytes, Extractor.GetVector3s);

                    Vector3[] normals = null;
                    if (primitive.attributes.NORMAL >= 0)
                    {
                        #if DEBUG
                        Assert.AreEqual(GetAccessorTye(gltf.accessors[primitive.attributes.NORMAL].typeEnum), typeof(Vector3));
                        #endif
                        normals = gltf.IsAccessorInterleaved(pos)
                                                    ? GetAccessorDataInterleaved <Vector3>(primitive.attributes.NORMAL, ref bytes, Extractor.GetVector3sInterleaved)
                                                    : GetAccessorData <Vector3>(primitive.attributes.NORMAL, ref bytes, Extractor.GetVector3s);
                    }

                    Vector2[] uvs0 = GetUvs(primitive.attributes.TEXCOORD_0, ref bytes);
                    Vector2[] uvs1 = GetUvs(primitive.attributes.TEXCOORD_1, ref bytes);

                    Vector4[] tangents = null;
                    if (primitive.attributes.TANGENT >= 0)
                    {
                        #if DEBUG
                        Assert.AreEqual(GetAccessorTye(gltf.accessors[primitive.attributes.TANGENT].typeEnum), typeof(Vector4));
                        #endif
                        tangents = gltf.IsAccessorInterleaved(pos)
                                            ? GetAccessorDataInterleaved <Vector4>(primitive.attributes.TANGENT, ref bytes, Extractor.GetVector4sInterleaved)
                                                : GetAccessorData <Vector4>(primitive.attributes.TANGENT, ref bytes, Extractor.GetVector4s);
                    }

                    Color32[] colors32;
                    Color[]   colors;
                    GetColors(primitive.attributes.COLOR_0, ref bytes, out colors32, out colors);

                    var msh = new UnityEngine.Mesh();
                    msh.name     = mesh.name;
                    msh.vertices = positions;
                    msh.SetIndices(indices, MeshTopology.Triangles, 0);
                    if (uvs0 != null)
                    {
                        msh.uv = uvs0;
                    }
                    if (uvs1 != null)
                    {
                        msh.uv2 = uvs1;
                    }
                    if (normals != null)
                    {
                        msh.normals = normals;
                    }
                    else
                    {
                        msh.RecalculateNormals();
                    }
                    if (colors != null)
                    {
                        msh.colors = colors;
                    }
                    else if (colors32 != null)
                    {
                        msh.colors32 = colors32;
                    }
                    if (tangents != null)
                    {
                        msh.tangents = tangents;
                    }
                    else
                    {
                        msh.RecalculateTangents();
                    }
                    primitives.Add(new Primitive(msh, primitive.material));
                    resources.Add(msh);
                }
            }

            meshPrimitiveIndex[gltf.meshes.Length] = primitives.Count;

            var nodes     = new Transform[gltf.nodes.Length];
            var relations = new Dictionary <uint, uint>();

            for (uint nodeIndex = 0; nodeIndex < gltf.nodes.Length; nodeIndex++)
            {
                var node = gltf.nodes[nodeIndex];

                if (node.children == null && node.mesh < 0)
                {
                    continue;
                }

                var go = new GameObject(node.name ?? "Node");
                nodes[nodeIndex] = go.transform;

                if (node.children != null)
                {
                    foreach (var child in node.children)
                    {
                        relations[child] = nodeIndex;
                    }
                }

                if (node.matrix != null)
                {
                    Matrix4x4 m = new Matrix4x4();
                    m.m00 = node.matrix[0];
                    m.m10 = node.matrix[1];
                    m.m20 = node.matrix[2];
                    m.m30 = node.matrix[3];
                    m.m01 = node.matrix[4];
                    m.m11 = node.matrix[5];
                    m.m21 = node.matrix[6];
                    m.m31 = node.matrix[7];
                    m.m02 = node.matrix[8];
                    m.m12 = node.matrix[9];
                    m.m22 = node.matrix[10];
                    m.m32 = node.matrix[11];
                    m.m03 = node.matrix[12];
                    m.m13 = node.matrix[13];
                    m.m23 = node.matrix[14];
                    m.m33 = node.matrix[15];

                    if (m.ValidTRS())
                    {
                        go.transform.localPosition = new Vector3(m.m03, m.m13, m.m23);
                        go.transform.localRotation = m.rotation;
                        go.transform.localScale    = m.lossyScale;
                    }
                    else
                    {
                        Debug.LogErrorFormat("Invalid matrix on node {0}", nodeIndex);
                    }
                }
                else
                {
                    if (node.translation != null)
                    {
                        Assert.AreEqual(node.translation.Length, 3);
                        go.transform.localPosition = new Vector3(
                            node.translation[0],
                            node.translation[1],
                            node.translation[2]
                            );
                    }
                    if (node.rotation != null)
                    {
                        Assert.AreEqual(node.rotation.Length, 4);
                        go.transform.localRotation = new Quaternion(
                            node.rotation[0],
                            node.rotation[1],
                            node.rotation[2],
                            node.rotation[3]
                            );
                    }
                    if (node.scale != null)
                    {
                        Assert.AreEqual(node.scale.Length, 3);
                        go.transform.localScale = new Vector3(
                            node.scale[0],
                            node.scale[1],
                            node.scale[2]
                            );
                    }
                }

                if (node.mesh >= 0)
                {
                    int        end    = meshPrimitiveIndex[node.mesh + 1];
                    GameObject meshGo = null;
                    for (int i = meshPrimitiveIndex[node.mesh]; i < end; i++)
                    {
                        if (meshGo == null)
                        {
                            meshGo = go;
                        }
                        else
                        {
                            meshGo = new GameObject("Primitive");
                            meshGo.transform.SetParent(go.transform, false);
                        }
                        var mf = meshGo.AddComponent <MeshFilter>();
                        mf.mesh = primitives[i].mesh;
                        var mr = meshGo.AddComponent <MeshRenderer>();

                        int materialIndex = primitives[i].materialIndex;
                        if (materials != null && materialIndex >= 0 && materialIndex < materials.Length)
                        {
                            mr.material = materials[primitives[i].materialIndex];
                        }
                        else
                        {
                            mr.material = materialGenerator.GetDefaultMaterial();
                        }
                    }
                }
            }

            foreach (var rel in relations)
            {
                nodes[rel.Key]?.SetParent(nodes[rel.Value], false);
            }

            foreach (var scene in gltf.scenes)
            {
                var go = new GameObject(scene.name ?? "Scene");
                go.transform.SetParent(parent, false);

                // glTF to unity space ( -z forward to z forward )
                go.transform.localScale = new Vector3(1, 1, -1);

                foreach (var nodeIndex in scene.nodes)
                {
                    nodes[nodeIndex]?.SetParent(go.transform, false);
                }
            }

            foreach (var bv in gltf.bufferViews)
            {
                if (gltf.buffers[bv.buffer].uri == null)
                {
                }
            }
        }
        /// <summary>
        /// Read the data into the specified value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <param name="reader">Reader.</param>
        public override void ReadInto(object value, ISaveGameReader reader)
        {
            UnityEngine.Texture2D texture2D = (UnityEngine.Texture2D)value;
            foreach (string property in reader.Properties)
            {
                switch (property)
                {
                case "width":
                    reader.ReadProperty <System.Int32>();
                    break;

                case "height":
                    reader.ReadProperty <System.Int32>();
                    break;

                case "rawTextureData":
                    texture2D.LoadImage(reader.ReadProperty <byte[]>());
                    texture2D.Apply();
                    break;

                case "dimension":
                    reader.ReadProperty <UnityEngine.Rendering.TextureDimension>();
                    break;

                case "filterMode":
                    texture2D.filterMode = reader.ReadProperty <UnityEngine.FilterMode>();
                    break;

                case "anisoLevel":
                    texture2D.anisoLevel = reader.ReadProperty <System.Int32>();
                    break;

                case "wrapMode":
                    texture2D.wrapMode = reader.ReadProperty <UnityEngine.TextureWrapMode>();
                    break;

                case "wrapModeU":
#if UNITY_2017_1_OR_NEWER
                    texture2D.wrapModeU = reader.ReadProperty <UnityEngine.TextureWrapMode>();
#else
                    reader.ReadProperty <UnityEngine.TextureWrapMode>();
#endif
                    break;

                case "wrapModeV":
#if UNITY_2017_1_OR_NEWER
                    texture2D.wrapModeV = reader.ReadProperty <UnityEngine.TextureWrapMode>();
#else
                    reader.ReadProperty <UnityEngine.TextureWrapMode>();
#endif
                    break;

                case "wrapModeW":
#if UNITY_2017_1_OR_NEWER
                    texture2D.wrapModeW = reader.ReadProperty <UnityEngine.TextureWrapMode>();
#else
                    reader.ReadProperty <UnityEngine.TextureWrapMode>();
#endif
                    break;

                case "mipMapBias":
                    texture2D.mipMapBias = reader.ReadProperty <System.Single>();
                    break;

                case "name":
                    texture2D.name = reader.ReadProperty <System.String>();
                    break;

                case "hideFlags":
                    texture2D.hideFlags = reader.ReadProperty <UnityEngine.HideFlags>();
                    break;
                }
            }
        }
Пример #43
0
        bool CreateGameObjects(Root gltf, Transform parent)
        {
            var primitives         = new List <Primitive>(gltf.meshes.Length);
            var meshPrimitiveIndex = new int[gltf.meshes.Length + 1];

            resources = new List <UnityEngine.Object>();

            if (gltf.images != null)
            {
                if (images == null)
                {
                    images = new Texture2D[gltf.images.Length];
                }
                else
                {
                    Assert.AreEqual(images.Length, gltf.images.Length);
                }
                for (int i = 0; i < images.Length; i++)
                {
                    if (images[i] != null)
                    {
                        resources.Add(images[i]);
                    }
                    var  img            = gltf.images[i];
                    bool knownImageType = false;
                    if (string.IsNullOrEmpty(img.mimeType))
                    {
                        Debug.LogWarning("Image is missing mime type");
                        knownImageType = img.uri.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                                         img.uri.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
                                         img.uri.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase);
                    }
                    else
                    {
                        knownImageType = img.mimeType == "image/jpeg" || img.mimeType == "image/png";
                    }

                    if (knownImageType)
                    {
                        if (img.bufferView >= 0)
                        {
                            var bufferView = gltf.bufferViews[img.bufferView];
                            var buffer     = GetBuffer(bufferView.buffer);
                            var chunk      = binChunks[bufferView.buffer];
                            var imgBytes   = Extractor.CreateBufferViewCopy(bufferView, chunk, buffer);
                            var txt        = new UnityEngine.Texture2D(4, 4);
                            txt.name = string.IsNullOrEmpty(img.name) ? string.Format("glb embed texture {0}", i) : img.name;
                            txt.LoadImage(imgBytes);
                            images[i] = txt;
                            resources.Add(txt);
                        }
                    }
                }
            }

            if (gltf.materials != null)
            {
                materials = new UnityEngine.Material[gltf.materials.Length];
                for (int i = 0; i < materials.Length; i++)
                {
                    materials[i] = materialGenerator.GenerateMaterial(gltf.materials[i], gltf.textures, images, resources);
                }
            }

            //foreach( var mesh in gltf.meshes ) {
            for (int meshIndex = 0; meshIndex < gltf.meshes.Length; meshIndex++)
            {
                var mesh = gltf.meshes[meshIndex];
                meshPrimitiveIndex[meshIndex] = primitives.Count;

                foreach (var primitive in mesh.primitives)
                {
                    // index
                    var accessor    = gltf.accessors[primitive.indices];
                    var bufferView  = gltf.bufferViews[accessor.bufferView];
                    var bufferIndex = bufferView.buffer;
                    var buffer      = GetBuffer(bufferIndex);

                    GlbBinChunk chunk = binChunks[bufferIndex];
                    Assert.AreEqual(accessor.typeEnum, GLTFAccessorAttributeType.SCALAR);
                    //Assert.AreEqual(accessor.count * GetLength(accessor.typeEnum) * 4 , (int) chunk.length);
                    int[] indices = null;
                    switch (accessor.componentType)
                    {
                    case GLTFComponentType.UnsignedByte:
                        indices = Extractor.GetIndicesUInt8(buffer, accessor.byteOffset + bufferView.byteOffset + chunk.start, accessor.count);
                        break;

                    case GLTFComponentType.UnsignedShort:
                        indices = Extractor.GetIndicesUInt16(buffer, accessor.byteOffset + bufferView.byteOffset + chunk.start, accessor.count);
                        break;

                    case GLTFComponentType.UnsignedInt:
                        indices = Extractor.GetIndicesUInt32(buffer, accessor.byteOffset + bufferView.byteOffset + chunk.start, accessor.count);
                        break;

                    default:
                        Debug.LogErrorFormat("Invalid index format {0}", accessor.componentType);
                        return(false);
                    }

                    #if DEBUG
                    if (accessor.min != null && accessor.min.Length > 0 && accessor.max != null && accessor.max.Length > 0)
                    {
                        int minInt   = (int)accessor.min[0];
                        int maxInt   = (int)accessor.max[0];
                        int minIndex = int.MaxValue;
                        int maxIndex = int.MinValue;
                        foreach (var index in indices)
                        {
                            Assert.IsTrue(index >= minInt);
                            Assert.IsTrue(index <= maxInt);
                            minIndex = Math.Min(minIndex, index);
                            maxIndex = Math.Max(maxIndex, index);
                        }
                        if (minIndex != minInt ||
                            maxIndex != maxInt
                            )
                        {
                            Debug.LogErrorFormat("Faulty index bounds: is {0}:{1} expected:{2}:{3}", minIndex, maxIndex, minInt, maxInt);
                        }
                    }
                    #endif

                    // position
                    int pos = primitive.attributes.POSITION;
                    Assert.IsTrue(pos >= 0);
                    #if DEBUG
                    Assert.AreEqual(GetAccessorTye(gltf.accessors[pos].typeEnum), typeof(Vector3));
                    #endif
                    var positions = gltf.IsAccessorInterleaved(pos)
                                ? GetAccessorDataInterleaved <Vector3>(gltf, pos, ref buffer, Extractor.GetVector3sInterleaved)
                                : GetAccessorData <Vector3>(gltf, pos, ref buffer, Extractor.GetVector3s);

                    #if DEBUG
                    var     posAcc = gltf.accessors[pos];
                    Vector3 minPos = new Vector3((float)posAcc.min[0], (float)posAcc.min[1], (float)posAcc.min[2]);
                    Vector3 maxPos = new Vector3((float)posAcc.max[0], (float)posAcc.max[1], (float)posAcc.max[2]);
                    foreach (var p in positions)
                    {
                        if (!(p.x >= minPos.x &&
                              p.y >= minPos.y &&
                              p.z >= minPos.z &&
                              p.x <= maxPos.x &&
                              p.y <= maxPos.y &&
                              p.z <= maxPos.z
                              ))
                        {
                            Debug.LogError("Vertex outside of limits");
                            break;
                        }
                    }

                    var pUsage = new int[positions.Length];
                    foreach (var index in indices)
                    {
                        pUsage[index] += 1;
                    }
                    int pMin = int.MaxValue;
                    foreach (var u in pUsage)
                    {
                        pMin = Math.Min(pMin, u);
                    }
                    if (pMin < 1)
                    {
                        Debug.LogError("Unused vertices");
                    }
                    #endif


                    Vector3[] normals = null;
                    if (primitive.attributes.NORMAL >= 0)
                    {
                        #if DEBUG
                        Assert.AreEqual(GetAccessorTye(gltf.accessors[primitive.attributes.NORMAL].typeEnum), typeof(Vector3));
                        #endif
                        normals = gltf.IsAccessorInterleaved(pos)
                                                    ? GetAccessorDataInterleaved <Vector3>(gltf, primitive.attributes.NORMAL, ref buffer, Extractor.GetVector3sInterleaved)
                                                    : GetAccessorData <Vector3>(gltf, primitive.attributes.NORMAL, ref buffer, Extractor.GetVector3s);
                    }

                    Vector2[] uvs0 = GetUvs(gltf, primitive.attributes.TEXCOORD_0, ref buffer);
                    Vector2[] uvs1 = GetUvs(gltf, primitive.attributes.TEXCOORD_1, ref buffer);

                    Vector4[] tangents = null;
                    if (primitive.attributes.TANGENT >= 0)
                    {
                        #if DEBUG
                        Assert.AreEqual(GetAccessorTye(gltf.accessors[primitive.attributes.TANGENT].typeEnum), typeof(Vector4));
                        #endif
                        tangents = gltf.IsAccessorInterleaved(pos)
                                            ? GetAccessorDataInterleaved <Vector4>(gltf, primitive.attributes.TANGENT, ref buffer, Extractor.GetVector4sInterleaved)
                                                : GetAccessorData <Vector4>(gltf, primitive.attributes.TANGENT, ref buffer, Extractor.GetVector4s);
                    }

                    Color32[] colors32;
                    Color[]   colors;
                    GetColors(gltf, primitive.attributes.COLOR_0, ref buffer, out colors32, out colors);

                    var msh = new UnityEngine.Mesh();
                    if (positions.Length > 65536)
                    {
#if UNITY_2017_3_OR_NEWER
                        msh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
#else
                        throw new System.Exception("Meshes with more than 65536 vertices are only supported from Unity 2017.3 onwards.");
#endif
                    }
                    msh.name     = mesh.name;
                    msh.vertices = positions;
                    msh.SetIndices(indices, MeshTopology.Triangles, 0);
                    if (uvs0 != null)
                    {
                        msh.uv = uvs0;
                    }
                    if (uvs1 != null)
                    {
                        msh.uv2 = uvs1;
                    }
                    if (normals != null)
                    {
                        msh.normals = normals;
                    }
                    else
                    {
                        msh.RecalculateNormals();
                    }
                    if (colors != null)
                    {
                        msh.colors = colors;
                    }
                    else if (colors32 != null)
                    {
                        msh.colors32 = colors32;
                    }
                    if (tangents != null)
                    {
                        msh.tangents = tangents;
                    }
                    else
                    {
                        msh.RecalculateTangents();
                    }
                    primitives.Add(new Primitive(msh, primitive.material));
                    resources.Add(msh);
                }
            }

            meshPrimitiveIndex[gltf.meshes.Length] = primitives.Count;

            var nodes     = new Transform[gltf.nodes.Length];
            var relations = new Dictionary <uint, uint>();

            for (uint nodeIndex = 0; nodeIndex < gltf.nodes.Length; nodeIndex++)
            {
                var node = gltf.nodes[nodeIndex];

                if (node.children == null && node.mesh < 0)
                {
                    continue;
                }

                var go = new GameObject(node.name ?? "Node");
                nodes[nodeIndex] = go.transform;

                if (node.children != null)
                {
                    foreach (var child in node.children)
                    {
                        relations[child] = nodeIndex;
                    }
                }

                if (node.matrix != null)
                {
                    Matrix4x4 m = new Matrix4x4();
                    m.m00 = node.matrix[0];
                    m.m10 = node.matrix[1];
                    m.m20 = node.matrix[2];
                    m.m30 = node.matrix[3];
                    m.m01 = node.matrix[4];
                    m.m11 = node.matrix[5];
                    m.m21 = node.matrix[6];
                    m.m31 = node.matrix[7];
                    m.m02 = node.matrix[8];
                    m.m12 = node.matrix[9];
                    m.m22 = node.matrix[10];
                    m.m32 = node.matrix[11];
                    m.m03 = node.matrix[12];
                    m.m13 = node.matrix[13];
                    m.m23 = node.matrix[14];
                    m.m33 = node.matrix[15];

                    if (m.ValidTRS())
                    {
                        go.transform.localPosition = new Vector3(m.m03, m.m13, m.m23);
                        go.transform.localRotation = m.rotation;
                        go.transform.localScale    = m.lossyScale;
                    }
                    else
                    {
                        Debug.LogErrorFormat("Invalid matrix on node {0}", nodeIndex);
                        return(false);
                    }
                }
                else
                {
                    if (node.translation != null)
                    {
                        Assert.AreEqual(node.translation.Length, 3);
                        go.transform.localPosition = new Vector3(
                            node.translation[0],
                            node.translation[1],
                            node.translation[2]
                            );
                    }
                    if (node.rotation != null)
                    {
                        Assert.AreEqual(node.rotation.Length, 4);
                        go.transform.localRotation = new Quaternion(
                            node.rotation[0],
                            node.rotation[1],
                            node.rotation[2],
                            node.rotation[3]
                            );
                    }
                    if (node.scale != null)
                    {
                        Assert.AreEqual(node.scale.Length, 3);
                        go.transform.localScale = new Vector3(
                            node.scale[0],
                            node.scale[1],
                            node.scale[2]
                            );
                    }
                }

                if (node.mesh >= 0)
                {
                    int        end    = meshPrimitiveIndex[node.mesh + 1];
                    GameObject meshGo = null;
                    for (int i = meshPrimitiveIndex[node.mesh]; i < end; i++)
                    {
                        if (meshGo == null)
                        {
                            meshGo = go;
                        }
                        else
                        {
                            meshGo = new GameObject("Primitive");
                            meshGo.transform.SetParent(go.transform, false);
                        }
                        var mf = meshGo.AddComponent <MeshFilter>();
                        mf.mesh = primitives[i].mesh;
                        var mr = meshGo.AddComponent <MeshRenderer>();

                        int materialIndex = primitives[i].materialIndex;
                        if (materials != null && materialIndex >= 0 && materialIndex < materials.Length)
                        {
                            mr.material = materials[primitives[i].materialIndex];
                        }
                        else
                        {
                            mr.material = materialGenerator.GetDefaultMaterial();
                        }
                    }
                }
            }

            foreach (var rel in relations)
            {
                nodes[rel.Key]?.SetParent(nodes[rel.Value], false);
            }

            foreach (var scene in gltf.scenes)
            {
                var go = new GameObject(scene.name ?? "Scene");
                go.transform.SetParent(parent, false);

                // glTF to unity space ( -z forward to z forward )
                go.transform.localScale = new Vector3(1, 1, -1);

                foreach (var nodeIndex in scene.nodes)
                {
                    nodes[nodeIndex]?.SetParent(go.transform, false);
                }
            }

            foreach (var bv in gltf.bufferViews)
            {
                if (gltf.buffers[bv.buffer].uri == null)
                {
                }
            }
            return(true);
        }