Пример #1
0
    public override Texture2D LoadImageAt(int index, bool Alpha)
    {
        switch (_RES)
        {
        case GAME_UW2:
        {
            return(extractUW2Bitmap("data\\byt.ark", index, Alpha));
        }

        default:
        {
            if (File.Exists(BasePath + FilePaths[index].Replace(".", "_") + "\\001.tga"))
            {
                return(TGALoader.LoadTGA(BasePath + FilePaths[index].Replace(".", "_") + "\\001.tga"));
            }
            if (currentIndex != index)
            {                    //Only load from disk if the image to bring back has changed.
                DataLoaded = false;
                Path       = FilePaths[index];
                LoadImageFile();
            }
            return(Image(ImageFileData, 0, 320, 200, "name_goes_here", GameWorldController.instance.palLoader.Palettes[PaletteIndices[index]], Alpha));
        }
        }
    }
Пример #2
0
        private void LoadTGATextures(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 texture that's getting pulled from the pk3 file.
                if (pk3.ContainsEntry(tex.Name + ".tga"))
                {
                    Texture2D readyTex = new Texture2D(4, 4);
                    var       entry    = pk3 [tex.Name + ".tga"];
                    using (var stream = entry.OpenReader())
                    {
                        var ms = new MemoryStream();
                        entry.Extract(ms);
                        readyTex = TGALoader.LoadTGA(ms);
                    }

                    readyTex.name       = tex.Name;
                    readyTex.filterMode = FilterMode.Trilinear;
                    readyTex.Compress(true);

                    if (readyTextures.ContainsKey(tex.Name))
                    {
                        Debug.Log("Updating texture with name " + tex.Name + ".tga");
                        readyTextures [tex.Name] = readyTex;
                    }
                    else
                    {
                        readyTextures.Add(tex.Name, readyTex);
                    }
                }
            }
        }
Пример #3
0
    /*public GRLoader(int File, string AuxPalToUse, int AuxPalIndex)
     * {
     *      if (AuxPalIndex!=-1)
     *      {
     *              useOverrideAuxPalIndex=true;
     *              //OverrideAuxPalIndex=OverrideAuxPalIndex	;
     *      }
     *      AuxPalPath=AuxPalToUse;
     *      FileToLoad=File;
     *      LoadImageFile();
     * }*/

    public override bool LoadImageFile()
    {
        string ModPath = BasePath + pathGR[FileToLoad].Replace("--", sep.ToString()).Replace(".", "_");

        if (Directory.Exists(ModPath))
        {
            LoadMod = true;
        }
        if (!DataLoader.ReadStreamFile(BasePath + pathGR[FileToLoad].Replace("--", sep.ToString()), out ImageFileData))
        {
            Debug.Log("Unable to load " + BasePath + pathGR[FileToLoad].Replace("--", sep.ToString()));
            return(false);
        }
        else
        {
            NoOfImages = (int)DataLoader.getValAtAddress(ImageFileData, 1, 16);
            ImageCache = new  Texture2D[NoOfImages];
            if (LoadMod)
            {                    //Load up modded image data at the path
                for (int i = 0; i <= ImageCache.GetUpperBound(0); i++)
                {
                    if (File.Exists(ModPath + sep + i.ToString("d3") + ".tga"))
                    {
                        ImageCache[i] = TGALoader.LoadTGA(ModPath + sep + i.ToString("d3") + ".tga");
                    }
                }
            }
            ImageFileDataLoaded = true;
            return(true);
        }
    }
Пример #4
0
        public void Awake()
        {
            var x = Screen.width / 2 - _width / 2;
            var y = Screen.height / 2 - _height / 2;

            _atlas      = TGALoader.LoadTGA($"{Central.Instance.HomePath}/resources/icons.tga", false);
            _windowRect = new Rect(x, y, _width, _height);

            _coordsCache  = new List <Rect>();
            _spritesCache = new List <Rect>();

            _itemNameStyle = new GUIStyle()
            {
                fixedHeight = 64,
                fontSize    = 12,
                fontStyle   = FontStyle.BoldAndItalic,
                wordWrap    = true
            };

            _itemNameStyle.normal.textColor = Color.yellow;
            _itemNameStyle.alignment        = TextAnchor.MiddleCenter;

            _itemSimilarStyle = new GUIStyle(_itemNameStyle)
            {
                fontSize    = 10,
                fontStyle   = FontStyle.Bold,
                fixedHeight = 20,
                fixedWidth  = 20
            };
            _itemSimilarStyle.normal.textColor = Color.white;
        }
Пример #5
0
        public bool GetMapPreview(string Mapname, out Texture2D preview)
        {
            preview = new Texture2D(1, 1);
            if (!isReady || Mapname == "")
            {
                return(false);
            }

            var mapPreviewPath = Path.Combine(MapFitPath, Mapname + ".tga").ToUpper();
            var fileData       = MechCommanderUnity.Instance.FileManager.File(mapPreviewPath);

            if (fileData != null)
            {
                MechCommanderUnity.LogMessage("TGA file " + mapPreviewPath);
                preview = TGALoader.LoadTGA(new MemoryStream(fileData));
                return(true);
            }
            else
            {
                var missionFile = new FITFile(MechCommanderUnity.Instance.FileManager.File(MCGExtensions.PathCombine(new string[] { "missions", Mapname + ".fit" })));
                missionFile.SeekSection("TerrainSystem");
                missionFile.GetString("TerrainFileName", out string terrainFileName);
                mapPreviewPath = Path.Combine(MapFitPath, terrainFileName + ".tga").ToUpper();
                fileData       = MechCommanderUnity.Instance.FileManager.File(mapPreviewPath);
                if (fileData != null)
                {
                    MechCommanderUnity.LogMessage("TGA file DIFFERENT NAME " + mapPreviewPath);
                    preview = TGALoader.LoadTGA(new MemoryStream(fileData));
                    return(true);
                }
            }

            MechCommanderUnity.LogMessage("Can´t Find TGA file " + mapPreviewPath);
            return(false);
        }
Пример #6
0
    // Start is called before the first frame update
    void Start()
    {
        Material   mat     = GetComponent <MeshRenderer>().material;
        MeshFilter mf      = GetComponent <MeshFilter>();
        string     objName = mf.mesh.name.Split(' ')[0];
        string     path    = Application.dataPath + "/objects/" + objName + "/";

        string[]       lines = File.ReadAllLines(path + objName + ".txt");
        List <Vector4> list  = new List <Vector4>();
        int            num   = 1;

        while (true)
        {
            if (lines[num].Split(' ').Length == 1)
            {
                break;
            }
            num++;
        }

        string    imageName = path + lines[num];
        Texture2D tex       = TGALoader.LoadTGA(imageName);

        mat.mainTexture = tex;
    }
Пример #7
0
    void Awake()
    {
        GameObject player = GameObject.Find("Gronk");

        return;

        //Debug.Log ("Moving " + player.name);
        player.transform.position = new Vector3(38.72f, 4.152f, 3.244f);

        GameObject skul = GameObject.Find("a_skull_30_03_00_1016");
        //if (skul!=null)
        //{
        string filePath = "c:\\objects_0000.tga";
        //Debug.Log (filePath);
        SpriteRenderer sprt = skul.GetComponentInChildren <SpriteRenderer>();
        //Sprite newimage= new Sprite();
        //Texture2D newtex= new Texture2D(22,11);
        Texture2D newTex = TGALoader.LoadTGA(filePath);
        //newTex.height=newTex.height*2;
        //newTex.width=newTex.width*2;
        Sprite newSprite = Sprite.Create(newTex, new Rect(0, 0, newTex.width, newTex.height), new Vector2(0.5f, 0.0f));

        //Sprite newSprite = TGALoader.LoadTGASprite(filePath);e
        sprt.sprite = newSprite;


        GameObject theWallBrotha = GameObject.Find("Wall_30_03");

        Material[] myMat = theWallBrotha.GetComponent <Renderer>().materials;
        for (int i = 0; i < myMat.GetUpperBound(0); i++)
        {
            //Debug.Log (myMat[i].name);
            myMat[i].mainTexture = newTex;
        }

        Mesh mesh = theWallBrotha.GetComponent <MeshFilter>().mesh;

        Vector3[] vertices = mesh.vertices;
        Vector2[] uvs      = new Vector2[vertices.Length];
        int       j        = 0;

        while (j < uvs.Length)
        {
            uvs[j] = new Vector2(vertices[j].x, vertices[j].z);
            j++;
        }
        //mesh.uv = uvs;

        //if (newimage!=null)
        //{
        //Debug.Log("New image loaded");
        //}
        //else
        //{
        //Debug.Log("f**k");
        //}
        //}
        //CreateObj();
    }
Пример #8
0
    private Texture2D GetTexture(WWW loader)
    {
        string ext = Path.GetExtension(loader.url).ToLower();

        if (ext != ".png" && ext != ".jpg" && ext != ".tga")
        {
            //Debug.LogWarning("maybe unsupported texture format:"+ext);
        }

        return(ext == ".tga" ? TGALoader.LoadTGA(new MemoryStream(loader.bytes)) : loader.texture);
        // refactor this method to add support for more formats
    }
        private void ChangeColor(string color, string folder)
        {
            var material        = Resources.Load <Material>($"Materials/{folder}/{characterConfig.HairMaterial}");
            var directory       = Application.streamingAssetsPath;
            var characterFolder = $"Colors/{characterConfig.PrefabName}/{folder}";
            var path            = Path.Combine(directory, characterFolder);
            var file            = Path.Combine(path, $"{color}.tga");

            var texture2D = TGALoader.LoadTGA(file);

            material.mainTexture = texture2D;
        }
Пример #10
0
    /// <summary>
    /// Loads specified atlas into memory.
    /// </summary>
    /// <param name="name">Raw file name of an atlas. It gets converted into 'maps/[name].tga'</param>
    /// <param name="blackIsTransparency">Specifies whether to use black color as a transparency or rely on the alpha channel</param>
    public void LoadAtlas(string name, bool blackIsTransparency = false)
    {
        if (atlases.ContainsKey(name))
        {
            return;
        }

        var atlas = new UIAtlas();

        atlas.atlas = TGALoader.LoadTGA(GameAPI.instance.fileSystem.GetStreamFromPath(Path.Combine("maps", name + ".tga")), blackIsTransparency);

        atlases.Add(name, atlas);
    }
Пример #11
0
    /// <summary>
    /// Initializes a new instance of the <see cref="TextureLoader"/> class.
    /// </summary>
    /// <param name="index">Index.</param>
    /// <param name="TextureType">Texture type. 0 = normal, 1 = palette cycled</param>
    public Texture2D LoadImageAt(int index, short TextureType)
    {
        switch (TextureType)
        {
        case 1:         // Palette cycled
            return(LoadImageAt(index, GameWorldController.instance.palLoader.GreyScale));

        case 2:        //normal map
            return(TGALoader.LoadTGA(ModPathW + sep + index.ToString("d3") + "_normal.tga"));

        default:
            return(LoadImageAt(index, GameWorldController.instance.palLoader.Palettes[0]));
        }
    }
        private static bool LoadTextureData(string path, out U::UnityEngine.Texture2D texture2D)
        {
            bool flag;

            texture2D = null;
            try
            {
                path = string.Concat(Texture2DOverride.TranslationImageDir, path);
                string extension = Path.GetExtension(path);
                if (extension == ".dds")
                {
                    flag = DXTLoader.LoadDXT(path, out texture2D);
                }
                else if (extension == ".jpeg" || extension == ".jpg")
                {
                    texture2D = new Texture2D(2, 2, TextureFormat.RGB24, false);
                    flag      = texture2D.LoadImage(File.ReadAllBytes(path));
                }
                else if (extension == ".png")
                {
                    texture2D = new Texture2D(2, 2, TextureFormat.ARGB32, false);
                    flag      = texture2D.LoadImage(File.ReadAllBytes(path));
                }
                else if (extension == ".psd")
                {
                    flag = PSDLoader.LoadPSD(path, out texture2D);
                }
                else if (extension == ".tga")
                {
                    flag = TGALoader.LoadTGA(path, out texture2D);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception exception)
            {
                IniSettings.Error(string.Concat("LoadImage:\n", exception.ToString()));
                return(false);
            }
            return(flag);
        }
Пример #13
0
    /// <summary>
    /// Loads specified atlas into memory.
    /// </summary>
    /// <param name="name">Raw file name of an atlas. It gets converted into 'maps/[name].tga'</param>
    /// <param name="blackIsTransparency">Specifies whether to use black color as a transparency or rely on the alpha channel</param>
    public void LoadAtlas(string name, bool blackIsTransparency = false)
    {
        if (atlases.ContainsKey(name))
        {
            return;
        }

        var atlas  = new UIAtlas();
        var stream = GameAPI.instance.fileSystem.GetStreamFromPath(Path.Combine("maps", name + ".tga"));

        if (stream == null)
        {
            Debug.LogWarning(string.Format("Atlas {0} was not found!", name));
            return;
        }

        atlas.atlas = TGALoader.LoadTGA(stream, blackIsTransparency);

        atlases.Add(name, atlas);
    }
Пример #14
0
    GameObject LoadTGA(string path, Vector3 position)
    {
        var bg1  = new GameObject("bg1", typeof(RectTransform));
        var rect = bg1.GetComponent <RectTransform>();

        bg1.transform.SetParent(canvas.transform);
        bg1.AddComponent <CanvasRenderer>();
        var image = bg1.AddComponent <Image>();

        Texture2D tex = TGALoader.LoadTGA(path);

        bg1.GetComponent <RectTransform>().sizeDelta = new Vector2(tex.width, tex.height);
        Sprite spr = Sprite.Create(tex, Rect.MinMaxRect(0, 0, tex.width, tex.height), Vector2.zero);

        image.sprite   = spr;
        rect.anchorMin = new Vector2(0.5f, 0.5f);
        rect.anchorMax = new Vector2(0.5f, 0.5f);

        rect.localPosition = position;
        return(bg1);
    }
Пример #15
0
    private void OnPointerEnter(PointerEventData x)
    {
        try
        {
            toolTip.SetActive(true);
            GameObject    obj = x.pointerEnter;
            MapTeleport   mt  = obj.GetComponent <MapTeleport>();
            RectTransform rw  = obj.GetComponent <RectTransform>();

            WorldSpawn    spawn = mt.spawn;
            RectTransform rrt   = toolTip.GetComponent <RectTransform>();
            rrt.anchoredPosition = new Vector3(((spawn.pos.x / 256.0f) * pixelsPerMeter) + rw.sizeDelta.x / 2, ((spawn.pos.z / 256.0f) * pixelsPerMeter) + rw.sizeDelta.y / 2, 0);

            RawImage      ri       = toolTip.transform.FindDeepChild("TooltipImage").GetComponent <RawImage>();
            Text          txt      = toolTip.transform.FindDeepChild("SpawnName").GetComponent <Text>();
            string        img      = spawn.imagePath;
            string        nameOnly = Path.GetFileName(img);
            AssetDatabase adb      = AssetDatabaseInst.DB;
            byte[]        data     = adb.extractUsingFilename(nameOnly, AssetDatabase.RequestCategory.TEXTURE);
            if (nameOnly.EndsWith("dds"))
            {
                ri.texture = DDSLoader.DatabaseLoaderTexture_DDS.LoadDDS(data);
            }
            else if (nameOnly.EndsWith("tga"))
            {
                ri.texture = TGALoader.LoadTGA(new MemoryStream(data));
            }
            else
            {
                throw new Exception("Unknown texture type:" + nameOnly);
            }
            rrt.sizeDelta = new Vector2(ri.texture.width, ri.texture.height);
            txt.text      = spawn.spawnName;
        }
        catch (Exception ex)
        {
            Debug.LogWarning(ex);
            toolTip.SetActive(true);
        }
    }
Пример #16
0
    public List <Texture2D> LoadTorsoTextures()
    {
        string           path          = Path.Combine(Application.streamingAssetsPath, _characterPrefabName, "Torso");
        List <Texture2D> torsoTextures = new List <Texture2D>();
        var directoryInfo = new DirectoryInfo(path);
        var allFiles      = directoryInfo.GetFiles("*.*");

        foreach (var fileInfo in allFiles)
        {
            if (fileInfo.Name.Contains("meta"))
            {
                continue;
            }
            var bytes = File.ReadAllBytes(fileInfo.FullName);

            // TGA format is not supported => I have to use wrapper
            var texture2D = TGALoader.LoadTGA(fileInfo.FullName);
            torsoTextures.Add(texture2D);
        }

        return(torsoTextures);
    }
Пример #17
0
    // Start is called before the first frame update
    void Start()
    {
        mat = GetComponent <MeshRenderer>().material;
        MeshFilter mf      = GetComponent <MeshFilter>();
        string     objName = mf.mesh.name.Split(' ')[0];
        string     path    = Application.dataPath + "/objects/" + objName + "/";

        string[]       lines = File.ReadAllLines(path + objName + ".txt");
        List <Vector4> list  = new List <Vector4>();
        int            num   = 1;

        while (true)
        {
            Vector4 vec = new Vector4();
            if (!ToVector(lines[num], ref vec))
            {
                break;
            }
            list.Add(vec);
            num++;
        }

        if (list.Count == 12)
        {
            mat.SetVectorArray("texelVector", list.ToArray());
        }

        int imgIdx = 0;

        while (num < lines.Length)
        {
            string    imageName = path + lines[num];
            Texture2D tex       = TGALoader.LoadTGA(imageName);
            mat.SetTexture("_Tex" + imgIdx, tex);
            num++;
            imgIdx++;
        }
    }
Пример #18
0
        public static Texture2D LoadTexture2D(string resref)
        {
            if (!loadedTextures.ContainsKey(resref))
            {
                Texture2D tex;
                Stream    stream;
                if (null != (stream = data.GetStream(resref, ResourceType.TPC)))
                {
                    TPCObject tpc = new TPCObject(stream);

                    tex = new Texture2D(tpc.Width, tpc.Height, tpc.Format, false);

                    tex.LoadRawTextureData(tpc.RawData);
                    tex.Apply();

                    tex.anisoLevel = ANISO_LEVEL;
                }
                else if (null != (stream = data.GetStream(resref, ResourceType.TGA)))
                {
                    tex            = TGALoader.LoadTGA(stream);
                    tex.anisoLevel = ANISO_LEVEL;
                }
                else
                {
                    //Debug.Log("Missing texture: " + resref);
                    return(new Texture2D(1, 1));
                }
                //loadedTextures[resref + "_base"] = tex;
                //tex = ImageFilter.Upscale(tex);

                loadedTextures[resref] = tex;
            }

            //return NormalGeneration.Diff2Normal(loadedTextures[resref]);
            return(loadedTextures[resref]);
        }
Пример #19
0
        public static Texture2D LoadTexture2D(string resref)
        {
            Stream stream;

            if (null != (stream = GetStream(resref, ResourceType.TPC)))
            {
                TPCObject tpc = new TPCObject(stream);
                Texture2D tex = new Texture2D(tpc.Width, tpc.Height, tpc.Format, false);

                tex.LoadRawTextureData(tpc.RawData);
                tex.Apply();

                return(tex);
            }
            else if (null != (stream = GetStream(resref, ResourceType.TGA)))
            {
                return(TGALoader.LoadTGA(stream));
            }
            else
            {
                //Debug.Log("Missing texture: " + resref);
                return(new Texture2D(1, 1));
            }
        }
Пример #20
0
    public Texture2D extractUW2Bitmap(string path, int index, bool Alpha)
    {
        char[] textureFile;                          // Pointer to our buffered data (little endian format)
        //int i;
        long NoOfTextures;

        if (File.Exists(BasePath + path.Replace(".", "_") + "\\" + index.ToString("d3") + ".tga"))
        {
            return(TGALoader.LoadTGA(BasePath + path.Replace(".", "_") + "\\" + index.ToString("d3") + ".tga"));
        }

        if (!DataLoader.ReadStreamFile(BasePath + path, out textureFile))
        {
            return(null);
        }
        // Get the size of the file in bytes

        NoOfTextures = DataLoader.getValAtAddress(textureFile, 0, 8);
        long textureOffset = (int)DataLoader.getValAtAddress(textureFile, (index * 4) + 6, 32);

        if (textureOffset != 0)
        {
            int compressionFlag = (int)DataLoader.getValAtAddress(textureFile, ((index * 4) + 6) + (NoOfTextures * 4), 32);
            int isCompressed    = (compressionFlag >> 1) & 0x01;
            if (isCompressed == 1)
            {
                int datalen = 0;
                return(Image(DataLoader.unpackUW2(textureFile, textureOffset, ref datalen), 0, 320, 200, "namehere", GameWorldController.instance.palLoader.Palettes[PaletteIndicesUW2[index]], Alpha));
            }
            else
            {
                return(Image(textureFile, textureOffset, 320, 200, "name_goes_here", GameWorldController.instance.palLoader.Palettes[PaletteIndicesUW2[index]], Alpha));
            }
        }
        return(null);
    }
Пример #21
0
    private int ReadPageFile(char[] PageFile, int XX, int YY, int spriteIndex, int AuxPalNo, bool LoadMod, string ModPath)
    {
        int addptr    = 0;
        int slotbase  = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8);
        int NoOfSlots = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8);

        int[]  SlotIndices   = new int[NoOfSlots];
        int    spriteCounter = 0;
        int    k             = 0;
        string XXo           = DecimalToOct(XX.ToString());
        string YYo           = DecimalToOct(YY.ToString());

        for (int i = 0; i < NoOfSlots; i++)
        {
            int val = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8);
            if (val != 255)
            {
                SlotIndices[k++] = i;
            }
        }
        int NoOfSegs = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8);

        for (int i = 0; i < NoOfSegs; i++)
        {
            //string[] AnimFiles = new string[8];
            string AnimName = PrintAnimName(slotbase + SlotIndices[i]);

            int index = TranslateAnimToIndex(slotbase + SlotIndices[i]);
            AnimInfo.animName[index] = AnimName;
            int ValidCount = 0;
            for (int j = 0; j < 8; j++)
            {
                int val = (int)DataLoader.getValAtAddress(PageFile, addptr++, 8);
                if (val != 255)
                {                   //AnimFiles[j] = "CR" + XX.ToString("d2") + "PAGE_N" + YY.ToString("d2") + "_" + AuxPalNo + "_" + val;
                    AnimInfo.animSequence[index, j] = "CR" + XXo + "PAGE_N" + YYo + "_" + AuxPalNo + "_" + (val).ToString("d4");
                    AnimInfo.animIndices[index, j]  = (val + spriteIndex);
                    ValidCount++;
                }
                else
                {
                    AnimInfo.animIndices[index, j] = -1;
                }
            }
        }

        //Read in the palette
        int NoOfPals = (int)DataLoader.getValAtAddress(PageFile, addptr, 8);//Will skip ahead this far.

        addptr++;
        char[] auxPalVal = new char[32];
        for (int i = 0; i < 32; i++)
        {
            auxPalVal[i] = (char)DataLoader.getValAtAddress(PageFile, (addptr) + (AuxPalNo * 32) + i, 8);
        }

        //Skip past the palettes
        addptr = addptr + NoOfPals * 32;
        int NoOfFrames = (int)DataLoader.getValAtAddress(PageFile, addptr, 8);

        //AnimInfo.animSprites=new Sprite[NoOfFrames];
        addptr = addptr + 2;
        int addptr_start = addptr;//Bookmark my positiohn
        int MaxWidth     = 0;
        int MaxHeight    = 0;
        int MaxHotSpotX  = 0;
        int MaxHotSpotY  = 0;

        for (int pass = 0; pass <= 1; pass++)
        {
            addptr = addptr_start;
            if (pass == 0)
            {//get the max width and height
                for (int i = 0; i < NoOfFrames; i++)
                {
                    int frameOffset  = (int)DataLoader.getValAtAddress(PageFile, addptr + (i * 2), 16);
                    int BitMapWidth  = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 0, 8);
                    int BitMapHeight = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 1, 8);
                    int hotspotx     = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 2, 8);
                    int hotspoty     = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 3, 8);
                    if (hotspotx > BitMapWidth)
                    {
                        hotspotx = BitMapWidth;
                    }
                    if (hotspoty > BitMapHeight)
                    {
                        hotspoty = BitMapHeight;
                    }

                    if (BitMapWidth > MaxWidth)
                    {
                        MaxWidth = BitMapWidth;
                    }
                    if (BitMapHeight > MaxHeight)
                    {
                        MaxHeight = BitMapHeight;
                    }

                    if (hotspotx > MaxHotSpotX)
                    {
                        MaxHotSpotX = hotspotx;
                    }
                    if (hotspoty > MaxHotSpotY)
                    {
                        MaxHotSpotY = hotspoty;
                    }
                }
            }
            else
            {     //Extract
                if (MaxHotSpotX * 2 > MaxWidth)
                { //Try and center the hot spot in the image.
                    MaxWidth = MaxHotSpotX * 2;
                }
                char[] outputImg;
                outputImg = new char[MaxWidth * MaxHeight * 2];
                for (int i = 0; i < NoOfFrames; i++)
                {
                    int frameOffset  = (int)DataLoader.getValAtAddress(PageFile, addptr + (i * 2), 16);
                    int BitMapWidth  = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 0, 8);
                    int BitMapHeight = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 1, 8);
                    int hotspotx     = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 2, 8);
                    int hotspoty     = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 3, 8);
                    int compression  = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 4, 8);
                    int datalen      = (int)DataLoader.getValAtAddress(PageFile, frameOffset + 5, 16);

                    //Adjust the hotspots from the biggest point back to the image corners
                    int cornerX; int cornerY;
                    cornerX = MaxHotSpotX - hotspotx;
                    cornerY = MaxHotSpotY - hotspoty;
                    if (cornerX <= 0)
                    {
                        cornerX = 0;
                    }
                    else
                    {
                        cornerX = cornerX - 1;
                    }
                    if (cornerY <= 0)
                    {
                        cornerY = 0;
                    }
                    bool ModFileIsLoaded = false;
                    if (LoadMod)
                    {
                        if (File.Exists(ModPath + sep + AuxPalNo + sep + i.ToString("d3") + ".tga"))
                        {
                            Texture2D tex = TGALoader.LoadTGA(ModPath + sep + AuxPalNo + sep + i.ToString("d3") + ".tga");
                            ModFileIsLoaded = true;
                            AnimInfo.animSprites[spriteIndex + i] = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(0.5f, 0.0f));
                        }
                    }
                    if (!ModFileIsLoaded)
                    {
                        //Extract the image
                        char[] srcImg;
                        srcImg    = new char[BitMapWidth * BitMapHeight * 2];
                        outputImg = new char[MaxWidth * MaxHeight * 2];
                        ArtLoader.ua_image_decode_rle(PageFile, srcImg, compression == 6 ? 5 : 4, datalen, BitMapWidth * BitMapHeight, frameOffset + 7, auxPalVal);


                        //*Put the sprite in the a frame of size max width & height
                        cornerY = MaxHeight - cornerY;//y is from the top left corner
                        int  ColCounter = 0; int RowCounter = 0;
                        bool ImgStarted = false;
                        for (int y = 0; y < MaxHeight; y++)
                        {
                            for (int x = 0; x < MaxWidth; x++)
                            {
                                if ((cornerX + ColCounter == x) && (MaxHeight - cornerY + RowCounter == y) && (ColCounter < BitMapWidth) && (RowCounter < BitMapHeight))
                                {//the pixel from the source image is here
                                    ImgStarted = true;
                                    outputImg[x + (y * MaxWidth)] = srcImg[ColCounter + (RowCounter * BitMapWidth)];
                                    ColCounter++;
                                }
                                else
                                {
                                    outputImg[x + (y * MaxWidth)] = (char)0;//alpha
                                }
                            }
                            if (ImgStarted == true)
                            {//New Row on the src image
                                RowCounter++;
                                ColCounter = 0;
                            }
                        }
                        //Set the heights for output
                        BitMapWidth  = MaxWidth;
                        BitMapHeight = MaxHeight;

                        //****************************

                        Texture2D imgData = ArtLoader.Image(outputImg, 0, BitMapWidth, BitMapHeight, "namehere", pal, true, true);
                        CropImageData(ref imgData, pal);

                        AnimInfo.animSprites[spriteIndex + i] = Sprite.Create(imgData, new Rect(0f, 0f, imgData.width, imgData.height), new Vector2(0.5f, 0.0f));
                        AnimInfo.animSprites[spriteIndex + i].texture.filterMode = FilterMode.Point;
                        spriteCounter++;
                    }
                }
            }//endextract
        }
        return(spriteCounter);
    }
Пример #22
0
    public void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (CloudMaterial == null || curlNoise == null || blueNoiseTexture == null || lowFreqNoise == null || highFreqNoise == null) // if some script public parameters are missing, do nothing
        {
            Graphics.Blit(source, destination);                                                                                      // do nothing
            return;
        }

        if (_cloudShapeTexture == null) // if shape texture is missing load it in
        {
            _cloudShapeTexture = TGALoader.load3DFromTGASlices(lowFreqNoise);
        }

        if (_cloudDetailTexture == null) // if detail texture is missing load it in
        {
            _cloudDetailTexture = TGALoader.load3DFromTGASlices(highFreqNoise);
        }
        Vector3 cameraPos = CurrentCamera.transform.position;
        // sunLight.rotation.x 364 -> 339, 175 -> 201

        float sunLightFactorUpdated     = sunLightFactor;
        float ambientLightFactorUpdated = ambientLightFactor;
        float sunAngle = sunLight.transform.eulerAngles.x;
        Color sunColor = highSunColor;
        float henyeyGreensteinGBackwardLerp = henyeyGreensteinGBackward;

        float noiseScale = 0.00001f + scale * 0.0004f;

        if (sunAngle > 170.0f) // change sunlight color based on sun's height.
        {
            float gradient  = Mathf.Max(0.0f, (sunAngle - 330.0f) / 30.0f);
            float gradient2 = gradient * gradient;
            sunLightFactorUpdated         *= gradient;
            ambientLightFactorUpdated     *= gradient;
            henyeyGreensteinGBackwardLerp *= gradient2 * gradient;
            ambientLightFactorUpdated      = Mathf.Max(0.02f, ambientLightFactorUpdated);
            sunColor = Color.Lerp(lowSunColor, highSunColor, gradient2);
        }

        updateMaterialKeyword(debugNoLowFreqNoise, "DEBUG_NO_LOW_FREQ_NOISE");
        updateMaterialKeyword(debugNoHighFreqNoise, "DEBUG_NO_HIGH_FREQ_NOISE");
        updateMaterialKeyword(debugNoCurlNoise, "DEBUG_NO_CURL");
        updateMaterialKeyword(allowFlyingInClouds, "ALLOW_IN_CLOUDS");
        updateMaterialKeyword(randomUnitSphere, "RANDOM_UNIT_SPHERE");
        updateMaterialKeyword(aLotMoreLightSamples, "SLOW_LIGHTING");

        switch (randomJitterNoise)
        {
        case RandomJitter.Off:
            updateMaterialKeyword(false, "RANDOM_JITTER_WHITE");
            updateMaterialKeyword(false, "RANDOM_JITTER_BLUE");
            break;

        case RandomJitter.Random:
            updateMaterialKeyword(true, "RANDOM_JITTER_WHITE");
            updateMaterialKeyword(false, "RANDOM_JITTER_BLUE");
            break;

        case RandomJitter.BlueNoise:
            updateMaterialKeyword(false, "RANDOM_JITTER_WHITE");
            updateMaterialKeyword(true, "RANDOM_JITTER_BLUE");
            break;
        }

        // send uniforms to shader
        CloudMaterial.SetVector("_SunDir", sunLight.transform ? (-sunLight.transform.forward).normalized : Vector3.up);
        CloudMaterial.SetVector("_PlanetCenter", planetZeroCoordinate - new Vector3(0, planetSize, 0));
        CloudMaterial.SetVector("_ZeroPoint", planetZeroCoordinate);
        CloudMaterial.SetColor("_SunColor", sunColor);
        //CloudMaterial.SetColor("_SunColor", sunLight.color);

        CloudMaterial.SetColor("_CloudBaseColor", cloudBaseColor);
        CloudMaterial.SetColor("_CloudTopColor", cloudTopColor);
        CloudMaterial.SetFloat("_AmbientLightFactor", ambientLightFactorUpdated);
        CloudMaterial.SetFloat("_SunLightFactor", sunLightFactorUpdated);
        //CloudMaterial.SetFloat("_AmbientLightFactor", sunLight.intensity * ambientLightFactor * 0.3f);
        //CloudMaterial.SetFloat("_SunLightFactor", sunLight.intensity * sunLightFactor);

        CloudMaterial.SetTexture("_ShapeTexture", _cloudShapeTexture);
        CloudMaterial.SetTexture("_DetailTexture", _cloudDetailTexture);
        CloudMaterial.SetTexture("_CurlNoise", curlNoise);
        CloudMaterial.SetTexture("_BlueNoise", blueNoiseTexture);
        CloudMaterial.SetVector("_Randomness", new Vector4(Random.value, Random.value, Random.value, Random.value));
        CloudMaterial.SetTexture("_AltoClouds", cloudsHighTexture);

        CloudMaterial.SetFloat("_CoverageHigh", 1.0f - coverageHigh);
        CloudMaterial.SetFloat("_CoverageHighScale", highCoverageScale * weatherScale * 0.001f);
        CloudMaterial.SetFloat("_HighCloudsScale", highCloudsScale * 0.002f);

        CloudMaterial.SetFloat("_CurlDistortAmount", 150.0f + curlDistortAmount);
        CloudMaterial.SetFloat("_CurlDistortScale", curlDistortScale * noiseScale);

        CloudMaterial.SetFloat("_LightConeRadius", lightConeRadius);
        CloudMaterial.SetFloat("_LightStepLength", lightStepLength);
        CloudMaterial.SetFloat("_SphereSize", planetSize);
        CloudMaterial.SetVector("_CloudHeightMinMax", new Vector2(startHeight, startHeight + thickness));
        CloudMaterial.SetFloat("_Thickness", thickness);
        CloudMaterial.SetFloat("_Scale", noiseScale);
        CloudMaterial.SetFloat("_DetailScale", detailScale * noiseScale);
        CloudMaterial.SetVector("_LowFreqMinMax", new Vector4(lowFreqMin, lowFreqMax));
        CloudMaterial.SetFloat("_HighFreqModifier", highFreqModifier);
        CloudMaterial.SetFloat("_WeatherScale", weatherScale * 0.00025f);
        CloudMaterial.SetFloat("_Coverage", 1.0f - coverage);
        CloudMaterial.SetFloat("_HenyeyGreensteinGForward", henyeyGreensteinGForward);
        CloudMaterial.SetFloat("_HenyeyGreensteinGBackward", -henyeyGreensteinGBackwardLerp);
        if (adjustDensity)
        {
            CloudMaterial.SetFloat("_SampleMultiplier", cloudSampleMultiplier * stepDensityAdjustmentCurve.Evaluate(steps / 256.0f));
        }
        else
        {
            CloudMaterial.SetFloat("_SampleMultiplier", cloudSampleMultiplier);
        }


        CloudMaterial.SetFloat("_Density", density);

        CloudMaterial.SetFloat("_WindSpeed", _multipliedWindSpeed);
        CloudMaterial.SetVector("_WindDirection", _windDirectionVector);
        CloudMaterial.SetVector("_WindOffset", _windOffset);
        CloudMaterial.SetVector("_CoverageWindOffset", _coverageWindOffset);
        CloudMaterial.SetVector("_HighCloudsWindOffset", _highCloudsWindOffset);

        CloudMaterial.SetVector("_Gradient1", gradientToVector4(gradientLow));
        CloudMaterial.SetVector("_Gradient2", gradientToVector4(gradientMed));
        CloudMaterial.SetVector("_Gradient3", gradientToVector4(gradientHigh));

        CloudMaterial.SetInt("_Steps", steps);

        CloudMaterial.SetMatrix("_FrustumCornersES", GetFrustumCorners(CurrentCamera));
        CloudMaterial.SetMatrix("_CameraInvViewMatrix", CurrentCamera.cameraToWorldMatrix);
        CloudMaterial.SetVector("_CameraWS", cameraPos);
        CloudMaterial.SetFloat("_FarPlane", CurrentCamera.farClipPlane);

        // get cloud render texture and render clouds to it
        RenderTexture rtClouds = RenderTexture.GetTemporary((int)(source.width / ((float)downSample)), (int)(source.height / ((float)downSample)), 0, source.format, RenderTextureReadWrite.Default, source.antiAliasing);

        CustomGraphicsBlit(source, rtClouds, CloudMaterial, 0);

        if (temporalAntiAliasing) // if TAA is enabled, then apply it to cloud render texture
        {
            RenderTexture rtTemporal = RenderTexture.GetTemporary(rtClouds.width, rtClouds.height, 0, rtClouds.format, RenderTextureReadWrite.Default, source.antiAliasing);
            _temporalAntiAliasing.TemporalAntiAliasing(rtClouds, rtTemporal);
            UpscaleMaterial.SetTexture("_Clouds", rtTemporal);
            RenderTexture.ReleaseTemporary(rtTemporal);
        }
        else
        {
            UpscaleMaterial.SetTexture("_Clouds", rtClouds);
        }
        // Apply clouds to background
        Graphics.Blit(source, destination, UpscaleMaterial, 0);
        RenderTexture.ReleaseTemporary(rtClouds);
    }
Пример #23
0
    private static object DoLoad(string file, string ext)
    {
        //string fileWOExt = file.Replace("." + ext, "");

        switch (ext)
        {
        case "grf":
            return(File.OpenRead(file));

        // Regular images files
        case "jpg":
        case "jpeg":
        case "png":
            using (var br = ReadSync(file)) {
                return(new RawImage()
                {
                    data = br.ToArray()
                });
            }

        case "bmp":
            using (var br = ReadSync(file))
                return(loader.LoadBMP(br));

        case "tga":
            using (var br = ReadSync(file))
                return(TGALoader.LoadTGA(br));

        // Texts
        case "txt":
        case "xml":
        case "lua":
            using (var br = ReadSync(file)) {
                if (br != null)
                {
                    return(Encoding.UTF8.GetString(br.ToArray()));
                }
                else
                {
                    return(null);
                }
            }

        case "spr":
            using (var br = ReadSync(file)) {
                if (br != null)
                {
                    SPR spr = SpriteLoader.Load(br);
                    spr.SwitchToRGBA();
                    spr.Compile();
                    spr.filename = file;
                    return(spr);
                }
                else
                {
                    return(null);
                }
            }

        case "str":
            using (var br = ReadSync(file)) {
                if (br != null)
                {
                    STR str = EffectLoader.Load(br);
                    return(str);
                }
                else
                {
                    return(null);
                }
            }

        // Binary
        case "gat":
            using (var br = ReadSync(file))
                return(new Altitude(br));

        case "rsw":
            using (var br = ReadSync(file))
                return(WorldLoader.Load(br));

        case "gnd":
            using (var br = ReadSync(file))
                return(GroundLoader.Load(br));

        case "rsm":
            using (var br = ReadSync(file))
                return(ModelLoader.Load(br));

        // Audio
        case "wav":
            using (var br = ReadSync(file)) {
                WAVLoader.WAVFile wav  = WAVLoader.OpenWAV(br.ToArray());
                AudioClip         clip = AudioClip.Create(file, wav.samples, wav.channels, wav.sampleRate, false);
                clip.SetData(wav.leftChannel, 0);
                return(clip);
            }

        case "mp3":
        case "ogg":

        case "act":
            //return new Action(ReadSync(file)).compile();
            Debug.LogWarning("Can't read " + file + "\nLoader for " + ext + " is not implemented");
            break;

        default:
            throw new System.Exception("Unknown file format: " + file);
        }
        return(null);
    }
Пример #24
0
    public void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (CloudMaterial == null || curlNoise == null || blueNoiseTexture == null || lowFreqNoise == null || highFreqNoise == null) // if some script public parameters are missing, do nothing
        {
            Graphics.Blit(source, destination);                                                                                      // do nothing
            return;
        }

        if (_cloudShapeTexture == null) // if shape texture is missing load it in
        {
            _cloudShapeTexture = TGALoader.load3DFromTGASlices(lowFreqNoise);
        }

        if (_cloudDetailTexture == null) // if detail texture is missing load it in
        {
            _cloudDetailTexture = TGALoader.load3DFromTGASlices(highFreqNoise);
        }
        Vector3 cameraPos = CurrentCamera.transform.position;
        // sunLight.rotation.x 364 -> 339, 175 -> 201

        float sunLightFactorUpdated     = sunLightFactor;
        float ambientLightFactorUpdated = ambientLightFactor;
        float sunAngle = sunLight.transform.eulerAngles.x;
        Color sunColor = highSunColor;
        float henyeyGreensteinGBackwardLerp = henyeyGreensteinGBackward;

        float noiseScale = 0.00001f + scale * 0.0004f;

        if (sunAngle > 170.0f) // change sunlight color based on sun's height.
        {
            float gradient  = Mathf.Max(0.0f, (sunAngle - 330.0f) / 30.0f);
            float gradient2 = gradient * gradient;
            sunLightFactorUpdated         *= gradient;
            ambientLightFactorUpdated     *= gradient;
            henyeyGreensteinGBackwardLerp *= gradient2 * gradient;
            ambientLightFactorUpdated      = Mathf.Max(0.02f, ambientLightFactorUpdated);
            sunColor = Color.Lerp(lowSunColor, highSunColor, gradient2);
        }

        updateMaterialKeyword(debugNoLowFreqNoise, "DEBUG_NO_LOW_FREQ_NOISE");
        updateMaterialKeyword(debugNoHighFreqNoise, "DEBUG_NO_HIGH_FREQ_NOISE");
        updateMaterialKeyword(debugNoCurlNoise, "DEBUG_NO_CURL");
        updateMaterialKeyword(allowFlyingInClouds, "ALLOW_IN_CLOUDS");
        updateMaterialKeyword(randomUnitSphere, "RANDOM_UNIT_SPHERE");
        updateMaterialKeyword(aLotMoreLightSamples, "SLOW_LIGHTING");

        switch (randomJitterNoise)
        {
        case RandomJitter.Off:
            updateMaterialKeyword(false, "RANDOM_JITTER_WHITE");
            updateMaterialKeyword(false, "RANDOM_JITTER_BLUE");
            break;

        case RandomJitter.Random:
            updateMaterialKeyword(true, "RANDOM_JITTER_WHITE");
            updateMaterialKeyword(false, "RANDOM_JITTER_BLUE");
            break;

        case RandomJitter.BlueNoise:
            updateMaterialKeyword(false, "RANDOM_JITTER_WHITE");
            updateMaterialKeyword(true, "RANDOM_JITTER_BLUE");
            break;
        }

        // send uniforms to shader
        CloudMaterial.SetVector("_SunDir", sunLight.transform ? (-sunLight.transform.forward).normalized : Vector3.up);
        CloudMaterial.SetVector("_PlanetCenter", planetZeroCoordinate - new Vector3(0, planetSize, 0));
        CloudMaterial.SetVector("_ZeroPoint", planetZeroCoordinate);
        CloudMaterial.SetColor("_SunColor", sunColor);
        //CloudMaterial.SetColor("_SunColor", sunLight.color);

        CloudMaterial.SetColor("_CloudBaseColor", cloudBaseColor);
        CloudMaterial.SetColor("_CloudTopColor", cloudTopColor);
        CloudMaterial.SetFloat("_AmbientLightFactor", ambientLightFactorUpdated);
        CloudMaterial.SetFloat("_SunLightFactor", sunLightFactorUpdated);
        //CloudMaterial.SetFloat("_AmbientLightFactor", sunLight.intensity * ambientLightFactor * 0.3f);
        //CloudMaterial.SetFloat("_SunLightFactor", sunLight.intensity * sunLightFactor);

        CloudMaterial.SetTexture("_ShapeTexture", _cloudShapeTexture);
        CloudMaterial.SetTexture("_DetailTexture", _cloudDetailTexture);
        CloudMaterial.SetTexture("_CurlNoise", curlNoise);
        CloudMaterial.SetTexture("_BlueNoise", blueNoiseTexture);
        CloudMaterial.SetVector("_Randomness", new Vector4(Random.value, Random.value, Random.value, Random.value));
        CloudMaterial.SetTexture("_AltoClouds", cloudsHighTexture);

        CloudMaterial.SetFloat("_CoverageHigh", 1.0f - coverageHigh);
        CloudMaterial.SetFloat("_CoverageHighScale", highCoverageScale * weatherScale * 0.001f);
        CloudMaterial.SetFloat("_HighCloudsScale", highCloudsScale * 0.002f);

        CloudMaterial.SetFloat("_CurlDistortAmount", 150.0f + curlDistortAmount);
        CloudMaterial.SetFloat("_CurlDistortScale", curlDistortScale * noiseScale);

        CloudMaterial.SetFloat("_LightConeRadius", lightConeRadius);
        CloudMaterial.SetFloat("_LightStepLength", lightStepLength);
        CloudMaterial.SetFloat("_SphereSize", planetSize);
        CloudMaterial.SetVector("_CloudHeightMinMax", new Vector2(startHeight, startHeight + thickness));
        CloudMaterial.SetFloat("_Thickness", thickness);
        CloudMaterial.SetFloat("_Scale", noiseScale);
        CloudMaterial.SetFloat("_DetailScale", detailScale * noiseScale);
        CloudMaterial.SetVector("_LowFreqMinMax", new Vector4(lowFreqMin, lowFreqMax));
        CloudMaterial.SetFloat("_HighFreqModifier", highFreqModifier);
        CloudMaterial.SetFloat("_WeatherScale", weatherScale * 0.00025f);
        CloudMaterial.SetFloat("_Coverage", 1.0f - coverage);
        CloudMaterial.SetFloat("_HenyeyGreensteinGForward", henyeyGreensteinGForward);
        CloudMaterial.SetFloat("_HenyeyGreensteinGBackward", -henyeyGreensteinGBackwardLerp);
        if (adjustDensity)
        {
            CloudMaterial.SetFloat("_SampleMultiplier", cloudSampleMultiplier * stepDensityAdjustmentCurve.Evaluate(steps / 256.0f));
        }
        else
        {
            CloudMaterial.SetFloat("_SampleMultiplier", cloudSampleMultiplier);
        }


        CloudMaterial.SetFloat("_Density", density);

        CloudMaterial.SetFloat("_WindSpeed", _multipliedWindSpeed);
        CloudMaterial.SetVector("_WindDirection", _windDirectionVector);
        CloudMaterial.SetVector("_WindOffset", _windOffset);
        CloudMaterial.SetVector("_CoverageWindOffset", _coverageWindOffset);
        CloudMaterial.SetVector("_HighCloudsWindOffset", _highCloudsWindOffset);

        CloudMaterial.SetVector("_Gradient1", gradientToVector4(gradientLow));
        CloudMaterial.SetVector("_Gradient2", gradientToVector4(gradientMed));
        CloudMaterial.SetVector("_Gradient3", gradientToVector4(gradientHigh));

        CloudMaterial.SetInt("_Steps", steps);
        CloudMaterial.SetInt("_renderInFront", renderInFront);//v0.1 choose to render in front of objects for reflections

        CloudMaterial.SetMatrix("_FrustumCornersES", GetFrustumCorners(CurrentCamera));
        CloudMaterial.SetMatrix("_CameraInvViewMatrix", CurrentCamera.cameraToWorldMatrix);
        CloudMaterial.SetVector("_CameraWS", cameraPos);
        CloudMaterial.SetVector("_CameraWSOffset", _CameraWSOffset);
        CloudMaterial.SetFloat("_FarPlane", CurrentCamera.farClipPlane);



        //v0.2
        //v3.5.3
        CloudMaterial.SetTexture("_InteractTexture", _InteractTexture);
        CloudMaterial.SetVector("_InteractTexturePos", _InteractTexturePos);
        CloudMaterial.SetVector("_InteractTextureAtr", _InteractTextureAtr);
        CloudMaterial.SetVector("_InteractTextureOffset", _InteractTextureOffset); //v4.0


        //////// SCATTER
        //Camera cam = GetComponent<Camera>(); //v2.1.15
        //Transform camtr = cam.transform;
        //float camNear = cam.nearClipPlane;
        //float camFar = cam.farClipPlane;
        //float camFov = cam.fieldOfView;
        //float camAspect = cam.aspect;

        //Matrix4x4 frustumCorners = Matrix4x4.identity;

        //float fovWHalf = camFov * 0.5f;

        //Vector3 toRight = camtr.right * camNear * Mathf.Tan(fovWHalf * Mathf.Deg2Rad) * camAspect;
        //Vector3 toTop = camtr.up * camNear * Mathf.Tan(fovWHalf * Mathf.Deg2Rad);

        //Vector3 topLeft = (camtr.forward * camNear - toRight + toTop);
        //float camScale = topLeft.magnitude * camFar / camNear;

        //topLeft.Normalize();
        //topLeft *= camScale;

        //Vector3 topRight = (camtr.forward * camNear + toRight + toTop);
        //topRight.Normalize();
        //topRight *= camScale;

        //Vector3 bottomRight = (camtr.forward * camNear + toRight - toTop);
        //bottomRight.Normalize();
        //bottomRight *= camScale;

        //Vector3 bottomLeft = (camtr.forward * camNear - toRight - toTop);
        //bottomLeft.Normalize();
        //bottomLeft *= camScale;

        //frustumCorners.SetRow(0, topLeft);
        //frustumCorners.SetRow(1, topRight);
        //frustumCorners.SetRow(2, bottomRight);
        //frustumCorners.SetRow(3, bottomLeft);

        CloudMaterial.SetInt("scatterOn", scatterOn);             //v0.3
        CloudMaterial.SetInt("sunRaysOn", sunRaysOn);             //v0.3
        CloudMaterial.SetFloat("zeroCountSteps", zeroCountSteps); //v0.3
        CloudMaterial.SetInt("sunShaftSteps", sunShaftSteps);     //v0.3

        //var camPos = camtr.position;
        float FdotC  = CurrentCamera.transform.position.y - height;
        float paramK = (FdotC <= 0.0f ? 1.0f : 0.0f);

        //fogMaterial.SetMatrix("_FrustumCornersWS", frustumCorners);
        //fogMaterial.SetVector("_CameraWS", camPos);
        CloudMaterial.SetVector("_HeightParams", new Vector4(height, FdotC, paramK, heightDensity * 0.5f));
        CloudMaterial.SetVector("_DistanceParams", new Vector4(-Mathf.Max(startDistance, 0.0f), 0, 0, 0));


        //v3.5.1
        //fogMaterial.SetFloat("_NearZCutoff", _NearZCutoff);
        //fogMaterial.SetFloat("_HorizonYAdjust", _HorizonYAdjust);
        //fogMaterial.SetFloat("_HorizonZAdjust", _HorizonZAdjust);//v2.1.24
        //fogMaterial.SetFloat("_FadeThreshold", _FadeThreshold);

        //v3.5
        //fogMaterial.SetFloat("_SampleCount0", _SampleCount0);
        //fogMaterial.SetFloat("_SampleCount1", _SampleCount1);
        //fogMaterial.SetInt("_SampleCountL", _SampleCountL);

        //fogMaterial.SetFloat("_NoiseFreq1", _NoiseFreq1);
        //fogMaterial.SetFloat("_NoiseFreq2", _NoiseFreq2);
        //fogMaterial.SetFloat("_NoiseAmp1", _NoiseAmp1);
        //fogMaterial.SetFloat("_NoiseAmp2", _NoiseAmp2);
        //fogMaterial.SetFloat("_NoiseBias", _NoiseBias);

        //fogMaterial.SetVector("_Scroll1", _Scroll1);
        //fogMaterial.SetVector("_Scroll2", _Scroll2);

        //fogMaterial.SetFloat("_Altitude0", _Altitude0);
        //fogMaterial.SetFloat("_Altitude1", _Altitude1);
        //fogMaterial.SetFloat("_FarDist", _FarDist);

        CloudMaterial.SetFloat("_Scatter", _Scatter);
        CloudMaterial.SetFloat("_HGCoeff", _HGCoeff);
        CloudMaterial.SetFloat("_Extinct", _Extinct);


        // CloudMaterial.SetFloat("_Exposure", _ExposureUnder); //v4.0
        //  CloudMaterial.SetVector("_GroundColor", _GroundColor);//
        //  CloudMaterial.SetFloat("_SunSize", _SunSize);
        CloudMaterial.SetVector("_SkyTint", _SkyTint);
        //fogMaterial.SetFloat("_AtmosphereThickness", _AtmosphereThickness);
        //v3.5
        CloudMaterial.SetFloat("_BackShade", _BackShade);
        //fogMaterial.SetFloat("_UndersideCurveFactor", _UndersideCurveFactor);

        //v2.1.19
        if (localLight != null)
        {
            Vector3 localLightPos = localLight.transform.position;
            //float intensity = Mathf.Pow(10, 3 + (localLightFalloff - 3) * 3);
            currentLocalLightIntensity = Mathf.Pow(10, 3 + (localLightFalloff - 3) * 3);
            //fogMaterial.SetVector ("_LocalLightPos", new Vector4 (localLightPos.x, localLightPos.y, localLightPos.z, localLight.intensity * localLightIntensity * intensity));
            CloudMaterial.SetVector("_LocalLightPos", new Vector4(localLightPos.x, localLightPos.y, localLightPos.z, localLight.intensity * localLightIntensity * currentLocalLightIntensity));
            CloudMaterial.SetVector("_LocalLightColor", new Vector4(localLight.color.r, localLight.color.g, localLight.color.b, localLightFalloff));
        }
        else
        {
            if (currentLocalLightIntensity > 0)
            {
                currentLocalLightIntensity = 0;
                //fogMaterial.SetVector ("_LocalLightPos", new Vector4 (localLightPos.x, localLightPos.y, localLightPos.z, localLight.intensity * localLightIntensity * intensity));
                CloudMaterial.SetVector("_LocalLightColor", Vector4.zero);
            }
        }

        //SM v1.7
        CloudMaterial.SetFloat("luminance", luminance);
        CloudMaterial.SetFloat("lumFac", lumFac);
        CloudMaterial.SetFloat("Multiplier1", ScatterFac);
        CloudMaterial.SetFloat("Multiplier2", TurbFac);
        CloudMaterial.SetFloat("Multiplier3", HorizFac);
        CloudMaterial.SetFloat("turbidity", turbidity);
        CloudMaterial.SetFloat("reileigh", reileigh);
        CloudMaterial.SetFloat("mieCoefficient", mieCoefficient);
        CloudMaterial.SetFloat("mieDirectionalG", mieDirectionalG);
        CloudMaterial.SetFloat("bias", bias);
        CloudMaterial.SetFloat("contrast", contrast);
        CloudMaterial.SetVector("v3LightDir", -sunLight.transform.forward);
        CloudMaterial.SetVector("_TintColor", new Vector4(TintColor.x, TintColor.y, TintColor.z, 1));//68, 155, 345

        float Foggy = 0;

        if (FogSky)
        {
            Foggy = 1;
        }
        CloudMaterial.SetFloat("FogSky", Foggy);
        CloudMaterial.SetFloat("ClearSkyFac", ClearSkyFac);

        var     sceneMode    = RenderSettings.fogMode;
        var     sceneDensity = 0.01f; //RenderSettings.fogDensity;//v3.0
        var     sceneStart   = RenderSettings.fogStartDistance;
        var     sceneEnd     = RenderSettings.fogEndDistance;
        Vector4 sceneParams;
        bool    linear  = (sceneMode == FogMode.Linear);
        float   diff    = linear ? sceneEnd - sceneStart : 0.0f;
        float   invDiff = Mathf.Abs(diff) > 0.0001f ? 1.0f / diff : 0.0f;

        sceneParams.x = sceneDensity * 1.2011224087f; // density / sqrt(ln(2)), used by Exp2 fog mode
        sceneParams.y = sceneDensity * 1.4426950408f; // density / ln(2), used by Exp fog mode
        sceneParams.z = linear ? -invDiff : 0.0f;
        sceneParams.w = linear ? sceneEnd * invDiff : 0.0f;
        CloudMaterial.SetVector("_SceneFogParams", sceneParams);
        CloudMaterial.SetVector("_SceneFogMode", new Vector4((int)sceneMode, useRadialDistance ? 1 : 0, 0, 0));


        ////////// END SCATTER



        // get cloud render texture and render clouds to it
        RenderTexture rtClouds = RenderTexture.GetTemporary((int)(source.width / ((float)downSample)), (int)(source.height / ((float)downSample)), 0, source.format, RenderTextureReadWrite.Default, source.antiAliasing);

        CustomGraphicsBlit(source, rtClouds, CloudMaterial, 0);

        //v5.1.1
        if (enableEdgeControl)
        {
            //UpscaleMaterial.SetTexture("_Clouds", rtClouds);
            UpscaleMaterial.SetVector("edgeControl", edgeControl);
            //UpscaleMaterial.SetInt("enableEdges", 1);
            if (debugClouds > 0)
            {
                UpscaleMaterial.SetInt("enableEdges", debugClouds - 1);
            }
            else
            {
                UpscaleMaterial.SetInt("enableEdges", 1);
            }
            RenderTexture rtTemporalA = RenderTexture.GetTemporary(rtClouds.width, rtClouds.height, 0, rtClouds.format, RenderTextureReadWrite.Default);
            //v5.1.1
            // CustomGraphicsBlit(rtClouds, rtTemporalA, UpscaleMaterial, 1);
            Graphics.Blit(rtClouds, rtTemporalA, UpscaleMaterial, 1);

            if (temporalAntiAliasing && Application.isPlaying) // if TAA is enabled, then apply it to cloud render texture //v5.1.0
            {
                RenderTexture rtTemporal = RenderTexture.GetTemporary(rtClouds.width, rtClouds.height, 0, rtClouds.format, RenderTextureReadWrite.Default, source.antiAliasing);
                _temporalAntiAliasing.TemporalAntiAliasing(rtTemporalA, rtTemporal);
                UpscaleMaterial.SetTexture("_Clouds", rtTemporal);

                // Apply clouds to background
                if (debugClouds > 0)
                {
                    Graphics.Blit(rtTemporalA, destination, UpscaleMaterial, 0);
                }
                else
                {
                    Graphics.Blit(source, destination, UpscaleMaterial, 0);
                }

                RenderTexture.ReleaseTemporary(rtTemporal);
            }
            else
            {
                UpscaleMaterial.SetTexture("_Clouds", rtTemporalA); //

                // Apply clouds to background
                if (debugClouds > 0)
                {
                    Graphics.Blit(rtTemporalA, destination, UpscaleMaterial, 0);
                }
                else
                {
                    Graphics.Blit(source, destination, UpscaleMaterial, 0);
                }
            }

            RenderTexture.ReleaseTemporary(rtClouds); RenderTexture.ReleaseTemporary(rtTemporalA);
        }
        else
        {
            UpscaleMaterial.SetInt("enableEdges", 0);
            if (temporalAntiAliasing && Application.isPlaying) // if TAA is enabled, then apply it to cloud render texture //v5.1.0
            {
                RenderTexture rtTemporal = RenderTexture.GetTemporary(rtClouds.width, rtClouds.height, 0, rtClouds.format, RenderTextureReadWrite.Default, source.antiAliasing);

                _temporalAntiAliasing.TemporalAntiAliasing(rtClouds, rtTemporal);
                UpscaleMaterial.SetTexture("_Clouds", rtTemporal);
                RenderTexture.ReleaseTemporary(rtTemporal);
            }
            else
            {
                UpscaleMaterial.SetTexture("_Clouds", rtClouds); //
            }
            // Apply clouds to background
            Graphics.Blit(source, destination, UpscaleMaterial, 0);
            RenderTexture.ReleaseTemporary(rtClouds);
        }
    }
Пример #25
0
        public static Texture2D LoadTexture(string path)
        {
            if (Path.GetExtension(path).ToLower() == ".tga")
            {
                return(TGALoader.LoadTGA(path));
            }

            var bmp = new BMPLoader();

            bmp.ForceAlphaReadWhenPossible = false;
            var img = bmp.LoadBMP(path);

            if (img == null)
            {
                throw new Exception("Failed to load: " + path);
            }

            var colors = (Color32[])img.imageData.Clone();

            var width  = img.info.width;
            var height = img.info.height;

            //magic pink conversion and transparent color expansion
            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    var count = 0;
                    var r     = 0;
                    var g     = 0;
                    var b     = 0;

                    if (x + y * width >= colors.Length)
                    {
                        Debug.LogWarning($"For some reason looking out of bounds on color table on texture {path} w{width} h{height} position {x} {y} ({x + y * width}");
                    }
                    var color = colors[x + y * width];
                    //Debug.Log(color);
                    if (color.r < 254 || color.g != 0 || color.b < 254)
                    {
                        continue;
                    }

                    //Debug.Log("OHWOW: " + color);

                    for (var y2 = -1; y2 <= 1; y2++)
                    {
                        for (var x2 = -1; x2 <= 1; x2++)
                        {
                            if (y + y2 < 0 || y + y2 >= height)
                            {
                                continue;
                            }
                            if (x + x2 < 0 || x + x2 >= width)
                            {
                                continue;
                            }

                            var color2 = colors[x + x2 + (y + y2) * width];

                            if (color2.r >= 254 && color2.g == 0 && color2.b >= 254)
                            {
                                continue;
                            }

                            count++;

                            r += color2.r;
                            g += color2.g;
                            b += color2.b;
                        }
                    }

                    if (count > 0)
                    {
                        var r2 = (byte)Mathf.Clamp(r / count, 0, 255);
                        var g2 = (byte)Mathf.Clamp(g / count, 0, 255);
                        var b2 = (byte)Mathf.Clamp(b / count, 0, 255);

                        //Debug.Log($"{x},{y} - change {color} to {r2},{g2},{b2}");

                        img.imageData[x + y * width] = new Color32(r2, g2, b2, 0);
                    }
                    else
                    {
                        img.imageData[x + y * width] = new Color32(0, 0, 0, 0);
                    }
                }
            }

            return(img.ToTexture2D());
        }
Пример #26
0
        void ReadFile(BinaryReader reader)
        {
            var header = file.Read <WZItemHeader>(reader);

            if (header.nType == 3)
            {
                reader.ReadBytes(44);
            }

            if (header.nFaces > 1000 || header.nVertices > 1000)
            {
                Debug.LogError("Error Reading ITM FILE!");
                return;
            }

            List <Vector3> vertices = new List <Vector3>();
            List <Vector2> uvs      = new List <Vector2>();

            //SortedDictionary<int, Vector2> uvs = new SortedDictionary<int, Vector2>();
            Dictionary <int, List <int> > subMeshesTriangles = new Dictionary <int, List <int> >();



            if (header.nType > 1)
            {
                List <D3DWizFaceSmall> LstFaces = new List <D3DWizFaceSmall>();

                for (int i = 0; i < header.nVertices; i++)
                {
                    D3DWizVertexSmall vertex = file.Read <D3DWizVertexSmall>(reader);
                    vertices.Add(new Vector3(vertex.x, vertex.y, vertex.z));
                    uvs.Add(new Vector2(0, 0));
                }

                for (int i = 0; i < header.nFaces; i++)
                {
                    D3DWizFaceSmall face = file.Read <D3DWizFaceSmall>(reader);
                    LstFaces.Add(face);
                }

                LstFaces = LstFaces.OrderBy(x => x.btMaterial).ToList();

                foreach (var face in LstFaces)
                {
                    if (!subMeshesTriangles.ContainsKey(face.btMaterial))
                    {
                        subMeshesTriangles.Add(face.btMaterial, new List <int>());
                    }

                    var shVertex1 = new Vector2(face.ftu1, -face.ftv1);
                    var shVertex2 = new Vector2(face.ftu2, -face.ftv2);
                    var shVertex3 = new Vector2(face.ftu3, -face.ftv3);

                    var InitVector2 = new Vector2(0, 0);

                    var idxVertex1 = 0;
                    var idxVertex2 = 0;
                    var idxVertex3 = 0;
                    if (uvs[face.shVertex1] == InitVector2)
                    {
                        uvs[face.shVertex1] = shVertex1;
                        idxVertex1          = face.shVertex1;
                    }
                    else if (uvs[face.shVertex1] != shVertex1)
                    {
                        vertices.Add(vertices[face.shVertex1]);
                        uvs.Add(shVertex1);
                        idxVertex1 = vertices.Count - 1;
                    }
                    else
                    {
                        idxVertex1 = face.shVertex1;
                    }

                    if (uvs[face.shVertex2] == InitVector2)
                    {
                        uvs[face.shVertex2] = shVertex2;
                        idxVertex2          = face.shVertex2;
                    }
                    else if (uvs[face.shVertex2] != shVertex2)
                    {
                        vertices.Add(vertices[face.shVertex2]);
                        uvs.Add(shVertex2);
                        idxVertex2 = vertices.Count - 1;
                    }
                    else
                    {
                        idxVertex2 = face.shVertex2;
                    }

                    if (uvs[face.shVertex3] == InitVector2)
                    {
                        uvs[face.shVertex3] = shVertex3;
                        idxVertex3          = face.shVertex3;
                    }
                    else if (uvs[face.shVertex3] != shVertex3)
                    {
                        vertices.Add(vertices[face.shVertex3]);
                        uvs.Add(shVertex3);
                        idxVertex3 = vertices.Count - 1;
                    }
                    else
                    {
                        idxVertex3 = face.shVertex3;
                    }

                    subMeshesTriangles[face.btMaterial].AddRange(new List <int>()
                    {
                        idxVertex1, idxVertex2, idxVertex3
                    });
                }
            }
            else
            {
                List <D3DWizFace> LstFaces = new List <D3DWizFace>();

                for (int i = 0; i < header.nVertices; i++)
                {
                    D3DWizVertex vertex = file.Read <D3DWizVertex>(reader);
                    vertices.Add(new Vector3(vertex.x, vertex.y, vertex.z));
                    uvs.Add(new Vector2(0, 0));
                }

                for (int i = 0; i < header.nFaces; i++)
                {
                    D3DWizFace face = file.Read <D3DWizFace>(reader);
                    LstFaces.Add(face);
                }

                LstFaces = LstFaces.OrderBy(x => x.nMaterial).ToList();

                foreach (var face in LstFaces)
                {
                    if (!subMeshesTriangles.ContainsKey((int)face.nMaterial))
                    {
                        subMeshesTriangles.Add((int)face.nMaterial, new List <int>());
                    }

                    var nVertex1 = new Vector2(face.ftu1, -face.ftv1);
                    var nVertex2 = new Vector2(face.ftu2, -face.ftv2);
                    var nVertex3 = new Vector2(face.ftu3, -face.ftv3);

                    var InitVector2 = new Vector2(0, 0);

                    var idxVertex1 = 0;
                    var idxVertex2 = 0;
                    var idxVertex3 = 0;
                    if (uvs[(int)face.nVertex1] == InitVector2)
                    {
                        uvs[(int)face.nVertex1] = nVertex1;
                        idxVertex1 = (int)face.nVertex1;
                    }
                    else if (uvs[(int)face.nVertex1] != nVertex1)
                    {
                        vertices.Add(vertices[(int)face.nVertex1]);
                        uvs.Add(nVertex1);
                        idxVertex1 = vertices.Count - 1;
                    }
                    else
                    {
                        idxVertex1 = (int)face.nVertex1;
                    }

                    if (uvs[(int)face.nVertex2] == InitVector2)
                    {
                        uvs[(int)face.nVertex2] = nVertex2;
                        idxVertex2 = (int)face.nVertex2;
                    }
                    else if (uvs[(int)face.nVertex2] != nVertex2)
                    {
                        vertices.Add(vertices[(int)face.nVertex2]);
                        uvs.Add(nVertex2);
                        idxVertex2 = vertices.Count - 1;
                    }
                    else
                    {
                        idxVertex2 = (int)face.nVertex2;
                    }

                    if (uvs[(int)face.nVertex3] == InitVector2)
                    {
                        uvs[(int)face.nVertex3] = nVertex3;
                        idxVertex3 = (int)face.nVertex3;
                    }
                    else if (uvs[(int)face.nVertex3] != nVertex3)
                    {
                        vertices.Add(vertices[(int)face.nVertex3]);
                        uvs.Add(nVertex3);
                        idxVertex3 = vertices.Count - 1;
                    }
                    else
                    {
                        idxVertex3 = (int)face.nVertex3;
                    }

                    subMeshesTriangles[(int)face.nMaterial].AddRange(new List <int>()
                    {
                        idxVertex1, idxVertex2, idxVertex3
                    });
                }
            }

            var NumberOfMaterials = reader.ReadUInt16();

            D3DWizMaterialSmall mat1 = file.Read <D3DWizMaterialSmall>(reader);

            if (mat1.btType == 4)
            {
                var w8Unity = Wizardry8Unity.Instance;

                for (int i = 1; i < NumberOfMaterials; i++)
                {
                    var itemMaterial = new Material(Shader.Find("Standard"));

                    D3DWizMaterial mat = file.Read <D3DWizMaterial>(reader);

                    if (mat.TextureFile == "")
                    {
                        Debug.Log("Material TextureFilename Empty: ");
                        Debug.Log(mat.Name);
                        Debug.Log(mat.TextureFile);

                        itemMaterial.SetColor("_Color", new Color(mat.rDiffuse, mat.gDiffuse, mat.bDiffuse, mat.aDiffuse));
                        //  continue;
                    }
                    else
                    {
                        var str  = @"ITEMS3D\BITMAPS\" + mat.TextureFile.ToUpper();
                        var data = w8Unity.ContentReader.DataFileReader.GetFile(str);

                        if (mat.f2 != 1) //IFL FIle
                        {
                            Debug.Log("ifl Texture - Not Animating Yet!");

                            var firstTGAFile = "";

                            using (StreamReader file = new StreamReader(new MemoryStream(data)))
                            {
                                string line;
                                while ((line = file.ReadLine()) != null)
                                {
                                    firstTGAFile = line;

                                    break;
                                }

                                file.Close();
                            }

                            str  = @"ITEMS3D\BITMAPS\" + firstTGAFile.ToUpper();
                            data = w8Unity.ContentReader.DataFileReader.GetFile(str);
                        }

                        var texture = TGALoader.LoadTGA(data);

                        itemMaterial.mainTexture = texture;
                    }

                    itemMaterial.SetFloat("_SmoothnessTextureChannel", 1);
                    itemMaterial.SetFloat("_Metallic", 0);
                    itemMaterial.SetFloat("_Glossiness", 1);

                    itemMaterial.SetOverrideTag("RenderType", "");
                    itemMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    itemMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    itemMaterial.SetInt("_ZWrite", 1);
                    itemMaterial.DisableKeyword("_ALPHATEST_ON");
                    itemMaterial.DisableKeyword("_ALPHABLEND_ON");
                    itemMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    itemMaterial.renderQueue = -1;

                    itemMaterial.SetColor("_EmissionColor", new Color(mat.rEmissive, mat.gEmissive, mat.bEmissive, mat.aEmissive));

                    itemMaterial.name = mat.Name;

                    this.itemMaterials.Add(itemMaterial);
                }
            }
            else
            {
                var w8Unity = Wizardry8Unity.Instance;

                for (int i = 1; i < NumberOfMaterials; i++)
                {
                    var itemMaterial = new Material(Shader.Find("Standard"));

                    D3DWizMaterialSmall mat = file.Read <D3DWizMaterialSmall>(reader);

                    if (mat.TextureFile == "")
                    {
                        Debug.Log("Material TextureFilename Empty: ");
                        Debug.Log(mat.Name);
                        Debug.Log(mat.TextureFile);

                        itemMaterial.SetColor("_Color", new Color(mat.rDiffuse, mat.gDiffuse, mat.bDiffuse, mat.aDiffuse));
                        //  continue;
                    }
                    else
                    {
                        var str  = @"ITEMS3D\BITMAPS\" + mat.TextureFile.ToUpper();
                        var data = w8Unity.ContentReader.DataFileReader.GetFile(str);
                        if (mat.f2 != 1)
                        {
                            Debug.LogError("ifl!");
                        }
                        var texture = TGALoader.LoadTGA(data);

                        itemMaterial.mainTexture = texture;
                    }


                    itemMaterial.SetColor("_EmissionColor", new Color(mat.rEmissive, mat.gEmissive, mat.bEmissive, mat.aEmissive));

                    itemMaterial.name = mat.Name;

                    this.itemMaterials.Add(itemMaterial);
                }
            }

            itemMesh = new Mesh();

            itemMesh.name = this.itemName;

            itemMesh.vertices = vertices.ToArray();; // vertices.ToArray();
            itemMesh.uv       = uvs.ToArray();;      // vertices.ToArray();

            itemMesh.subMeshCount = NumberOfMaterials - 1;

            foreach (var subm in subMeshesTriangles.Keys)
            {
                itemMesh.SetTriangles(subMeshesTriangles[subm], subm - 1);
            }



            // itemMesh.RecalculateNormals();

            UnityEngine.Debug.Log("finish");
        }
Пример #27
0
        private static object DoLoad(string file, string ext)
        {
            if (ext == "grf")
            {
                return(File.OpenRead(file));
            }
            else
            {
                using (var br = ReadSync(file)) {
                    if (br == null)
                    {
                        throw new Exception($"Could not load file: {file}");
                    }

                    switch (ext)
                    {
                    // Images
                    case "jpg":
                    case "jpeg":
                    case "png":
                        return(new RawImage()
                        {
                            data = br.ToArray()
                        });

                    case "bmp":
                        return(loader.LoadBMP(br));

                    case "tga":
                        return(TGALoader.LoadTGA(br));

                    // Text
                    case "txt":
                    case "xml":
                    case "lua":
                        return(Encoding.UTF8.GetString(br.ToArray()));

                    case "spr":
                        SPR spr = SpriteLoader.Load(br);
                        spr.SwitchToRGBA();
                        spr.Compile();
                        spr.filename = file;
                        return(spr);

                    case "str":
                        return(EffectLoader.Load(br, Path.GetDirectoryName(file).Replace("\\", "/")));

                    case "act":
                        return(ActionLoader.Load(br));

                    // Binary
                    case "gat":
                        return(AltitudeLoader.Load(br));

                    case "rsw":
                        return(WorldLoader.Load(br));

                    case "gnd":
                        return(GroundLoader.Load(br));

                    case "rsm":
                        return(ModelLoader.Load(br));

                    // Audio
                    case "wav":
                        WAVLoader.WAVFile wav  = WAVLoader.OpenWAV(br.ToArray());
                        AudioClip         clip = AudioClip.Create(file, wav.samples, wav.channels, wav.sampleRate, false);
                        clip.SetData(wav.leftChannel, 0);
                        return(clip);

                    case "mp3":
                    case "ogg":
                        break;

                    case "json":
                        return(JObject.Parse(Encoding.UTF8.GetString(br.ToArray())));

                    default:
                        throw new Exception($"Unsuported file format: {ext} for file {file}");
                    }
                }
            }
            return(null);
        }
Пример #28
0
    /// <summary>
    /// Loads the image at index.
    /// </summary>
    /// <returns>The <see cref="UnityEngine.Texture2D"/>.</returns>
    /// <param name="index">Index.</param>
    /// <param name="palToUse">Pal to use.</param>
    /// If the index is greater than 209 I return a floor texture.
    public Texture2D LoadImageAt(int index, Palette palToUse)
    {
        if (_RES == GAME_UWDEMO)
        {        //Point the UW1 texture files to the demo files
            TextureSplit = 48;
            pathTexW_UW1 = pathTexW_UW0;
            pathTexF_UW1 = pathTexF_UW0;
        }
        if (_RES == GAME_UW2)
        {
            FloorDim = 64;
        }

        switch (_RES)
        {
        case GAME_SHOCK:
        {
            if (texturesFLoaded == false)
            {
                if (!DataLoader.ReadStreamFile(BasePath + pathTex_SS1, out texturebufferT))
                {
                    return(base.LoadImageAt(index));
                }
                else
                {
                    texturesFLoaded = true;
                }
            }
            //Load the chunk requested
            //For textures this is index + 1000
            DataLoader.Chunk art_ark;
            if (DataLoader.LoadChunk(texturebufferT, index + 1000, out art_ark))
            {
                switch (art_ark.chunkContentType)
                {
                case 2:
                case 17:
                {
                    long textureOffset   = (int)DataLoader.getValAtAddress(art_ark.data, 2 + (0 * 4), 32);
                    int  CompressionType = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 4, 16);
                    int  Width           = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 8, 16);
                    int  Height          = (int)DataLoader.getValAtAddress(art_ark.data, textureOffset + 10, 16);
                    if ((Width > 0) && (Height > 0))
                    {
                        if (CompressionType == 4)
                        {                                                        //compressed
                            char[] outputImg;
                            //  UncompressBitmap(art_ark+textureOffset+BitMapHeaderSize, outputImg,Height*Width);
                            UncompressBitmap(art_ark.data, textureOffset + BitMapHeaderSize, out outputImg, Height * Width);
                            return(Image(outputImg, 0, Width, Height, "namehere", palToUse, true));
                        }
                        else
                        {                                                        //Uncompressed
                            return(Image(art_ark.data, textureOffset + BitMapHeaderSize, Width, Height, "namehere", palToUse, true));
                        }
                    }
                    else
                    {
                        return(base.LoadImageAt(index));
                    }
                }
                    //break;
                }
            }

            return(base.LoadImageAt(index));
        }

        case GAME_UW2:
        {
            if (LoadMod)
            {
                if (File.Exists(ModPathW + "\\" + index.ToString("d3") + ".tga"))
                {
                    return(TGALoader.LoadTGA(ModPathW + "\\" + index.ToString("d3") + ".tga"));
                }
            }
            if (texturesFLoaded == false)
            {
                if (!DataLoader.ReadStreamFile(BasePath + pathTex_UW2, out texturebufferT))
                {
                    return(base.LoadImageAt(index));
                }
                else
                {
                    texturesFLoaded = true;
                }
            }
            long textureOffset = DataLoader.getValAtAddress(texturebufferT, ((index) * 4) + 4, 32);
            return(Image(texturebufferT, textureOffset, FloorDim, FloorDim, "name_goes_here", palToUse, false));
        }


        case GAME_UWDEMO:
        case GAME_UW1:
        default:
        {
            if (index < TextureSplit)
            {                    //Wall textures
                if (texturesWLoaded == false)
                {
                    if (!DataLoader.ReadStreamFile(BasePath + pathTexW_UW1, out texturebufferW))
                    {
                        return(base.LoadImageAt(index));
                    }
                    else
                    {
                        texturesWLoaded = true;
                    }
                }
                if (LoadMod)
                {
                    if (File.Exists(ModPathW + "\\" + index.ToString("d3") + ".tga"))
                    {
                        return(TGALoader.LoadTGA(ModPathW + "\\" + index.ToString("d3") + ".tga"));
                    }
                }
                long textureOffset = DataLoader.getValAtAddress(texturebufferW, (index * 4) + 4, 32);
                return(Image(texturebufferW, textureOffset, 64, 64, "name_goes_here", palToUse, false));
            }
            else
            {                    //Floor textures (to match my list of textures)
                if (texturesFLoaded == false)
                {
                    if (!DataLoader.ReadStreamFile(BasePath + pathTexF_UW1, out texturebufferF))
                    {
                        return(base.LoadImageAt(index));
                    }
                    else
                    {
                        texturesFLoaded = true;
                    }
                }
                if (LoadMod)
                {
                    if (File.Exists(ModPathF + "\\" + index.ToString("d3") + ".tga"))
                    {
                        return(TGALoader.LoadTGA(ModPathF + "\\" + index.ToString("d3") + ".tga"));
                    }
                }
                long textureOffset = DataLoader.getValAtAddress(texturebufferF, ((index - TextureSplit) * 4) + 4, 32);
                return(Image(texturebufferF, textureOffset, FloorDim, FloorDim, "name_goes_here", palToUse, false));
            }
        }                //end switch
        }
    }