示例#1
0
        public void TestTexturePackerWithMultiPack()
        {
            var textureElements = CreateFakeTextureElements();

            var texturePacker = new TexturePacker
            {
                AllowMultipack = true,
                AllowRotation  = true,
                MaxHeight      = 300,
                MaxWidth       = 300,
            };

            var canPackAllTextures = texturePacker.PackTextures(textureElements);

            Assert.Equal(2, textureElements.Count);
            Assert.Empty(texturePacker.AtlasTextureLayouts);
            Assert.False(canPackAllTextures);

            texturePacker.Reset();
            texturePacker.MaxWidth  = 1500;
            texturePacker.MaxHeight = 800;

            canPackAllTextures = texturePacker.PackTextures(textureElements);

            Assert.True(canPackAllTextures);
            Assert.Single(texturePacker.AtlasTextureLayouts);
            Assert.Equal(textureElements.Count, texturePacker.AtlasTextureLayouts[0].Textures.Count);

            Assert.True(MathUtil.IsPow2(texturePacker.AtlasTextureLayouts[0].Width));
            Assert.True(MathUtil.IsPow2(texturePacker.AtlasTextureLayouts[0].Height));
        }
示例#2
0
    void OnGUI()
    {
        if (Application.isPlaying)
        {
            GUILayout.Label("playing");
            SpriteReferenceInfoDetector.watchEditorChange = false;
            return;
        }

        GUILayout.BeginHorizontal();
        bool scanAtlas      = GUILayout.Button("Scan Atlas", GUILayout.Width(100));
        bool scanGameObject = GUILayout.Button("Scan Reference", GUILayout.Width(100));
        bool updateAtlas    = GUILayout.Button("Update Atlas", GUILayout.Width(100));

        SpriteReferenceInfoDetector.watchEditorChange = GUILayout.Toggle(SpriteReferenceInfoDetector.watchEditorChange, "watching");
        scan_scene = GUILayout.Toggle(scan_scene, "scan scene");
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();

        Rect atlasRect = new Rect(0, 30, position.width / 2 - 5, position.height);

        if (m_AtlasListTree == null)
        {
            m_AtlasListTree = new AtlasListView(this);
            ReloadTreeView();
        }
        m_AtlasListTree.OnGUI(atlasRect);

        if (m_ReferenceListView == null)
        {
            m_ReferenceListView = new ReferenceListView();
            m_ReferenceListView.Reload();
        }

        Rect refRect = new Rect(position.width / 2 + 5, 30, position.width / 2 - 5, position.height);

        m_ReferenceListView.OnGUI(refRect);

        if (scanAtlas)
        {
            ScanSpriteAtlas();
        }

        if (scanGameObject)
        {
            SpriteReferenceInfo.Instance.Scan(scan_scene);
        }

        if (updateAtlas)
        {
            SpriteAtlasData            atlas  = null;
            SpriteAtlasData.SpriteInfo sprite = null;
            Sprite origin = null;
            if (m_AtlasListTree.GetSelectAtlas(out atlas, out sprite, out origin))
            {
                TexturePacker.Pack(atlas.sprites, atlas.texture);
                atlas.Scan();
            }
        }
    }
示例#3
0
        public void Deduplicate(string remappingPath)
        {
            using (TexturePacker levelPacker = new TexturePacker(Level))
            {
                Dictionary <TexturedTile, List <TexturedTileSegment> > allTextures = new Dictionary <TexturedTile, List <TexturedTileSegment> >();
                foreach (TexturedTile tile in levelPacker.Tiles)
                {
                    allTextures[tile] = new List <TexturedTileSegment>(tile.Rectangles);
                }

                TextureRemapGroup remapGroup = JsonConvert.DeserializeObject <TextureRemapGroup>(File.ReadAllText(remappingPath));

                _deduplicator.SegmentMap           = allTextures;
                _deduplicator.PrecompiledRemapping = remapGroup.Remapping;
                _deduplicator.Deduplicate();

                levelPacker.AllowEmptyPacking = true;
                levelPacker.Pack(true);

                // Now we want to go through every IndexedTexture and see if it's
                // pointing to the same thing - so tile, position, and point direction
                // have to be equal. See IndexedTRObjectTexture
                Dictionary <int, int> indexMap = new Dictionary <int, int>();
                foreach (TexturedTile tile in allTextures.Keys)
                {
                    foreach (TexturedTileSegment segment in allTextures[tile])
                    {
                        TidySegment(segment, indexMap);
                    }
                }

                Level.ReindexTextures(indexMap);
                Level.ResetUnusedTextures();
            }
        }
示例#4
0
    }                                                   // スピードの実効値を取得する。ストッピング計算に使用するだけなので、微妙。



    // メッシュ単一化(使わなくてもいい) ----------------------------------------------

    public virtual GameObject combineMesh(bool isForcePackTexture = false)
    {
        var tfmeshbody = transform.Find("body/Mesh");


        var meshbody = tfmeshbody.gameObject;


        if (isForcePackTexture)
        // 単体でテクスチャをパックしてしまうか
        {
            var tpacker = new TexturePacker();

            tpacker.regist(meshbody);

            tpacker.packTextures();
        }


        var csm = new CombineSkinnedMesh();

        csm.combine(meshbody);

        csm.addRenderer(meshbody, Shader.Find("Custom/SkinnedMesh_1bone_nolit"));


        return(meshbody);
    }
示例#5
0
        private VectorInt2 AllocateTexture(WadTexture texture)
        {
            // Check if the texture is already loaded
            {
                VectorInt2 position;
                if (PackedTextures.TryGetValue(texture, out position))
                {
                    return(position);
                }
            }

            // Allocate texture
            {
                VectorInt2?position = TexturePacker.TryAdd(texture.Image.Size);
                if (position == null)
                {
                    throw new TextureAtlasFullException();
                }

                // Upload texture
                if (Texture == null)
                {
                    Texture = Texture2D.New(GraphicsDevice, TextureAtlasSize, TextureAtlasSize, SharpDX.DXGI.Format.B8G8R8A8_UNorm, TextureFlags.ShaderResource, 1, SharpDX.Direct3D11.ResourceUsage.Default);
                }
                TextureLoad.Update(GraphicsDevice, Texture, texture.Image, position.Value);
                PackedTextures.Add(texture, position.Value);
                return(position.Value);
            }
        }
示例#6
0
文件: main.cs 项目: wachel/block
 void Start()
 {
     texturePacker = new TexturePacker();
     SimpleModelFactory.CreateAll();
     HouseItemGenerator.Init();
     StartCoroutine(InitWorld());
 }
    //[MenuItem("Assets/TexturePacker/Process to Sprites")]
    static void ProcessToSprite(int pivot)
    {
        TextAsset txt = (TextAsset)Selection.activeObject;

        string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(txt));

        TexturePacker.MetaData meta = TexturePacker.GetMetaData(txt.text);

        List <SpriteMetaData> sprites = TexturePacker.ProcessToSprites(txt.text, pivot);

        string imageName = meta.image;

        //validate image name, if it's null or something, then try to load the sprite with the same name as text file with png extension
        if ((imageName == null) || (imageName.Length <= 0))
        {
            imageName  = Selection.activeObject.name;
            imageName += ".png";
        }
        string path = rootPath + "/" + imageName;

        Debug.Log("Loading spritesheet at: " + path);
        TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;

        texImp.spritesheet      = sprites.ToArray();
        texImp.textureType      = TextureImporterType.Sprite;
        texImp.spriteImportMode = SpriteImportMode.Multiple;

        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
    }
示例#8
0
        public void DicedTexturesArePreserved()
        {
            var dicedTexture = new DicedTexture(new SourceTexture("B", B), Array.Empty <DicedUnit>());
            var atlasTexture = new TexturePacker(new MockTextureSerializer(), 0, false, 1, 1, 0).Pack(new[] { dicedTexture })[0];

            AreEqual(dicedTexture, atlasTexture.DicedTextures[0]);
        }
示例#9
0
        public void TestPackTexture()
        {
            var resPath = Path.Combine(Environment.CurrentDirectory, @"..\..\Res");

            var path     = Path.Combine(resPath, "澄怜a_裸.psb-pure");
            var savePath = Path.Combine(path, "packed");
            Dictionary <string, Image> imgs = new Dictionary <string, Image>();

            foreach (var file in Directory.EnumerateFiles(path, "*.png", SearchOption.AllDirectories))
            {
                imgs.Add(file, Image.FromFile(file));
            }

            TexturePacker packer = new TexturePacker
            {
                FitHeuristic = BestFitHeuristic.MaxOneAxis,
            };

            packer.Process(imgs, 4096, 5, false);
            if (Directory.Exists(savePath))
            {
                Directory.Delete(savePath, true);
            }

            Directory.CreateDirectory(savePath);
            packer.SaveAtlasses(Path.Combine(savePath, "tex.txt"));
        }
示例#10
0
        static int CalcTextureSize(IList <Tile> tiles, int minSize = 128, int maxSize = 2048, int padding = 0)
        {
            int size = minSize;

            while (size < maxSize)
            {
                var packer       = new TexturePacker(size, size, padding);
                int textureCount = 0;
                foreach (var tile in tiles)
                {
                    var pack = packer.put(tile.width, -tile.height);
                    if (pack.newTexture)
                    {
                        ++textureCount;
                    }
                    if (textureCount > 1)
                    {
                        break;
                    }
                }

                if (textureCount == 1)
                {
                    break;
                }

                size *= 2;
            }
            return(size);
        }
示例#11
0
    //处理一个文件
    private static void ProcessOneFile(string txtPath)
    {
        txtPath = txtPath.Replace("\\", "/");
        Debug.Log("开始处理图集" + txtPath.Substring(0, txtPath.LastIndexOf("_cfg")) + ".png");

        string rootPath = txtPath;

        rootPath = rootPath.Substring(rootPath.IndexOf("Assets"));
        TextAsset txt = AssetDatabase.LoadAssetAtPath <TextAsset>(rootPath);

        string[] p      = rootPath.Split(new string[] { "/" }, StringSplitOptions.None);
        string   folder = p[p.Length - 2];

        TexturePacker.MetaData meta = TexturePacker.GetMetaData(txt.text);

        List <SpriteMetaData> sprites = TexturePacker.ProcessToSprites(txt.text, folder);

        rootPath = rootPath.Substring(0, rootPath.LastIndexOf("/"));

        string          path   = rootPath + "/" + meta.image;
        TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;

        texImp.spritesheet      = sprites.ToArray();
        texImp.textureType      = TextureImporterType.Sprite;
        texImp.spriteImportMode = SpriteImportMode.Multiple;

        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
    }
示例#12
0
        private void ExportDuplicateLevelTextures(string lvlPath)
        {
            TR2Level level = _reader.ReadLevel(lvlPath);

            using (TexturePacker levelPacker = new TexturePacker(level))
            {
                Dictionary <TexturedTile, List <TexturedTileSegment> > allTextures = new Dictionary <TexturedTile, List <TexturedTileSegment> >();
                foreach (TexturedTile tile in levelPacker.Tiles)
                {
                    allTextures[tile] = new List <TexturedTileSegment>(tile.Rectangles);
                }

                _deduplicator.SegmentMap = allTextures;
                _deduplicator.Deduplicate();

                if (_levelRemap.ContainsKey(_currentLevel))
                {
                    if (_outputTileImages)
                    {
                        string dir = Path.Combine(_outputDirectory, _currentLevel);
                        Directory.CreateDirectory(dir);
                        foreach (TexturedTile tile in allTextures.Keys)
                        {
                            tile.BitmapGraphics.Bitmap.Save(Path.Combine(dir, tile.Index.ToString() + ".png"), ImageFormat.Png);
                        }
                    }

                    File.WriteAllText(Path.Combine(_outputDirectory, _currentLevel + "-TextureRemap.json"), JsonConvert.SerializeObject(_levelRemap[_currentLevel], Formatting.Indented));
                }
            }
        }
示例#13
0
    public void Render1()
    {
        if (!_flag1)
        {
            return;
        }
        _flag1     = false;
        _texPacker = new TexturePacker();
        List <Texture2D> tmp = new List <Texture2D>();

        for (int i = 1; i < 16; i++)
        {
            Texture2D tex = AssetDatabase.LoadAssetAtPath <Texture2D>(string.Format("Assets/res_bundle/icon/Buff/{0:00}.png", i));
            _texPacker.AddTexture2D(tex);
            tmp.Add(tex);
        }
        _texPacker.PackerTexture();
        for (int i = tmp.Count - 1; i >= 0; i--)
        {
            Texture2D tex = tmp[i];
            tmp.RemoveAt(i);
            Resources.UnloadAsset(tex);
        }
        for (int i = 0; i < _imgs.Count; i++)
        {
            _imgs[i].sprite = _texPacker.GetSprite(string.Format("{0:00}", (i + 1)));
        }

        MainTex = _texPacker._mainTex;
    }
示例#14
0
        private void GenerateAtlas()
        {
            Rect[]    rectAreas;
            Texture2D returnTexture = TexturePacker.AtlasTextures(textures.ToArray(), 2048, out rectAreas);

            int lengthOfArrays = catagory.Count;

            for (int i = 0; i < lengthOfArrays; i++)
            {
                if (catagory[i] == TypeofEditorTile.Terrain)
                {
                    tileLocations.Add(tileManager.tiles[tempTileType[i]], rectAreas[i]);
                }
                else if (catagory[i] == TypeofEditorTile.Resource)
                {
                    resourceLocations.Add(resourceManager.resources[tempResourceType[i]], rectAreas[i]);
                }
                else
                {
                    improvementLocations.Add(improvementManager.improvements[tempImprovementType[i]], rectAreas[i]);
                }
            }

            FileUtility.SaveTexture(returnTexture, loc, "TerrainAtlas", false);
            worldManager.textureAtlas.terrainAtlas         = (Texture2D)AssetDatabase.LoadAssetAtPath(editedLoc + "/TerrainAtlas.png", typeof(Texture2D));
            worldManager.textureAtlas.tileLocations        = (TileItem[])tileLocations.ToArray().Clone();
            worldManager.textureAtlas.resourceLocations    = (ResourceItem[])resourceLocations.ToArray().Clone();
            worldManager.textureAtlas.improvementLocations = (ImprovementItem[])improvementLocations.ToArray().Clone();


            EditorUtility.UnloadUnusedAssets();
            Resources.UnloadUnusedAssets();
            this.Close();
        }
示例#15
0
        private void RemoveUnusedSprites(TexturePacker packer)
        {
            // TODO: We could potentially work out if guns/ammo other
            // than pistols can be removed - would need to get secret
            // rewards and convert to entities as script uses different
            // IDs.
            List <TR2Entities> unusedItems = new List <TR2Entities>
            {
                TR2Entities.PistolAmmo_S_P,
                TR2Entities.Map_M_U,
                TR2Entities.GrayDisk_S_H
            };

            ISet <TR2Entities> allEntities = new HashSet <TR2Entities>();

            for (int i = 0; i < Level.Entities.Length; i++)
            {
                allEntities.Add((TR2Entities)Level.Entities[i].TypeID);
            }

            for (int i = unusedItems.Count - 1; i >= 0; i--)
            {
                if (unusedItems[i] != TR2Entities.GrayDisk_S_H && allEntities.Contains(unusedItems[i]))
                {
                    unusedItems.RemoveAt(i);
                }
            }

            packer.RemoveSpriteSegments(unusedItems);
        }
        /// <summary>
        /// 计算合并贴图 Atlas Rect
        /// </summary>
        /// <param name="data"></param>
        /// <param name="doMultiAtlas"></param>
        /// <returns></returns>
        public static AtlasPackingResult[] CalculateAtlasRectanglesStatic(TextureCombinePipelineData data, bool doMultiAtlas)
        {
            List <Vector2> imageSizes = new List <Vector2>();

            for (int i = 0; i < data.distinctMaterialTextures.Count; i++)
            {
                imageSizes.Add(new Vector2(data.distinctMaterialTextures[i].idealWidth, data.distinctMaterialTextures[i].idealHeight));
            }

            TexturePacker tp = CreateTexturePacker(data.packingAlgorithm);

            tp.atlasMustBePowerOfTwo = data.meshBakerTexturePackerForcePowerOfTwo;

            List <AtlasPadding> paddings = new List <AtlasPadding>();

            for (int i = 0; i < imageSizes.Count; i++)
            {
                AtlasPadding padding = new AtlasPadding();
                padding.topBottom = data.atlasPadding;
                padding.leftRight = data.atlasPadding;
                if (data.packingAlgorithm == PackingAlgorithmEnum.MeshBakerTexturePacker_Horizontal)
                {
                    padding.leftRight = 0;
                }
                if (data.packingAlgorithm == PackingAlgorithmEnum.MeshBakerTexturePacker_Vertical)
                {
                    padding.topBottom = 0;
                }
                paddings.Add(padding);
            }

            return(tp.GetRects(imageSizes, paddings, data.maxAtlasWidth, data.maxAtlasHeight, doMultiAtlas));
        }
示例#17
0
        public void TestRotationElement1()
        {
            var textureElements = new List <AtlasTextureElement>
            {
                CreateElementFromFile("imageRotated0", 0, TextureAddressMode.Clamp, TextureAddressMode.Clamp)
            };

            textureElements[0].SourceRegion.IsRotated = true;

            var texturePacker = new TexturePacker
            {
                AllowMultipack = true,
                AllowRotation  = true,
                MaxWidth       = 128,
                MaxHeight      = 256,
            };

            var canPackAllTextures = texturePacker.PackTextures(textureElements);

            Assert.True(canPackAllTextures);
            Assert.Single(texturePacker.AtlasTextureLayouts);

            var atlasTexture = AtlasTextureFactory.CreateTextureAtlas(texturePacker.AtlasTextureLayouts[0], false);

            SaveAndCompareTexture(atlasTexture, "TestRotationElement1");
        }
示例#18
0
    public static List <SpriteMetaData> ProcessToSprites(string text)
    {
        Hashtable hashtable = text.hashtableFromJson();

        TexturePacker.MetaData           metaData = new TexturePacker.MetaData((Hashtable)hashtable["meta"]);
        List <TexturePacker.PackedFrame> list     = new List <TexturePacker.PackedFrame>();
        Hashtable hashtable2 = (Hashtable)hashtable["frames"];

        foreach (object obj in hashtable2)
        {
            DictionaryEntry dictionaryEntry = (DictionaryEntry)obj;
            list.Add(new TexturePacker.PackedFrame((string)dictionaryEntry.Key, metaData.size, (Hashtable)dictionaryEntry.Value));
        }
        TexturePacker.SortFrames(list);
        List <SpriteMetaData> list2 = new List <SpriteMetaData>();

        for (int i = 0; i < list.Count; i++)
        {
            SpriteMetaData spriteMetaData = list[i].BuildBasicSprite(0.01f, new Color32(128, 128, 128, 128));
            bool           flag           = !spriteMetaData.name.Equals("IGNORE_SPRITE");
            if (flag)
            {
                list2.Add(spriteMetaData);
            }
        }
        return(list2);
    }
示例#19
0
 public Sprite GetSprite(string atlasName, string spriteName)
 {
     if (!spritePackers.ContainsKey(atlasName))
     {
         spritePackers [atlasName] = new TexturePacker(atlasName);
     }
     return(spritePackers [atlasName].GetSprite(spriteName));
 }
示例#20
0
        public void TestCreateTextureAtlasToOutput()
        {
            var textureElements = new List <AtlasTextureElement>
            {
                CreateElement("MediumPurple", 130, 158, 10, TextureAddressMode.Border, Color.MediumPurple, Color.SteelBlue),
                CreateElement("Red", 127, 248, 10, TextureAddressMode.Border, Color.Red, Color.SteelBlue),
                CreateElement("Blue", 212, 153, 10, TextureAddressMode.Border, Color.Blue, Color.SteelBlue),
                CreateElement("Gold", 78, 100, 10, TextureAddressMode.Border, Color.Gold, Color.SteelBlue),
                CreateElement("RosyBrown", 78, 100, 10, TextureAddressMode.Border, Color.RosyBrown, Color.SteelBlue),
                CreateElement("SaddleBrown", 400, 100, 10, TextureAddressMode.Border, Color.SaddleBrown, Color.SteelBlue),
                CreateElement("Salmon", 400, 200, 10, TextureAddressMode.Border, Color.Salmon, Color.SteelBlue),
                CreateElement("PowderBlue", 190, 200, 10, TextureAddressMode.Border, Color.PowderBlue, Color.SteelBlue),
                CreateElement("Orange", 200, 230, 10, TextureAddressMode.Border, Color.Orange, Color.SteelBlue),
                CreateElement("Silver", 100, 170, 10, TextureAddressMode.Border, Color.Silver, Color.SteelBlue),
                CreateElement("SlateGray", 100, 170, 10, TextureAddressMode.Border, Color.SlateGray, Color.SteelBlue),
                CreateElement("Tan", 140, 110, 10, TextureAddressMode.Border, Color.Tan, Color.SteelBlue),
            };

            var texturePacker = new TexturePacker
            {
                AllowMultipack = false,
                AllowRotation  = true,
                MaxHeight      = 1024,
                MaxWidth       = 1024
            };

            var canPackAllTextures = texturePacker.PackTextures(textureElements);

            Assert.True(canPackAllTextures);

            // Obtain texture atlases
            var textureAtlases = texturePacker.AtlasTextureLayouts;

            Assert.Single(textureAtlases);

            if (!texturePacker.AllowNonPowerOfTwo)
            {
                Assert.True(MathUtil.IsPow2(textureAtlases[0].Width));
                Assert.True(MathUtil.IsPow2(textureAtlases[0].Height));
            }

            // Create atlas texture
            var atlasTexture = AtlasTextureFactory.CreateTextureAtlas(textureAtlases[0], false);

            SaveAndCompareTexture(atlasTexture, "TestCreateTextureAtlasToOutput");

            Assert.Equal(textureAtlases[0].Width, atlasTexture.Description.Width);
            Assert.Equal(textureAtlases[0].Height, atlasTexture.Description.Height);

            atlasTexture.Dispose();

            foreach (var texture in textureAtlases.SelectMany(textureAtlas => textureAtlas.Textures))
            {
                texture.Texture.Dispose();
            }
        }
示例#21
0
        public static void Load(GraphicsDevice graphics)
        {
            TexturePacker.LoadAsset(graphics, "AsteroidsAtlas", true);
            TexturePacker.LoadAsset(graphics, "ShipsAtlas", true);
            TexturePacker.LoadAsset(graphics, "ParticlesAtlas", true);
            TexturePacker.LoadAsset(graphics, "ResourcesAtlas", false);

            ShieldTexture = ModManager.Instance.AssetManager.LoadTexture2D(graphics, "Shield", true);
            DefaultFont   = ModManager.Instance.AssetManager.LoadDynamicSpriteFont("latoblack");
        }
 /// <summary>
 /// Creates AbsoluteAtlas.
 /// Setting initial size is good if minimum size of textures can be predicted.
 /// </summary>
 /// <param name="maxSize">Max size of the atlas texture. Must be greater or equal than 64 x 64.</param>
 /// <param name="initialSize">Initial size of the atlas texture. Must be smaller or equal to MaxSize</param>
 public AbsoluteAtlas(string atlasName, Vector2 maxSize, Vector2 initialSize)
     : base(atlasName, maxSize)
 {
     this.initialSize = initialSize;
     if (initialSize.x > maxSize.x || initialSize.y > maxSize.y)
     {
         Debug.LogError("Absolute atlas initial size can not be greater than maximum size of it. " + atlasName);
     }
     packer = new TexturePacker(initialSize, false);
 }
示例#23
0
        public void LoadData()
        {
            var data = EntityData.ShipTypes[Type];

            Sprite    = TexturePacker.GetSprite("ShipsAtlas", data.Sprite);
            Origin    = new Vector2(Sprite.SourceRect.Width / 2, Sprite.SourceRect.Height / 2);
            MoveSpeed = data.MoveSpeed;
            TurnSpeed = data.TurnSpeed;

            BaseArmourHP        = data.ArmourHP;
            BaseShieldHP        = data.ShieldHP;
            BaseShieldRegenRate = data.ShieldRegenRate;

            CurrentArmourHP        = BaseArmourHP;
            CurrentShieldHP        = BaseShieldHP;
            CurrentShieldRegenRate = BaseShieldRegenRate;

            Weapons = new List <Weapon>();

            foreach (var weapon in data.Weapons)
            {
                Weapons.Add(new Weapon()
                {
                    Type            = weapon.Type,
                    Range           = weapon.Range,
                    Cooldown        = weapon.Cooldown,
                    Damage          = weapon.Damage,
                    CurrentCooldown = weapon.Cooldown,
                });
            }

            foreach (var weapon in Weapons)
            {
                if (MinWeaponRange == -1 || weapon.Range < MinWeaponRange)
                {
                    MinWeaponRange = weapon.Range;
                }
                if (MaxWeaponRange == -1 || weapon.Range > MaxWeaponRange)
                {
                    MaxWeaponRange = weapon.Range;
                }
            }

            ShieldSprite          = new Sprite(Sprites.ShieldTexture);
            ShieldSprite.Colour   = Color.Turquoise;
            ShieldSprite.Colour.A = 0;
            ActivateShield();

            float shipSize = (Sprite.SourceRect.Width > Sprite.SourceRect.Height ? Sprite.SourceRect.Width : Sprite.SourceRect.Height);

            shipSize *= 1.4f;

            ShieldSprite.Scale = shipSize / ShieldSprite.Width;
            ShieldRadius       = ShieldSprite.Width * ShieldSprite.Scale;
        }
示例#24
0
        private static List <AtlasTexture> Pack(Texture2D[] textures,
                                                float uvInset = 0, bool square = false, int sizeLimit = 8, int unitSize = 1, int padding = 0)
        {
            // TODO: Don't use dicer here; create mock diced textures instead.
            var dicer         = new TextureDicer(unitSize, padding);
            var dicedTextures = textures.Select(t => new SourceTexture(t.name, t)).Select(dicer.Dice);
            var serializer    = new MockTextureSerializer();
            var packer        = new TexturePacker(serializer, uvInset, square, sizeLimit, unitSize, padding);

            return(packer.Pack(dicedTextures));
        }
示例#25
0
 static void Main(string[] args)
 {
     if (args.Length > 0)
     {
         TexturePacker.Extract(args[0]);
     }
     else
     {
         Console.WriteLine("please enter the folder or file you want to extract.");
     }
 }
示例#26
0
        private void PreloadReplaceTextures(IEnumerable <WadMoveable> newMoveables, IEnumerable <WadStatic> newStatics)
        {
            Dispose();

            // Collect textures
            var textures = new HashSet <WadTexture>();

            foreach (var moveable in newMoveables)
            {
                foreach (var mesh in moveable.Meshes)
                {
                    foreach (WadPolygon polygon in mesh.Polys)
                    {
                        textures.Add((WadTexture)polygon.Texture.Texture);
                    }
                }
            }
            foreach (var stat in newStatics)
            {
                foreach (WadPolygon polygon in stat.Mesh.Polys)
                {
                    textures.Add((WadTexture)polygon.Texture.Texture);
                }
            }

            // Order textures for packing
            var packedTextures = new List <WadTexture>(textures);

            packedTextures.Sort(new ComparerWadTextures());

            // Pack the textures in a single atlas
            CreateTexturePacker();
            foreach (var texture in packedTextures)
            {
                VectorInt2?positionInAtlas = TexturePacker.TryAdd(texture.Image.Size);
                if (positionInAtlas == null)
                {
                    throw new TextureAtlasFullException();
                }
                PackedTextures.Add(texture, positionInAtlas.Value);
            }

            // Create texture atlas
            var tempBitmap = ImageC.CreateNew(TextureAtlasSize, TextureAtlasSize);

            foreach (var texture in PackedTextures)
            {
                tempBitmap.CopyFrom(texture.Value.X, texture.Value.Y, texture.Key.Image);
            }
            Texture = TextureLoad.Load(GraphicsDevice, tempBitmap, SharpDX.Direct3D11.ResourceUsage.Default);
        }
示例#27
0
        private Dictionary <Guid, string> ProcessObjectTextures(Project input, ContentProcessorContext context, out List <Page> pages)
        {
            Dictionary <Guid, string> texAssetMap = new Dictionary <Guid, string>();

            pages = new List <Page>();

            string assetPath = Path.GetDirectoryName(context.OutputFilename).Substring(context.OutputDirectory.Length);

            if (!Directory.Exists(Path.Combine(BuildPath, assetPath)))
            {
                Directory.CreateDirectory(Path.Combine(BuildPath, assetPath));
            }

            foreach (ObjectPool pool in input.ObjectPoolManager.Pools)
            {
                string path = Path.Combine(BuildPath, assetPath, "objects-" + pool.Uid + ".png");
                //Debugger.Launch();
                TexturePacker packer = new TexturePacker(Path.Combine(BuildPath, assetPath), new Settings()
                {
                    Rotation = false,
                });
                foreach (ObjectClass obj in pool.Objects)
                {
                    using (Bitmap image = obj.Image.CreateBitmap()) {
                        packer.AddImage(image, obj.Uid.ToString());
                    }
                }

                pages.AddRange(packer.Pack(Path.Combine(BuildPath, assetPath), "objects-" + pool.Uid));

                string assetName = Path.GetFileNameWithoutExtension(path).Substring(BuildPath.Length);

                OpaqueDataDictionary data = new OpaqueDataDictionary()
                {
                    { "GenerateMipmaps", false },
                    { "ResizeToPowerofTwo", false },
                    { "TextureFormat", TextureProcessorOutputFormat.Color },
                };

                context.BuildAsset <TextureContent, TextureContent>(
                    new ExternalReference <TextureContent>(path),
                    "TextureProcessor",
                    data,
                    "TextureImporter",
                    assetName);

                texAssetMap[pool.Uid] = assetName;
            }

            return(texAssetMap);
        }
示例#28
0
文件: DC6.cs 项目: D7tila/Diablerie
    private Direction ReadFrames(Stream stream, BinaryReader reader, int dirIndex)
    {
        int internalIndex = DirectionMapping.MapToInternal(directionCount, dirIndex);
        var dir           = new Direction();

        dir.frames  = new Frame[framesPerDirection];
        dir.sprites = new Sprite[framesPerDirection];
        int maxWidth  = 0;
        int maxHeight = 0;

        for (int frameIndex = 0; frameIndex < framesPerDirection; frameIndex++)
        {
            int offset = offsets[internalIndex * framesPerDirection + frameIndex];
            stream.Seek(offset, SeekOrigin.Begin);

            var frame = new Frame();
            reader.ReadInt32(); // skip
            frame.width   = reader.ReadInt32();
            frame.height  = reader.ReadInt32();
            frame.offsetX = reader.ReadInt32();
            frame.offsetY = reader.ReadInt32();
            reader.ReadInt32(); // skip
            reader.ReadInt32(); // skip
            frame.dataSize         = reader.ReadInt32();
            frame.dataOffset       = (int)stream.Position;
            dir.frames[frameIndex] = frame;

            maxWidth  = Mathf.Max(maxWidth, frame.width);
            maxHeight = Mathf.Max(maxHeight, frame.height);
        }

        TexturePacker packer;
        int           padding = framesPerDirection > 1 ? 2 : 0;

        if (textureSize == -1)
        {
            int textureWidth  = Mathf.NextPowerOfTwo((maxWidth + padding) * framesPerDirection);
            int textureHeight = Mathf.NextPowerOfTwo(maxHeight + padding);
            textureWidth = Mathf.Min(1024, textureWidth);
            packer       = new TexturePacker(textureWidth, textureHeight, padding);
        }
        else
        {
            packer = new TexturePacker(textureSize, textureSize, padding);
        }

        DrawFrames(dir, packer);

        return(dir);
    }
示例#29
0
        public void SetType(string type, Ship source)
        {
            ProjectileType = type;

            var data = EntityData.ProjectileTypes[ProjectileType];

            DeathType = data.DeathType;
            MoveSpeed = data.MoveSpeed;
            TurnSpeed = data.TurnSpeed;
            Lifetime  = data.Lifetime;
            Colour    = source.IsPlayerShip ? data.Colour : data.EnemyColour;
            Sprite    = TexturePacker.GetSprite("ParticlesAtlas", data.Sprite);
            Scale     = data.Scale;
        }
        private void Dispose(bool manual)
        {
            if (!disposed)
            {
                pack = null;
                if (manual)
                {
                    GL.DeleteTextures(1, ref texture);
                    font.Dispose();
                    gfx.Dispose();
                }

                disposed = true;
            }
        }
	public override void OnInspectorGUI ()
	{
        SuperLevelOptimizer SLO = (SuperLevelOptimizer)target;

		EditorGUILayout.HelpBox("SuperLevelOptimizer only works with static objects."
		                        ,UnityEditor.MessageType.None);

        SLO.GroupingWithoutCombine = GUILayout.Toggle(SLO.GroupingWithoutCombine, "GroupingWithoutCombine");
        SLO.SuperOptimization = GUILayout.Toggle(SLO.SuperOptimization, "SuperOptimization");
        SLO.combineState = (SuperLevelOptimizer.CombineState)EditorGUILayout.EnumPopup("CombineState :", SLO.combineState);

        if (SLO.combineState == SuperLevelOptimizer.CombineState.CombineToPrefab)
        {
            SLO.folderPatch = EditorGUILayout.TextField("Folder patch", SLO.folderPatch);
        }

        teb.combineState = (MaterialStructurizer.CombineState)SLO.combineState;
        teb.folderPatch = SLO.folderPatch;
        teb.GroupingWithoutCombine = SLO.GroupingWithoutCombine;

		if(GUILayout.Button("Create atlases"))
		{
			TexturePacker tp = new TexturePacker();
            tp.superOptimization = SLO.SuperOptimization;
			tp.StartPacking();
		}


		if( GUILayout.Button("Combine Meshes") )
		{
            teb.gameObject = SLO.gameObject;
			teb.Remove();
			teb.FindRenderers();
            teb.CreateObjects();
		}

		if( GUILayout.Button("Destroy sources") )
		{
			teb.DestroyChildren();
		}
	}
示例#32
0
        private void Dispose(bool manual)
        {
            if (!disposed)
            {
                pack = null;
                if (manual)
                {
                    GL.DeleteTextures(1, ref texture);
                    font.Dispose();
                    gfx.Dispose();
                }

                disposed = true;
            }
        }
示例#33
0
 public ItemPackingStep(PackingProcess proc, int start, int total)
     : base(proc, start, total)
 {
     TexturePacker = new TexturePacker(this, "items");
 }
示例#34
0
 public TilePackingStep(PackingProcess proc, int start, int total)
     : base(proc, start, total)
 {
     TexturePacker = new TexturePacker(this, "tiles");
 }
示例#35
0
        /// <summary>
        /// Calculates the optimal size for the font texture and TexturePacker, and creates both.
        /// </summary>
        private void PrepareTexturePacker()
        {
            // Calculate the size of the texture packer. We want a power-of-two size
            // that is less than 1024 (supported in Geforce256-era cards), but large
            // enough to hold at least 256 (16*16) font glyphs.
            // TODO: Find the actual card limits, maybe?
            int size = (int)(font.Size * 16);
            size = (int)System.Math.Pow(2.0, System.Math.Ceiling(System.Math.Log((double)size, 2.0)));
            if (size > 1024)
                size = 1024;

            texture_width = size;
            texture_height = size;
            pack = new TexturePacker<Glyph>(texture_width, texture_height);

            GL.GenTextures(1, out texture);
            GL.BindTexture(TextureTarget.Texture2d, texture);
            GL.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureMinFilter, (int)All.Linear);
            GL.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureMagFilter, (int)All.Linear);

            GL.TexImage2D(TextureTarget.Texture2d, 0, PixelInternalFormat.Alpha, texture_width, texture_height, 0,
                OpenTK.OpenGL.Enums.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);
        }