/// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <param name="pobTexture"></param>
        /// <param name="framePrefix"></param>
        /// <returns>The framePrefix parameter</returns>
        public string AddSpriteFramesWithFile(string pszPlist, CCTexture2D pobTexture, string framePrefix)
        {
            //string pszPath = CCFileUtils.fullPathFromRelativePath(pszPlist);
            //Dictionary<string, Object> dict = CCFileUtils.dictionaryWithContentsOfFile(pszPath);
            PlistDocument document = null;

            try
            {
                document = CCApplication.SharedApplication.Content.Load <PlistDocument>(pszPlist);
            }
            catch (System.Exception)
            {
                string xml = CCContent.LoadContentFile(pszPlist);
                if (xml != null)
                {
                    document = new PlistDocument(xml);
                }
            }
            if (document == null)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from " + pszPlist));
            }

            PlistDictionary dict = document.Root.AsDictionary;

            AddSpriteFramesWithDictionary(dict, pobTexture, framePrefix);
            return(framePrefix);
        }
예제 #2
0
 public bool InitWithSpriteFrame(CCSpriteFrame spriteFrame, float delayUnits, PlistDictionary userInfo)
 {
     m_pSpriteFrame = spriteFrame;
     m_fDelayUnits  = delayUnits;
     m_pUserInfo    = userInfo;
     return(true);
 }
        public void AddAnimationsWithFile(string plist)
        {
            Debug.Assert(!string.IsNullOrEmpty(plist), "Invalid texture file name");

            string path = CCFileUtils.FullPathFromRelativePath(plist);

            PlistDocument document = null;

            try
            {
                document = CCApplication.SharedApplication.Content.Load <PlistDocument>(path);
            }
            catch (System.Exception)
            {
                string xml = CCContent.LoadContentFile(path);
                if (xml != null)
                {
                    document = new PlistDocument(xml);
                }
            }
            if (document == null)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from " + path));
            }

            PlistDictionary dict = document.Root.AsDictionary;

            Debug.Assert(dict != null, "CCAnimationCache: File could not be found");

            AddAnimationsWithDictionary(dict);
        }
        public void RemoveSpriteFramesFromFile(string plist)
        {
            //string path = CCFileUtils.fullPathFromRelativePath(plist);
            //Dictionary<string, object> dict = CCFileUtils.dictionaryWithContentsOfFile(path);
            PlistDocument document = null;

            try
            {
                document = CCApplication.SharedApplication.Content.Load <PlistDocument>(plist);
            }
            catch (System.Exception)
            {
                string xml = CCContent.LoadContentFile(plist);
                if (xml != null)
                {
                    document = new PlistDocument(xml);
                }
            }
            if (document == null)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from " + plist));
            }

            PlistDictionary dict = document.Root.AsDictionary;

            RemoveSpriteFramesFromDictionary(dict);
        }
예제 #5
0
        private PlistDictionary LoadDictionaryContents(XmlReader reader, PlistDictionary dict)
        {
            Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.LocalName == "key");
            while (!reader.EOF && reader.NodeType == XmlNodeType.Element)
            {
                //string key = reader.ReadElementString ();
                string key = reader.ReadElementContentAsString();
                while (reader.NodeType != XmlNodeType.Element && reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        throw new Exception(String.Format("No value found for key {0}", key));
                    }
                }
                PlistObjectBase result = LoadFromNode(reader);
                if (result != null)
                {
                    dict.Add(key, result);
                }

                // when there is no whitespace between nodes, we might already be at
                // the next key element, so reading to next sibling would jump over
                // the next (current) key element
                if (!"key".Equals(reader.Name))
                {
                    reader.ReadToNextSibling("key");
                }
            }
            return(dict);
        }
        private void ParseVersion1(PlistDictionary animations)
        {
            CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;

            foreach (var pElement in animations)
            {
                PlistDictionary animationDict = pElement.Value.AsDictionary;

                PlistArray frameNames = animationDict["frames"].AsArray;
                float      delay      = animationDict["delay"].AsFloat;
                //CCAnimation* animation = NULL;

                if (frameNames == null)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: Animation '{0}' found in dictionary without any frames - cannot add to animation cache.",
                        pElement.Key);
                    continue;
                }

                var frames = new List <CCAnimationFrame>(frameNames.Count);

                foreach (PlistObjectBase pObj in frameNames)
                {
                    string        frameName   = pObj.AsString;
                    CCSpriteFrame spriteFrame = frameCache.SpriteFrameByName(frameName);

                    if (spriteFrame == null)
                    {
                        CCLog.Log(
                            "cocos2d: CCAnimationCache: Animation '{0}' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.",
                            pElement.Key, frameName);
                        continue;
                    }

                    var animFrame = new CCAnimationFrame();
                    animFrame.InitWithSpriteFrame(spriteFrame, 1, null);
                    frames.Add(animFrame);
                }

                if (frames.Count == 0)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: None of the frames for animation '{0}' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.",
                        pElement.Key);
                    continue;
                }
                else if (frames.Count != frameNames.Count)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '{0}' may be missing.",
                        pElement.Key);
                }

                CCAnimation animation = new CCAnimation(frames, delay, 1);

                SharedAnimationCache.AddAnimation(animation, pElement.Key);
            }
        }
예제 #7
0
        public void RemoveSpriteFramesFromFile(string plist)
        {
            //string path = CCFileUtils.fullPathFromRelativePath(plist);
            //Dictionary<string, object> dict = CCFileUtils.dictionaryWithContentsOfFile(path);
            PlistDictionary dict = CCApplication.SharedApplication.Content.Load <PlistDocument>(plist).Root.AsDictionary;

            RemoveSpriteFramesFromDictionary(dict);
        }
예제 #8
0
        public void RemoveSpriteFramesFromFile(string plist)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(plist);

            PlistDictionary dict = document.Root.AsDictionary;

            RemoveSpriteFramesFromDictionary(dict);
        }
예제 #9
0
        public void AddSpriteFramesWithFile(string pszPlist, CCTexture2D pobTexture)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(pszPlist);

            PlistDictionary dict = document.Root.AsDictionary;

            AddSpriteFramesWithDictionary(dict, pobTexture);
        }
예제 #10
0
        public void InitWithFile(string fileName, CCTexture2D texture)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(fileName);

            PlistDictionary dict = document.Root.AsDictionary;

            InitWithDictionary(dict, texture);
        }
        private void ParseVersion2(PlistDictionary animations)
        {
            CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;

            foreach (var pElement in animations)
            {
                string          name          = pElement.Key;
                PlistDictionary animationDict = pElement.Value.AsDictionary;

                int  loops = animationDict["loops"].AsInt;
                bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].AsBool;

                PlistArray frameArray = animationDict["frames"].AsArray;

                if (frameArray == null)
                {
                    CCLog.Log(
                        "cocos2d: CCAnimationCache: Animation '{0}' found in dictionary without any frames - cannot add to animation cache.",
                        name);
                    continue;
                }

                // Array of AnimationFrames
                var array = new List <CCAnimationFrame>(frameArray.Count);

                foreach (PlistObjectBase pObj in frameArray)
                {
                    PlistDictionary entry = pObj.AsDictionary;

                    string        spriteFrameName = entry["spriteframe"].AsString;
                    CCSpriteFrame spriteFrame     = frameCache.SpriteFrameByName(spriteFrameName);

                    if (spriteFrame == null)
                    {
                        CCLog.Log(
                            "cocos2d: CCAnimationCache: Animation '{0}' refers to frame '{1}' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.",
                            name, spriteFrameName);

                        continue;
                    }

                    float           delayUnits = entry["delayUnits"].AsFloat;
                    PlistDictionary userInfo   = entry["notification"].AsDictionary;

                    var animFrame = new CCAnimationFrame();
                    animFrame.InitWithSpriteFrame(spriteFrame, delayUnits, userInfo);

                    array.Add(animFrame);
                }

                float delayPerUnit = animationDict["delayPerUnit"].AsFloat;
                var   animation    = new CCAnimation(array, delayPerUnit, (uint)loops);

                animation.RestoreOriginalFrame = restoreOriginalFrame;

                SharedAnimationCache.AddAnimation(animation, name);
            }
        }
예제 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <param name="pobTexture"></param>
        /// <param name="framePrefix"></param>
        /// <returns>The framePrefix parameter</returns>
        public string AddSpriteFramesWithFile(string pszPlist, CCTexture2D pobTexture, string framePrefix)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(pszPlist);

            PlistDictionary dict = document.Root.AsDictionary;

            AddSpriteFramesWithDictionary(dict, pobTexture, framePrefix);
            return(framePrefix);
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <param name="pobTexture"></param>
        /// <param name="framePrefix"></param>
        /// <returns>The framePrefix parameter</returns>
        public string AddSpriteFramesWithFile(string pszPlist, CCTexture2D pobTexture, string framePrefix)
        {
            //string pszPath = CCFileUtils.fullPathFromRelativePath(pszPlist);
            //Dictionary<string, Object> dict = CCFileUtils.dictionaryWithContentsOfFile(pszPath);
            PlistDictionary dict = CCApplication.SharedApplication.Content.Load <PlistDocument>(pszPlist).Root.AsDictionary;

            AddSpriteFramesWithDictionary(dict, pobTexture, framePrefix);
            return(framePrefix);
        }
예제 #14
0
        public void AddAnimationsWithFile(string plist)
        {
            Debug.Assert(!string.IsNullOrEmpty(plist), "Invalid texture file name");

            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(plist);

            PlistDictionary dict = document.Root.AsDictionary;

            Debug.Assert(dict != null, "CCAnimationCache: File could not be found");

            AddAnimationsWithDictionary(dict);
        }
예제 #15
0
        public void AddAnimationsWithFile(string plist)
        {
            Debug.Assert(!string.IsNullOrEmpty(plist), "Invalid texture file name");

            string path = CCFileUtils.FullPathFromRelativePath(plist);

            var             document = CCApplication.SharedApplication.Content.Load <PlistDocument>(path);
            PlistDictionary dict     = document.Root.AsDictionary;

            Debug.Assert(dict != null, "CCAnimationCache: File could not be found");

            AddAnimationsWithDictionary(dict);
        }
예제 #16
0
            protected PlistObjectBase ReadValue(ContentReader input)
            {
                var type = (ValueType)input.ReadByte();

                switch (type)
                {
                case ValueType.Array:
                    var count = input.ReadInt32();
                    var array = new PlistArray(count);
                    for (int i = 0; i < count; i++)
                    {
                        array.Add(ReadValue(input));
                    }
                    return(array);

                case ValueType.Bool:
                    return(new PlistBoolean(input.ReadBoolean()));

                case ValueType.Data:
                    count = input.ReadInt32();
                    return(new PlistData(input.ReadBytes(count)));

                case ValueType.Date:
                    return(new PlistDate(input.ReadObject <DateTime>()));

                case ValueType.Dictionary:
                    count = input.ReadInt32();
                    var dict = new PlistDictionary();
                    for (int i = 0; i < count; i++)
                    {
                        string key = _stringPool[input.ReadInt32()];
                        dict.Add(key, ReadValue(input));
                    }
                    return(dict);

                case ValueType.Integer:
                    return(new PlistInteger(input.ReadInt32()));

                case ValueType.Null:
                    return(new PlistNull());

                case ValueType.Real:
                    return(new PlistReal(input.ReadSingle()));

                case ValueType.String:
                    return(new PlistString(_stringPool[input.ReadInt32()]));

                default:
                    throw new InvalidOperationException();
                }
            }
예제 #17
0
        public void InitWithDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            _spriteFrames.Clear();
            _spriteFramesAliases.Clear();

            if (plistType == PlistType.SpriteKit)
            {
                LoadAppleDictionary(dict, texture);
            }
            else
            {
                LoadCocos2DDictionary(dict, texture);
            }
        }
예제 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <returns>The scope parameter derived from the pszPlist parameter.</returns>
        public string AddSpriteFramesWithFile(string pszPlist)
        {
            string pszPath = CCFileUtils.FullPathFromRelativePath(pszPlist);
            //Dictionary<string, Object> dict = CCFileUtils.dictionaryWithContentsOfFile(pszPath);
            PlistDictionary dict = CCApplication.SharedApplication.Content.Load <PlistDocument>(pszPlist).Root.AsDictionary;

            string          texturePath  = "";
            PlistDictionary metadataDict = dict.ContainsKey("metadata") ? dict["metadata"].AsDictionary : null;

            string framePrefix = string.Empty;

            if (metadataDict != null)
            {
                // try to read  texture file name from meta data
                if (metadataDict.ContainsKey("textureFileName"))
                {
                    texturePath = metadataDict["textureFileName"].AsString;
                    framePrefix = ExtractPrefix(texturePath);
                }
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // build texture path relative to plist file
                texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, pszPath);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = pszPath;

                // remove .xxx
                texturePath = CCFileUtils.RemoveExtension(texturePath);

                CCLog.Log("cocos2d: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
            }

            CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);

            if (pTexture != null)
            {
                AddSpriteFramesWithDictionary(dict, pTexture, framePrefix);
            }
            else
            {
                CCLog.Log("cocos2d: CCSpriteFrameCache: Couldn't load texture");
            }
            return(framePrefix);
        }
예제 #19
0
        public void AddSpriteFramesWithFile(string pszPlist)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(pszPlist);

            PlistDictionary dict         = document.Root.AsDictionary;
            string          texturePath  = "";
            PlistDictionary metadataDict = dict.ContainsKey("metadata") ? dict["metadata"].AsDictionary : null;

            if (metadataDict != null)
            {
                // try to read  texture file name from meta data
                if (metadataDict.ContainsKey("textureFileName"))
                {
                    texturePath = metadataDict["textureFileName"].AsString;
                }
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // build texture path relative to plist file
                texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, pszPlist);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = pszPlist;

                // remove .xxx
                texturePath = CCFileUtils.RemoveExtension(texturePath);

                // append .png
                texturePath = texturePath + ".png";

                CCLog.Log("cocos2d: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
            }

            CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);

            if (pTexture != null)
            {
                AddSpriteFramesWithDictionary(dict, pTexture);
            }
            else
            {
                CCLog.Log("cocos2d: CCSpriteFrameCache: Couldn't load texture");
            }
        }
예제 #20
0
        public void InitWithStream(Stream stream, CCTexture2D texture)
        {
            var document = new PlistDocument();

            try
            {
                document.LoadFromXmlFile(stream);
            }
            catch (Exception)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the sprite sheet definition file from stream"));
            }

            PlistDictionary dict = document.Root.AsDictionary;

            InitWithDictionary(dict, texture);
        }
예제 #21
0
        public void AddSpriteFramesWithFile(Stream plist, CCTexture2D pobTexture)
        {
            PlistDocument document = new PlistDocument();

            try
            {
                document.LoadFromXmlFile(plist);
            }
            catch (Exception)
            {
                throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from stream"));
            }

            PlistDictionary dict = document.Root.AsDictionary;

            AddSpriteFramesWithDictionary(dict, pobTexture);
        }
        public void RemoveSpriteFramesFromDictionary(PlistDictionary dictionary)
        {
            PlistDictionary framesDict   = dictionary["frames"].AsDictionary;
            var             keysToRemove = new List <string>();

            foreach (var pair in framesDict)
            {
                if (m_pSpriteFrames.ContainsKey(pair.Key))
                {
                    keysToRemove.Remove(pair.Key);
                }
            }

            foreach (string key in keysToRemove)
            {
                m_pSpriteFrames.Remove(key);
            }
        }
        public void AddAnimationsWithDictionary(PlistDictionary dictionary)
        {
            PlistDictionary animations = dictionary["animations"].AsDictionary;

            if (animations == null)
            {
                CCLog.Log("cocos2d: CCAnimationCache: No animations were found in provided dictionary.");
                return;
            }

            PlistDictionary properties = dictionary["properties"].AsDictionary;

            if (properties != null)
            {
                int        version      = properties["format"].AsInt;
                PlistArray spritesheets = properties["spritesheets"].AsArray;

                foreach (PlistObjectBase pObj in spritesheets)
                {
                    string name = pObj.AsString;
                    CCSpriteFrameCache.SharedSpriteFrameCache.AddSpriteFramesWithFile(name);
                }

                switch (version)
                {
                case 1:
                    ParseVersion1(animations);
                    break;

                case 2:
                    ParseVersion2(animations);
                    break;

                default:
                    Debug.Assert(false, "Invalid animation format");
                    break;
                }
            }
        }
예제 #24
0
        private PlistDictionary parseBinaryDictionary(int objRef)
        {
            var buffer = new PlistDictionary(true);

            List <int> refs     = new List <int>();
            int        refCount = 0;

            byte dictByte = objectTable[offsetTable[objRef]];

            int refStartPosition;

            refCount = getCount(offsetTable[objRef], out refStartPosition);


            if (refCount < 15)
            {
                refStartPosition = offsetTable[objRef] + 1;
            }
            else
            {
                refStartPosition = offsetTable[objRef] + 2 + RegulateNullBytes(BitConverter.GetBytes(refCount), 1).Length;
            }

            for (int i = refStartPosition; i < refStartPosition + refCount * 2 * objRefSize; i += objRefSize)
            {
                byte[] refBuffer = objectTable.GetRange(i, objRefSize).ToArray();
                Array.Reverse(refBuffer);
                refs.Add(BitConverter.ToInt32(RegulateNullBytes(refBuffer, 4), 0));
            }

            for (int i = 0; i < refCount; i++)
            {
                var key = ((PlistString)parseBinary(refs [i])).AsString;
                var val = parseBinary(refs [i + refCount]);
                buffer.Add(key, val);
            }

            return(buffer);
        }
예제 #25
0
        private PlistType GetPlistType(PlistDictionary dict)
        {
            var isSpriteKit = dict.ContainsKey("format") ? dict ["format"].AsString == "APPL" : false;

            return(isSpriteKit ? PlistType.SpriteKit : PlistType.Cocos2D);
        }
예제 #26
0
 public CCSpriteSheet(PlistDictionary dictionary, CCTexture2D texture)
 {
     InitWithDictionary(dictionary, texture);
 }
예제 #27
0
        private void LoadCocos2DDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            PlistDictionary metadataDict = null;

            if (dict.ContainsKey("metadata"))
            {
                metadataDict = dict["metadata"].AsDictionary;
            }

            PlistDictionary framesDict = null;

            if (dict.ContainsKey("frames"))
            {
                framesDict = dict["frames"].AsDictionary;
            }

            // get the format
            int format = 0;

            if (metadataDict != null)
            {
                format = metadataDict["format"].AsInt;
            }

            // check the format
            if (format < 0 || format > 3)
            {
                throw (new NotSupportedException("PList format " + format + " is not supported."));
            }

            foreach (var pair in framesDict)
            {
                PlistDictionary frameDict   = pair.Value.AsDictionary;
                CCSpriteFrame   spriteFrame = null;

                if (format == 0)
                {
                    float x = 0f, y = 0f, w = 0f, h = 0f;
                    x = frameDict["x"].AsFloat;
                    y = frameDict["y"].AsFloat;
                    w = frameDict["width"].AsFloat;
                    h = frameDict["height"].AsFloat;
                    float ox = 0f, oy = 0f;
                    ox = frameDict["offsetX"].AsFloat;
                    oy = frameDict["offsetY"].AsFloat;
                    int ow = 0, oh = 0;
                    ow = frameDict["originalWidth"].AsInt;
                    oh = frameDict["originalHeight"].AsInt;
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCLog.Log(
                            "cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
                    }
                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        texture,
                        new CCRect(x, y, w, h),
                        false,
                        new CCPoint(ox, oy),
                        new CCSize(ow, oh)
                        );
                }
                else if (format == 1 || format == 2)
                {
                    var  frame   = CCRect.Parse(frameDict["frame"].AsString);
                    bool rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        if (frameDict.ContainsKey("rotated"))
                        {
                            rotated = frameDict["rotated"].AsBool;
                        }
                    }

                    var offset     = CCPoint.Parse(frameDict["offset"].AsString);
                    var sourceSize = CCSize.Parse(frameDict["sourceSize"].AsString);

                    // create frame
                    spriteFrame = new CCSpriteFrame(texture, frame, rotated, offset, sourceSize);
                }
                else if (format == 3)
                {
                    var spriteSize       = CCSize.Parse(frameDict["spriteSize"].AsString);
                    var spriteOffset     = CCPoint.Parse(frameDict["spriteOffset"].AsString);
                    var spriteSourceSize = CCSize.Parse(frameDict["spriteSourceSize"].AsString);
                    var textureRect      = CCRect.Parse(frameDict["textureRect"].AsString);

                    bool textureRotated = false;

                    if (frameDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = frameDict["textureRotated"].AsBool;
                    }

                    // get aliases
                    var aliases = frameDict["aliases"].AsArray;

                    for (int i = 0; i < aliases.Count; i++)
                    {
                        string oneAlias = aliases[i].AsString;

                        if (_spriteFramesAliases.ContainsKey(oneAlias))
                        {
                            if (_spriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }

                        if (!_spriteFramesAliases.ContainsKey(oneAlias))
                        {
                            _spriteFramesAliases.Add(oneAlias, pair.Key);
                        }
                    }

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        texture,
                        new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
                        textureRotated,
                        spriteOffset,
                        spriteSourceSize
                        );
                }

                _spriteFrames[pair.Key] = spriteFrame;
            }
            AutoCreateAliasList();
        }
예제 #28
0
        private void LoadAppleDictionary(PlistDictionary dict, CCTexture2D texture)
        {
            var version = dict.ContainsKey("version") ? dict ["version"].AsInt : 0;

            if (version != 1)
            {
                throw (new NotSupportedException("Binary PList version " + version + " is not supported."));
            }


            var images = dict.ContainsKey("images") ? dict ["images"].AsArray : null;

            foreach (var imageEntry in images)
            {
                // we only support one image for now
                var imageDict = imageEntry.AsDictionary;

                var path = imageDict ["path"].AsString;

                path = Path.Combine(plistFilePath, CCFileUtils.RemoveExtension(path));

                if (!CCTextureCache.SharedTextureCache.Contains(path))
                {
                    texture = CCTextureCache.SharedTextureCache.AddImage(path);
                }
                else
                {
                    texture = CCTextureCache.SharedTextureCache[path];
                }



                // size not used right now
                //var size = CCSize.Parse(imageDict ["size"].AsString);

                var subImages = imageDict ["subimages"].AsArray;

                foreach (var subImage in subImages)
                {
                    CCSpriteFrame spriteFrame = null;

                    var subImageDict  = subImage.AsDictionary;
                    var name          = subImageDict ["name"].AsString;
                    var alias         = subImageDict ["alias"].AsString;
                    var isFullyOpaque = true;

                    if (subImageDict.ContainsKey("isFullyOpaque"))
                    {
                        isFullyOpaque = subImageDict ["isFullyOpaque"].AsBool;
                    }

                    var textureRect  = CCRect.Parse(subImageDict ["textureRect"].AsString);
                    var spriteOffset = CCPoint.Parse(subImageDict ["spriteOffset"].AsString);

                    // We are going to override the sprite offset for now to be 0,0
                    // It seems the offset is calculated off of the original size but if
                    // we pass this offset it throws our center position calculations off.
                    spriteOffset = CCPoint.Zero;

                    var textureRotated = false;
                    if (subImageDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = subImageDict ["textureRotated"].AsBool;
                    }
                    var spriteSourceSize = CCSize.Parse(subImageDict ["spriteSourceSize"].AsString);
                    var frameRect        = textureRect;
                    if (textureRotated)
                    {
                        frameRect = new CCRect(textureRect.Origin.X, textureRect.Origin.Y, textureRect.Size.Height, textureRect.Size.Width);
                    }

#if DEBUG
                    CCLog.Log("texture {0} rect {1} rotated {2} offset {3}, sourcesize {4}", name, textureRect, textureRotated, spriteOffset, spriteSourceSize);
#endif

                    // create frame
                    spriteFrame = new CCSpriteFrame(
                        texture,
                        frameRect,
                        textureRotated,
                        spriteOffset,
                        spriteSourceSize
                        );


                    _spriteFrames [name] = spriteFrame;
                }
            }
            AutoCreateAliasList();
        }
예제 #29
0
        public bool InitWithDictionary(PlistDictionary dictionary)
        {
            bool bRet = false;

            do
            {
                int maxParticles = dictionary["maxParticles"].AsInt;
                // self, not super
                if (InitWithTotalParticles(maxParticles))
                {
                    // angle
                    m_fAngle    = dictionary["angle"].AsFloat;
                    m_fAngleVar = dictionary["angleVariance"].AsFloat;

                    // duration
                    m_fDuration = dictionary["duration"].AsFloat;

                    // blend function
                    m_tBlendFunc.Source      = dictionary["blendFuncSource"].AsInt;
                    m_tBlendFunc.Destination = dictionary["blendFuncDestination"].AsInt;

                    // color
                    m_tStartColor.R = dictionary["startColorRed"].AsFloat;
                    m_tStartColor.G = dictionary["startColorGreen"].AsFloat;
                    m_tStartColor.B = dictionary["startColorBlue"].AsFloat;
                    m_tStartColor.A = dictionary["startColorAlpha"].AsFloat;

                    m_tStartColorVar.R = dictionary["startColorVarianceRed"].AsFloat;
                    m_tStartColorVar.G = dictionary["startColorVarianceGreen"].AsFloat;
                    m_tStartColorVar.B = dictionary["startColorVarianceBlue"].AsFloat;
                    m_tStartColorVar.A = dictionary["startColorVarianceAlpha"].AsFloat;

                    m_tEndColor.R = dictionary["finishColorRed"].AsFloat;
                    m_tEndColor.G = dictionary["finishColorGreen"].AsFloat;
                    m_tEndColor.B = dictionary["finishColorBlue"].AsFloat;
                    m_tEndColor.A = dictionary["finishColorAlpha"].AsFloat;

                    m_tEndColorVar.R = dictionary["finishColorVarianceRed"].AsFloat;
                    m_tEndColorVar.G = dictionary["finishColorVarianceGreen"].AsFloat;
                    m_tEndColorVar.B = dictionary["finishColorVarianceBlue"].AsFloat;
                    m_tEndColorVar.A = dictionary["finishColorVarianceAlpha"].AsFloat;

                    // particle size
                    m_fStartSize    = dictionary["startParticleSize"].AsFloat;
                    m_fStartSizeVar = dictionary["startParticleSizeVariance"].AsFloat;
                    m_fEndSize      = dictionary["finishParticleSize"].AsFloat;
                    m_fEndSizeVar   = dictionary["finishParticleSizeVariance"].AsFloat;

                    // position
                    float x = dictionary["sourcePositionx"].AsFloat;
                    float y = dictionary["sourcePositiony"].AsFloat;
                    Position    = new CCPoint(x, y);
                    m_tPosVar.X = dictionary["sourcePositionVariancex"].AsFloat;
                    m_tPosVar.Y = dictionary["sourcePositionVariancey"].AsFloat;

                    // Spinning
                    m_fStartSpin    = dictionary["rotationStart"].AsFloat;
                    m_fStartSpinVar = dictionary["rotationStartVariance"].AsFloat;
                    m_fEndSpin      = dictionary["rotationEnd"].AsFloat;
                    m_fEndSpinVar   = dictionary["rotationEndVariance"].AsFloat;

                    m_nEmitterMode = (CCEmitterMode)dictionary["emitterType"].AsInt;

                    // Mode A: Gravity + tangential accel + radial accel
                    if (m_nEmitterMode == CCEmitterMode.kCCParticleModeGravity)
                    {
                        // gravity
                        modeA.gravity.X = dictionary["gravityx"].AsFloat;
                        modeA.gravity.Y = dictionary["gravityy"].AsFloat;

                        // speed
                        modeA.speed    = dictionary["speed"].AsFloat;
                        modeA.speedVar = dictionary["speedVariance"].AsFloat;

                        // radial acceleration
                        modeA.radialAccel    = dictionary["radialAcceleration"].AsFloat;
                        modeA.radialAccelVar = dictionary["radialAccelVariance"].AsFloat;

                        // tangential acceleration
                        modeA.tangentialAccel    = dictionary["tangentialAcceleration"].AsFloat;
                        modeA.tangentialAccelVar = dictionary["tangentialAccelVariance"].AsFloat;
                    }

                    // or Mode B: radius movement
                    else if (m_nEmitterMode == CCEmitterMode.kCCParticleModeRadius)
                    {
                        modeB.startRadius        = dictionary["maxRadius"].AsFloat;
                        modeB.startRadiusVar     = dictionary["maxRadiusVariance"].AsFloat;
                        modeB.endRadius          = dictionary["minRadius"].AsFloat;
                        modeB.endRadiusVar       = 0.0f;
                        modeB.rotatePerSecond    = dictionary["rotatePerSecond"].AsFloat;
                        modeB.rotatePerSecondVar = dictionary["rotatePerSecondVariance"].AsFloat;
                    }
                    else
                    {
                        Debug.Assert(false, "Invalid emitterType in config file");
                        break;
                    }

                    // life span
                    m_fLife    = dictionary["particleLifespan"].AsFloat;
                    m_fLifeVar = dictionary["particleLifespanVariance"].AsFloat;

                    // emission Rate
                    m_fEmissionRate = m_uTotalParticles / m_fLife;

                    //don't get the internal texture if a batchNode is used
                    if (m_pBatchNode == null)
                    {
                        // Set a compatible default for the alpha transfer
                        m_bOpacityModifyRGB = false;

                        // texture
                        // Try to get the texture from the cache
                        string textureName = dictionary["textureFileName"].AsString;
                        string fullpath    = CCFileUtils.FullPathFromRelativeFile(textureName, m_sPlistFile);

                        CCTexture2D tex = null;

                        if (!string.IsNullOrEmpty(textureName))
                        {
                            // set not pop-up message box when load image failed
                            bool bNotify = CCFileUtils.IsPopupNotify;
                            CCFileUtils.IsPopupNotify = false;
                            try
                            {
                                tex = CCTextureCache.SharedTextureCache.AddImage(fullpath);
                            }
                            catch (Exception)
                            {
                                tex = null;
                            }

                            // reset the value of UIImage notify
                            CCFileUtils.IsPopupNotify = bNotify;
                        }

                        if (tex != null)
                        {
                            Texture = tex;
                        }
                        else
                        {
                            string textureData = dictionary["textureImageData"].AsString;
                            Debug.Assert(textureData != null && textureData.Length > 0, string.Format("CCParticleSystem: textureData does not exist : {0}", textureName));

                            int dataLen = textureData.Length;
                            if (dataLen != 0)
                            {
                                var dataBytes = Convert.FromBase64String(textureData);
                                Debug.Assert(dataBytes != null, string.Format("CCParticleSystem: error decoding textureImageData : {0}", textureName));

                                var imageBytes = Inflate(dataBytes);
                                Debug.Assert(imageBytes != null, string.Format("CCParticleSystem: error init image with Data for texture : {0}", textureName));

                                using (var imageStream = new MemoryStream(imageBytes))
                                {
                                    try
                                    {
                                        Texture = CCTextureCache.SharedTextureCache.AddImage(imageStream, textureName);
                                    }
                                    catch (Exception ex)
                                    {
                                        CCLog.Log(ex.ToString());
                                        throw (new NotSupportedException("Embedded textureImageData is a format that this platform does not understand. Use PNG, GIF, or JPEG for your particle systems."));
                                    }
                                }
                            }
                        }
                        Debug.Assert(Texture != null, string.Format("CCParticleSystem: error loading the texture : {0}", textureName));
                    }
                    bRet = true;
                }
            } while (false);

            return(bRet);
        }
        public void AddSpriteFramesWithDictionary(PlistDictionary pobDictionary, CCTexture2D pobTexture, string framePrefix)
        {
            /*
             * Supported Zwoptex Formats:
             *
             * ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
             * ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
             * ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
             * ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
             */

            PlistDictionary metadataDict = null;

            if (pobDictionary.ContainsKey("metadata"))
            {
                metadataDict = pobDictionary["metadata"].AsDictionary;
            }

            PlistDictionary framesDict = null;

            if (pobDictionary.ContainsKey("frames"))
            {
                framesDict = pobDictionary["frames"].AsDictionary;
            }

            int format = 0;

            // get the format
            if (metadataDict != null)
            {
                format = metadataDict["format"].AsInt;
            }

            // check the format
            if (format < 0 || format > 3)
            {
                throw (new NotSupportedException("PList format " + format + " is not supported."));
            }

            foreach (var pair in framesDict)
            {
                PlistDictionary frameDict   = pair.Value.AsDictionary;
                CCSpriteFrame   spriteFrame = null;

                if (format == 0)
                {
                    float x = 0f, y = 0f, w = 0f, h = 0f;
                    x = frameDict["x"].AsFloat;
                    y = frameDict["y"].AsFloat;
                    w = frameDict["width"].AsFloat;
                    h = frameDict["height"].AsFloat;
                    float ox = 0f, oy = 0f;
                    ox = frameDict["offsetX"].AsFloat;
                    oy = frameDict["offsetY"].AsFloat;
                    int ow = 0, oh = 0;
                    ow = frameDict["originalWidth"].AsInt;
                    oh = frameDict["originalHeight"].AsInt;
                    // check ow/oh
                    if (ow == 0 || oh == 0)
                    {
                        CCLog.Log(
                            "cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
                    }
                    // abs ow/oh
                    ow = Math.Abs(ow);
                    oh = Math.Abs(oh);
                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                    new CCRect(x, y, w, h),
                                                    false,
                                                    new CCPoint(ox, oy),
                                                    new CCSize(ow, oh)
                                                    );
                }
                else if (format == 1 || format == 2)
                {
                    CCRect frame   = CCRect.Parse(frameDict["frame"].AsString);
                    bool   rotated = false;

                    // rotation
                    if (format == 2)
                    {
                        if (frameDict.ContainsKey("rotated"))
                        {
                            rotated = frameDict["rotated"].AsBool;
                        }
                    }

                    CCPoint offset     = CCPoint.Parse(frameDict["offset"].AsString);
                    CCSize  sourceSize = CCSize.Parse(frameDict["sourceSize"].AsString);

                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                    frame,
                                                    rotated,
                                                    offset,
                                                    sourceSize
                                                    );
                }
                else if (format == 3)
                {
                    // get values
                    CCSize  spriteSize       = CCSize.Parse(frameDict["spriteSize"].AsString);
                    CCPoint spriteOffset     = CCPoint.Parse(frameDict["spriteOffset"].AsString);
                    CCSize  spriteSourceSize = CCSize.Parse(frameDict["spriteSourceSize"].AsString);
                    CCRect  textureRect      = CCRect.Parse(frameDict["textureRect"].AsString);
                    bool    textureRotated   = false;
                    if (frameDict.ContainsKey("textureRotated"))
                    {
                        textureRotated = frameDict["textureRotated"].AsBool;
                    }

                    // get aliases
                    PlistArray aliases  = frameDict["aliases"].AsArray;
                    string     frameKey = pair.Key;

                    foreach (PlistObjectBase item2 in aliases)
                    {
                        string oneAlias = item2.AsString;
                        if (m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            if (m_pSpriteFramesAliases[oneAlias] != null)
                            {
                                CCLog.Log("cocos2d: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }
                        if (!m_pSpriteFramesAliases.Keys.Contains(oneAlias))
                        {
                            m_pSpriteFramesAliases.Add(oneAlias, frameKey);
                        }
                    }

                    // create frame
                    spriteFrame = new CCSpriteFrame(pobTexture,
                                                    new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
                                                    textureRotated,
                                                    spriteOffset,
                                                    spriteSourceSize);
                }

                // add sprite frame
                string key = framePrefix + pair.Key;
                if (!_AllowFrameOverwrite && m_pSpriteFrames.ContainsKey(key))
                {
                    CCLog.Log("Frame named " + key + " already exists in the animation cache. Not overwriting existing record.");
                }
                else if (_AllowFrameOverwrite || !m_pSpriteFrames.ContainsKey(key))
                {
                    m_pSpriteFrames[key] = spriteFrame;
                }
            }
        }