Example #1
0
        public bool InitWithString(string text, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, string fontName,
                                   float fontSize)
        {
            try
            {
                m_CallParams = new object[] { text, dimensions, hAlignment, vAlignment, fontName, fontSize };

                // CCLog.Log("InitWithString: text={0}", text);

                Debug.Assert(dimensions.Width >= 0 || dimensions.Height >= 0);

                if (string.IsNullOrEmpty(text))
                {
                    return(false);
                }

                SpriteFont font = m_spriteFont;

                if (font == null)
                {
                    font = CCSpriteFontCache.SharedInstance.GetFont(fontName, fontSize);
                    if (font == null)
                    {
                        CCLog.Log("Can't find {0}, use system default ({1})", fontName, CCDrawManager.DefaultFont);
                        font = CCSpriteFontCache.SharedInstance.GetFont(CCDrawManager.DefaultFont, fontSize);
                        if (font == null)
                        {
                            CCLog.Log("Failed to load default font. No font supported.");
                        }
                    }
                    // m_spriteFont = font;
                }

                if (font == null)
                {
                    return(false);
                }

                // m_spriteFont = font;

                if (dimensions.Equals(CCSize.Zero))
                {
                    Microsoft.Xna.Framework.Vector2 temp = font.MeasureString(text);
                    dimensions.Width  = temp.X;
                    dimensions.Height = temp.Y;
                }

                //float scale = 1.0f;//need refer fontSize;

                var      textList = new List <String>();
                var      nextText = new StringBuilder();
                string[] lineList = text.Split('\n');

                float spaceWidth = font.MeasureString(" ").X;

                for (int j = 0; j < lineList.Length; ++j)
                {
                    string[] wordList = lineList[j].Split(' ');

                    float lineWidth = 0;
                    bool  firstWord = true;
                    for (int i = 0; i < wordList.Length; ++i)
                    {
                        lineWidth += font.MeasureString(wordList[i]).X;

                        if (lineWidth > dimensions.Width)
                        {
                            lineWidth = 0;

                            if (nextText.Length > 0)
                            {
                                firstWord = true;
                                textList.Add(nextText.ToString());
#if XBOX || XBOX360
                                nextText.Length = 0;
#else
                                nextText.Clear();
#endif
                            }
                            else
                            {
                                firstWord = false;
                                textList.Add(wordList[i]);
                                continue;
                            }
                        }

                        if (!firstWord)
                        {
                            nextText.Append(' ');
                            lineWidth += spaceWidth;
                        }

                        nextText.Append(wordList[i]);
                        firstWord = false;
                    }

                    textList.Add(nextText.ToString());
#if XBOX || XBOX360
                    nextText.Length = 0;
#else
                    nextText.Clear();
#endif
                }

                if (dimensions.Height == 0)
                {
                    dimensions.Height = textList.Count * font.LineSpacing;
                }

                //*  for render to texture
                RenderTarget2D renderTarget = CCDrawManager.CreateRenderTarget((int)dimensions.Width, (int)dimensions.Height,
                                                                               RenderTargetUsage.PreserveContents);
                CCDrawManager.SetRenderTarget(renderTarget);

                CCDrawManager.Clear(Color.Transparent);

                SpriteBatch spriteBatch = CCDrawManager.spriteBatch;

                spriteBatch.Begin();

                int   textHeight = textList.Count * font.LineSpacing;
                float nextY      = 0;

                if (vAlignment == CCVerticalTextAlignment.CCVerticalTextAlignmentBottom)
                {
                    nextY = dimensions.Height - textHeight;
                }
                else if (vAlignment == CCVerticalTextAlignment.CCVerticalTextAlignmentCenter)
                {
                    nextY = (dimensions.Height - textHeight) / 2.0f;
                }

                for (int j = 0; j < textList.Count; ++j)
                {
                    string line = textList[j];

                    var position = new Microsoft.Xna.Framework.Vector2(0, nextY);

                    if (hAlignment == CCTextAlignment.CCTextAlignmentRight)
                    {
                        position.X = dimensions.Width - font.MeasureString(line).X;
                    }
                    else if (hAlignment == CCTextAlignment.CCTextAlignmentCenter)
                    {
                        position.X = (dimensions.Width - font.MeasureString(line).X) / 2.0f;
                    }

#if MONOMAC
                    // It seems that MonoGame has an initialization problem with MONOMAC
                    // what we are doing here is a HACK and no doubt about it.  We can take this
                    // work around out when the issue is addressed in MonoGame.
                    // The issue is that if we do not re-initialize the font for some reason it is
                    // not drawing the next label if it is the same font and size.
                    spriteBatch.DrawString(hackFont, " ", position, Color.White);
#endif
                    spriteBatch.DrawString(font, line, position, Color.White);
                    nextY += font.LineSpacing;
                }
                spriteBatch.End();

                CCDrawManager.graphicsDevice.RasterizerState   = RasterizerState.CullNone;
                CCDrawManager.graphicsDevice.DepthStencilState = DepthStencilState.Default;

                CCDrawManager.SetRenderTarget((RenderTarget2D)null);

                // to copy the rendered target data to a plain texture(to the memory)
                //            texture2D = DrawManager.CreateTexture2D(renderTarget.Width, renderTarget.Height);
                // This is the old 3.1 way of doing things. 4.0 does not need this and it causes compatibility problems.

                //            var colors1D = new Color[renderTarget.Width * renderTarget.Height];
                //            renderTarget.GetData(colors1D);
                //            texture2D.SetData(colors1D);
                return(InitWithTexture(renderTarget));
            }
            catch (Exception ex)
            {
                CCLog.Log(ex.ToString());
            }
            return(false);
        }
Example #2
0
        protected virtual bool InitWithString(string theString, string fntFile, CCSize dimentions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                                              CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert(m_pConfiguration == null, "re-init is no longer supported");
            Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null),
                         "Invalid params for CCLabelBMFont");

            if (!String.IsNullOrEmpty(fntFile))
            {
                CCBMFontConfiguration newConf = FNTConfigLoadFile(fntFile);
                if (newConf == null)
                {
                    CCLog.Log("CCLabelBMFont: Impossible to create font. Please check file: '{0}'", fntFile);
                    return(false);
                }

                m_pConfiguration = newConf;

                m_sFntFile = fntFile;

                if (texture == null)
                {
                    try
                    {
                        texture = CCTextureCache.SharedTextureCache.AddImage(m_pConfiguration.AtlasName);
                    }
                    catch (Exception)
                    {
                        // Try the 'images' ref location just in case.
                        try
                        {
                            texture =
                                CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images",
                                                                                                  m_pConfiguration
                                                                                                  .AtlasName));
                        }
                        catch (Exception)
                        {
                            // Lastly, try <font_path>/images/<font_name>
                            string dir     = System.IO.Path.GetDirectoryName(m_pConfiguration.AtlasName);
                            string fname   = System.IO.Path.GetFileName(m_pConfiguration.AtlasName);
                            string newName = System.IO.Path.Combine(System.IO.Path.Combine(dir, "images"), fname);
                            texture = CCTextureCache.SharedTextureCache.AddImage(newName);
                        }
                    }
                }
            }
            else
            {
                texture = new CCTexture2D();
            }

            if (String.IsNullOrEmpty(theString))
            {
                theString = String.Empty;
            }

            if (base.InitWithTexture(texture, theString.Length))
            {
                m_tDimensions = dimentions;

                m_pHAlignment = hAlignment;
                m_pVAlignment = vAlignment;

                m_cDisplayedOpacity      = m_cRealOpacity = 255;
                m_tDisplayedColor        = m_tRealColor = CCTypes.CCWhite;
                m_bCascadeOpacityEnabled = true;
                m_bCascadeColorEnabled   = true;

                m_obContentSize = CCSize.Zero;

                m_bIsOpacityModifyRGB = m_pobTextureAtlas.Texture.HasPremultipliedAlpha;
                AnchorPoint           = new CCPoint(0.5f, 0.5f);

                m_tImageOffset = imageOffset;

                m_pReusedChar = new CCSprite();
                m_pReusedChar.InitWithTexture(m_pobTextureAtlas.Texture, CCRect.Zero, false);
                m_pReusedChar.BatchNode = this;

                SetString(theString, true);

                return(true);
            }
            return(false);
        }
Example #3
0
        public void CreateFontChars()
        {
            int  nextFontPositionX = 0;
            int  nextFontPositionY = 0;
            char prev          = (char)255;
            int  kerningAmount = 0;

            CCSize tmpSize = CCSize.Zero;

            int longestLine = 0;
            int totalHeight = 0;

            int quantityOfLines = 1;

            if (String.IsNullOrEmpty(m_sString))
            {
                return;
            }

            int stringLen = m_sString.Length;

            var charSet = m_pConfiguration.CharacterSet;

            if (charSet.Count == 0)
            {
                throw (new InvalidOperationException(
                           "Can not compute the size of the font because the character set is empty."));
            }

            for (int i = 0; i < stringLen - 1; ++i)
            {
                if (m_sString[i] == '\n')
                {
                    quantityOfLines++;
                }
            }

            totalHeight       = m_pConfiguration.m_nCommonHeight * quantityOfLines;
            nextFontPositionY = 0 -
                                (m_pConfiguration.m_nCommonHeight - m_pConfiguration.m_nCommonHeight * quantityOfLines);

            CCBMFontConfiguration.CCBMFontDef fontDef = null;
            CCRect rect;

            for (int i = 0; i < stringLen; i++)
            {
                char c = m_sString[i];

                if (c == '\n')
                {
                    nextFontPositionX  = 0;
                    nextFontPositionY -= m_pConfiguration.m_nCommonHeight;
                    continue;
                }

                if (charSet.IndexOf(c) == -1)
                {
                    CCLog.Log("Cocos2D.CCLabelBMFont: Attempted to use character not defined in this bitmap: {0}",
                              (int)c);
                    continue;
                }

                kerningAmount = this.KerningAmountForFirst(prev, c);

                // unichar is a short, and an int is needed on HASH_FIND_INT
                if (!m_pConfiguration.m_pFontDefDictionary.TryGetValue(c, out fontDef))
                {
                    CCLog.Log("cocos2d::CCLabelBMFont: characer not found {0}", (int)c);
                    continue;
                }

                rect = fontDef.rect;
                rect = rect.PixelsToPoints();

                rect.Origin.X += m_tImageOffset.X;
                rect.Origin.Y += m_tImageOffset.Y;

                CCSprite fontChar;

                //bool hasSprite = true;
                fontChar = (CCSprite)(GetChildByTag(i));
                if (fontChar != null)
                {
                    // Reusing previous Sprite
                    fontChar.Visible = true;
                }
                else
                {
                    // New Sprite ? Set correct color, opacity, etc...
                    //if( false )
                    //{
                    //    /* WIP: Doesn't support many features yet.
                    //     But this code is super fast. It doesn't create any sprite.
                    //     Ideal for big labels.
                    //     */
                    //    fontChar = m_pReusedChar;
                    //    fontChar.BatchNode = null;
                    //    hasSprite = false;
                    //}
                    //else
                    {
                        fontChar = new CCSprite();
                        fontChar.InitWithTexture(m_pobTextureAtlas.Texture, rect);
                        AddChild(fontChar, i, i);
                    }

                    // Apply label properties
                    fontChar.IsOpacityModifyRGB = m_bIsOpacityModifyRGB;

                    // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
                    fontChar.UpdateDisplayedColor(m_tDisplayedColor);
                    fontChar.UpdateDisplayedOpacity(m_cDisplayedOpacity);
                }

                // updating previous sprite
                fontChar.SetTextureRect(rect, false, rect.Size);

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = m_pConfiguration.m_nCommonHeight - fontDef.yOffset;
                var fontPos =
                    new CCPoint(
                        (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.Size.Width * 0.5f + kerningAmount,
                        (float)nextFontPositionY + yOffset - rect.Size.Height * 0.5f * CCMacros.CCContentScaleFactor());
                fontChar.Position = fontPos.PixelsToPoints();

                // update kerning
                nextFontPositionX += fontDef.xAdvance + kerningAmount;
                prev = c;

                if (longestLine < nextFontPositionX)
                {
                    longestLine = nextFontPositionX;
                }

                //if (! hasSprite)
                //{
                //  UpdateQuadFromSprite(fontChar, i);
                //}
            }

            // If the last character processed has an xAdvance which is less that the width of the characters image, then we need
            // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
            // box
            if (fontDef.xAdvance < fontDef.rect.Size.Width)
            {
                tmpSize.Width = longestLine + fontDef.rect.Size.Width - fontDef.xAdvance;
            }
            else
            {
                tmpSize.Width = longestLine;
            }
            tmpSize.Height = totalHeight;

            tmpSize = new CCSize(
                m_tDimensions.Width > 0 ? m_tDimensions.Width : tmpSize.Width,
                m_tDimensions.Height > 0 ? m_tDimensions.Height : tmpSize.Height
                );

            ContentSize = tmpSize.PixelsToPoints();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="pszPlist"></param>
        /// <returns>The scope parameter derived from the pszPlist parameter.</returns>
        public string AddSpriteFramesWithFile(string pszPlist)
        {
            string path = CCFileUtils.FullPathFromRelativePath(pszPlist);
            //Dictionary<string, Object> dict = CCFileUtils.dictionaryWithContentsOfFile(pszPath);
            PlistDocument document = null;

            try
            {
                document = CCApplication.SharedApplication.Content.Load <PlistDocument>(path);
            }
            catch (System.Exception)
            {
                string xml = Cocos2D.Framework.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;
            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, path);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = path;

                // 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);
        }
        static internal CTFont CreateFont(string familyName, float emSize, FontStyle style,
                                          byte gdiCharSet, bool gdiVerticalFont)
        {
            if (emSize <= 0)
            {
                throw new ArgumentException("emSize is less than or equal to 0, evaluates to infinity, or is not a valid number.", "emSize");
            }

            CTFont nativeFont;
            // convert to 96 Dpi to be consistent with Windows
            var dpiSize = emSize * dpiScale;

            var ext = System.IO.Path.GetExtension(familyName);

            if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
            {
                var fontName        = familyName.Substring(0, familyName.Length - ext.Length);
                var path            = CCApplication.SharedApplication.Game.Content.RootDirectory + Path.DirectorySeparatorChar + fontName;
                var pathForResource = NSBundle.MainBundle.PathForResource(path, ext.Substring(1));

                try {
                    var dataProvider = new CGDataProvider(pathForResource);
                    var cgFont       = CGFont.CreateFromProvider(dataProvider);

                    try {
                        nativeFont = new CTFont(cgFont, dpiSize, null);
                    }
                    catch
                    {
                        nativeFont = new CTFont("Helvetica", dpiSize);
                    }
                }
                catch (Exception)
                {
                    try {
                        nativeFont = new CTFont(Path.GetFileNameWithoutExtension(familyName), dpiSize);
                    }
                    catch
                    {
                        nativeFont = new CTFont("Helvetica", dpiSize);
                    }
                    CCLog.Log(string.Format("Could not load font: {0} so will use default {1}.", familyName, nativeFont.DisplayName));
                }
            }
            else
            {
                try {
                    nativeFont = new CTFont(familyName, dpiSize);
                }
                catch
                {
                    nativeFont = new CTFont("Helvetica", dpiSize);
                }
            }


            CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None;

            if ((style & FontStyle.Bold) == FontStyle.Bold)
            {
                tMask |= CTFontSymbolicTraits.Bold;
            }
            if ((style & FontStyle.Italic) == FontStyle.Italic)
            {
                tMask |= CTFontSymbolicTraits.Italic;
            }
            strikeThrough = (style & FontStyle.Strikeout) == FontStyle.Strikeout;
            underLine     = (style & FontStyle.Underline) == FontStyle.Underline;

            var nativeFont2 = nativeFont.WithSymbolicTraits(dpiSize, tMask, tMask);

            if (nativeFont2 != null)
            {
                nativeFont = nativeFont2;
            }

            return(nativeFont);
        }
Example #6
0
        public void InitWithFile(string fileName)
        {
            PlistDocument document = CCContentManager.SharedContentManager.Load <PlistDocument>(fileName);

            var dict        = document.Root.AsDictionary;
            var texturePath = string.Empty;

            plistFilePath = string.Empty;

            plistType = GetPlistType(dict);

            if (plistType == PlistType.SpriteKit)
            {
                var images = dict.ContainsKey("images") ? dict ["images"].AsArray : null;

                var imageDict = images [0].AsDictionary;

                if (imageDict != null)
                {
                    // try to read  texture file name from meta data
                    if (imageDict.ContainsKey("path"))
                    {
                        texturePath = imageDict ["path"].AsString;
                    }
                }
            }
            else
            {
                var 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, fileName);
            }
            else
            {
                // build texture path by replacing file extension
                texturePath = fileName;

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

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

            plistFilePath = Path.GetDirectoryName(texturePath);

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

            if (pTexture != null)
            {
                InitWithDictionary(dict, pTexture);
            }
            else
            {
                CCLog.Log("CCSpriteSheet: Couldn't load texture");
            }
        }
Example #7
0
        /// <summary>
        /// Tests the collision mask for the two sprites and returns true if there is a collision. The hit point of the
        /// collision is returned.
        /// </summary>
        /// <param name="a">Sprite A</param>
        /// <param name="b">Sprite B</param>
        /// <param name="hitPoint">The place, in real space, where they collide</param>
        /// <returns>True upon collision and false if not.</returns>
        static bool MaskCollision(CCSprite a, CCSprite b, out CCPoint hitPoint)
        {
            long lStart = DateTime.Now.Ticks;

            try
            {
                byte[] maskA   = a.CollisionMask;                  // bitfield mask of sprite A
                byte[] maskB   = b.CollisionMask;                  // bitfield mask of sprite B
                int    aWidth  = (int)a.Texture.ContentSize.Width; // bitwise stride
                int    bWidth  = (int)b.Texture.ContentSize.Width; // bitwise stride
                int    aHeight = (int)a.Texture.ContentSize.Height;
                int    bHeight = (int)b.Texture.ContentSize.Height;
                // Calculate the intersecting rectangle
                int x1 = Math.Max(a.Bounds.X, b.Bounds.X);
                int x2 = Math.Min(a.Bounds.X + a.Bounds.Width, b.Bounds.X + b.Bounds.Width);

                int y1 = Math.Max(a.Bounds.Y, b.Bounds.Y);
                int y2 = Math.Min(a.Bounds.Y + a.Bounds.Height, b.Bounds.Y + b.Bounds.Height);
                // Next extract the bitfields for the intersection rectangles
                for (int y = y1; y < y2; ++y)
                {
                    for (int x = x1; x < x2; x++)
                    {
                        // Coordinates in the respective sprites
                        // Invert the Y because screen coords are opposite of mask coordinates!
                        int xA = x - a.Bounds.X;
                        int yA = aHeight - (y - a.Bounds.Y);
                        if (yA < 0)
                        {
                            yA = 0;
                        }
                        else if (yA >= aHeight)
                        {
                            yA = aHeight - 1;
                        }
                        int xB = x - b.Bounds.X;
                        int yB = bHeight - (y - b.Bounds.Y);
                        if (yB < 0)
                        {
                            yB = 0;
                        }
                        else if (yB >= bHeight)
                        {
                            yB = bHeight - 1;
                        }
                        // Get the color from each texture
                        byte ca = maskA[xA + yA * aWidth];
                        byte cb = maskB[xB + yB * bWidth];
#if DEBUG
                        if (a.DebugCollision && b.DebugCollision)
                        {
                            CCLog.Log("Collision test[{0},{1}] = A{2} == B{3} {4}", x, y, ca, cb, (ca == cb && ca > 0) ? "BOOM" : "");
                        }
#endif

                        if (ca > 0 && cb > 0) // If both colors are not transparent (the alpha channel is not 0), then there is a collision
                        {
                            // Find the hit point, where on the sprite in real space the collision occurs.
                            hitPoint = new CCPoint(a.Position.X - a.AnchorPoint.X * a.ContentSizeInPixels.Width + x, a.Position.Y - a.AnchorPoint.Y * a.ContentSizeInPixels.Height + y);
                            return(true);
                        }
                    }
                }
                hitPoint.X = 0;
                hitPoint.Y = 0;
                return(false);
            }
            finally
            {
                long diff = DateTime.Now.Ticks - lStart;
                CCLog.Log("Bitwise Collision took {0:N2} ms", new TimeSpan(diff).TotalMilliseconds);
            }
        }
Example #8
0
        private CCNode ReadNodeGraph(CCNode parent)
        {
            /* Read class name. */
            string className = ReadCachedString();

            // Read assignment type and name
            var memberVarAssignmentType = (CCBTargetType)ReadInt(false);

            string memberVarAssignmentName = String.Empty;

            if (memberVarAssignmentType != CCBTargetType.None)
            {
                memberVarAssignmentName = ReadCachedString();
            }

            CCNodeLoader ccNodeLoader = mCCNodeLoaderLibrary.GetCCNodeLoader(className);

            if (ccNodeLoader == null)
            {
                CCLog.Log("no corresponding node loader for %s", className);
                return(null);
            }

            CCNode node = ccNodeLoader.LoadCCNode(parent, this);

            // Set root node
            if (mActionManager.RootNode == null)
            {
                mActionManager.RootNode = node;
            }

            // Read animated properties
            var seqs = new Dictionary <int, Dictionary <string, CCBSequenceProperty> >();

            mAnimatedProps.Clear();

            int numSequence = ReadInt(false);

            for (int i = 0; i < numSequence; ++i)
            {
                int seqId        = ReadInt(false);
                var seqNodeProps = new Dictionary <string, CCBSequenceProperty>();

                int numProps = ReadInt(false);

                for (int j = 0; j < numProps; ++j)
                {
                    var seqProp = new CCBSequenceProperty();

                    seqProp.Name = ReadCachedString();
                    seqProp.Type = (CCBPropType)ReadInt(false);
                    mAnimatedProps.Add(seqProp.Name);

                    int numKeyframes = ReadInt(false);

                    for (int k = 0; k < numKeyframes; ++k)
                    {
                        CCBKeyframe keyframe = ReadKeyframe(seqProp.Type);

                        seqProp.Keyframes.Add(keyframe);
                    }

                    seqNodeProps.Add(seqProp.Name, seqProp);
                }

                seqs.Add(seqId, seqNodeProps);
            }

            if (seqs.Count > 0)
            {
                mActionManager.AddNode(node, seqs);
            }

            // Read properties
            ccNodeLoader.ParseProperties(node, parent, this);

            // Handle sub ccb files (remove middle node)
            if (node is CCBFile)
            {
                var ccbFileNode = (CCBFile)node;

                CCNode embeddedNode = ccbFileNode.FileNode;
                embeddedNode.Position = ccbFileNode.Position;
                embeddedNode.Rotation = ccbFileNode.Rotation;
                embeddedNode.Scale    = ccbFileNode.Scale;
                embeddedNode.Tag      = ccbFileNode.Tag;
                embeddedNode.Visible  = true;
                embeddedNode.IgnoreAnchorPointForPosition = ccbFileNode.IgnoreAnchorPointForPosition;

                ccbFileNode.FileNode = null;

                node = embeddedNode;
            }

#if CCB_ENABLE_JAVASCRIPT
            /*
             * if (memberVarAssignmentType && memberVarAssignmentName && ![memberVarAssignmentName isEqualToString:@""])
             * {
             * [[JSCocoa sharedController] setObject:node withName:memberVarAssignmentName];
             * }*/
#else
            if (memberVarAssignmentType != CCBTargetType.None)
            {
                object target = null;
                if (memberVarAssignmentType == CCBTargetType.DocumentRoot)
                {
                    target = mActionManager.RootNode;
                }
                else if (memberVarAssignmentType == CCBTargetType.Owner)
                {
                    target = mOwner;
                }

                if (target != null)
                {
                    bool assigned = false;

                    var targetAsCCBMemberVariableAssigner = (ICCBMemberVariableAssigner)target;

                    if (targetAsCCBMemberVariableAssigner != null)
                    {
                        assigned = targetAsCCBMemberVariableAssigner.OnAssignCCBMemberVariable(target, memberVarAssignmentName, node);
                    }

                    if (!assigned && mCCBMemberVariableAssigner != null)
                    {
                        mCCBMemberVariableAssigner.OnAssignCCBMemberVariable(target, memberVarAssignmentName, node);
                    }
                }
            }
#endif
            // CCB_ENABLE_JAVASCRIPT

            mAnimatedProps.Clear();

            /* Read and add children. */
            int numChildren = ReadInt(false);
            for (int i = 0; i < numChildren; i++)
            {
                CCNode child = ReadNodeGraph(node);
                node.AddChild(child);
            }

            // Call onNodeLoaded
            var nodeAsCCNodeLoaderListener = node as ICCNodeLoaderListener;
            if (nodeAsCCNodeLoaderListener != null)
            {
                nodeAsCCNodeLoaderListener.OnNodeLoaded(node, ccNodeLoader);
            }
            else if (mCCNodeLoaderListener != null)
            {
                mCCNodeLoaderListener.OnNodeLoaded(node, ccNodeLoader);
            }

            return(node);
        }
Example #9
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;


            // we only support one image for now
            var imageDict = images [0].AsDictionary;

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

            // 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);

                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;
            }
        }
Example #10
0
        public virtual void ScrollViewDidScroll(CCScrollView view)
        {
            var uCountOfItems = m_pDataSource.NumberOfCellsInTableView(this);

            if (uCountOfItems == 0)
            {
                return;
            }

            int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;

            CCPoint offset = GetContentOffset() * -1;

            maxIdx = Math.Max(uCountOfItems - 1, 0);

            CCSize cellSize = m_pDataSource.CellSizeForTable(this);

            if (m_eVordering == CCTableViewVerticalFillOrder.FillTopDown)
            {
                offset.Y = offset.Y + m_tViewSize.Height / Container.ScaleY - cellSize.Height;
            }
            startIdx = _indexFromOffset(offset);

            if (m_eVordering == CCTableViewVerticalFillOrder.FillTopDown)
            {
                offset.Y -= m_tViewSize.Height / Container.ScaleY;
            }
            else
            {
                offset.Y += m_tViewSize.Height / Container.ScaleY;
            }
            offset.X += m_tViewSize.Width / Container.ScaleX;

            endIdx = _indexFromOffset(offset);

#if DEBUG_ // For Testing.
            int i = 0;
            foreach (object pObj in m_pCellsUsed)
            {
                var pCell = (CCTableViewCell)pObj;
                CCLog.Log("cells Used index {0}, value = {1}", i, pCell.getIdx());
                i++;
            }
            CCLog.Log("---------------------------------------");
            i = 0;
            foreach (object pObj in m_pCellsFreed)
            {
                var pCell = (CCTableViewCell)pObj;
                CCLog.Log("cells freed index {0}, value = {1}", i, pCell.getIdx());
                i++;
            }
            CCLog.Log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
#endif

            if (m_pCellsUsed.Count > 0)
            {
                var cell = (CCTableViewCell)m_pCellsUsed[0];

                idx = cell.Index;
                while (idx < startIdx)
                {
                    _moveCellOutOfSight(cell);
                    if (m_pCellsUsed.Count > 0)
                    {
                        cell = (CCTableViewCell)m_pCellsUsed[0];
                        idx  = cell.Index;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (m_pCellsUsed.Count > 0)
            {
                var cell = (CCTableViewCell)m_pCellsUsed[m_pCellsUsed.Count - 1];
                idx = cell.Index;

                while (idx <= maxIdx && idx > endIdx)
                {
                    _moveCellOutOfSight(cell);
                    if (m_pCellsUsed.Count > 0)
                    {
                        cell = (CCTableViewCell)m_pCellsUsed[m_pCellsUsed.Count - 1];
                        idx  = cell.Index;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            for (int j = startIdx; j <= endIdx; j++)
            {
                if (m_pIndices.Contains(j))
                {
                    continue;
                }
                UpdateCellAtIndex(j);
            }
        }
        public bool InitWithFile(string file)
        {
            m_bManaged = false;

            Texture2D texture = null;

            m_CacheInfo.CacheType = CCTextureCacheType.AssetFile;
            m_CacheInfo.Data      = file;

            try
            {
                texture = CCApplication.SharedApplication.Content.Load <Texture2D>(file);
                //????????????????????????????
                return(InitWithTexture(texture, DefaultAlphaPixelFormat, true, true));
            }
            catch (Exception)
            {
            }

            if (texture == null)
            {
                string srcfile = file;

                if (srcfile.IndexOf('.') > -1)
                {
                    // Remove the extension
                    srcfile = srcfile.Substring(0, srcfile.LastIndexOf('.'));
                }

                try
                {
                    texture = CCApplication.SharedApplication.Content.Load <Texture2D>(srcfile);
                    //????????????????????????????
                    return(InitWithTexture(texture, DefaultAlphaPixelFormat, true, true));
                }
                catch (Exception)
                {
                    if (!srcfile.EndsWith("-hd"))
                    {
                        srcfile = srcfile + "-hd";
                        try
                        {
                            texture    = CCApplication.SharedApplication.Content.Load <Texture2D>(srcfile);
                            m_bManaged = true;
                            //????????????????????????????
                            return(InitWithTexture(texture, DefaultAlphaPixelFormat, true, true));
                        }
                        catch (Exception)
                        {
                            try
                            {
                                var stream = CCFileUtils.GetFileStream(file);
                                return(InitWithStream(stream, DefaultAlphaPixelFormat));
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            CCLog.Log("Texture {0} was not found.", file);
            return(false);
        }
Example #12
0
        public override void Reinit()
        {
            CCLog.Log("reinit called on {1} '{0}' {2}", ToString(),
                      m_CacheInfo.CacheType,
                      (m_CacheInfo.CacheType == CCTextureCacheType.AssetFile || m_CacheInfo.CacheType == CCTextureCacheType.String) ? m_CacheInfo.Data : string.Empty);

            Texture2D textureToDispose = null;

            if (m_Texture2D != null && !m_Texture2D.IsDisposed && !m_bManaged)
            {
                textureToDispose = m_Texture2D;
                // m_Texture2D.Dispose();
            }

            m_bManaged  = false;
            m_Texture2D = null;

            if (m_CacheInfo.CacheType != CCTextureCacheType.None)
            {
                switch (m_CacheInfo.CacheType)
                {
                case CCTextureCacheType.None:
                    return;

                case CCTextureCacheType.AssetFile:
                    InitWithFile((string)m_CacheInfo.Data);
                    break;

                case CCTextureCacheType.Data:
                    InitWithData((byte[])m_CacheInfo.Data, m_ePixelFormat, m_bHasMipmaps);
                    break;

                case CCTextureCacheType.RawData:
#if NETFX_CORE
                    var methodInfo = typeof(CCTexture2D).GetType().GetTypeInfo().GetDeclaredMethod("InitWithRawData");
#else
                    var methodInfo = typeof(CCTexture2D).GetMethods(BindingFlags.Public | BindingFlags.Instance).First(m => m.Name == "InitWithRawData" && m.IsGenericMethod && m.GetParameters().Length == 7);
#endif
                    var genericMethod = methodInfo.MakeGenericMethod(m_CacheInfo.Data.GetType().GetElementType());
                    genericMethod.Invoke(this, new object[]
                    {
                        m_CacheInfo.Data,
                        m_ePixelFormat, m_uPixelsWide, m_uPixelsHigh,
                        m_bHasPremultipliedAlpha, m_bHasMipmaps, m_tContentSize
                    });

                    //                    InitWithRawData((byte[])m_CacheInfo.Data, m_ePixelFormat, m_uPixelsWide, m_uPixelsHigh,
                    //                                    m_bHasPremultipliedAlpha, m_bHasMipmaps, m_tContentSize);
                    break;

                case CCTextureCacheType.String:
                    var si = (CCStringCache)m_CacheInfo.Data;
                    InitWithString(si.Text, si.Dimensions, si.HAlignment, si.VAlignment, si.FontName, si.FontSize);
                    if (m_bHasMipmaps)
                    {
                        m_bHasMipmaps = false;
                        GenerateMipmap();
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            if (textureToDispose != null && !textureToDispose.IsDisposed)
            {
                textureToDispose.Dispose();
            }
            if (OnReInit != null)
            {
                OnReInit();
            }
        }
Example #13
0
        public bool InitWithString(string text, CCSize dimensions, CCTextAlignment hAlignment,
                                   CCVerticalTextAlignment vAlignment, string fontName,
                                   float fontSize)
        {
            try
            {
                Debug.Assert(dimensions.Width >= 0 || dimensions.Height >= 0);

                if (string.IsNullOrEmpty(text))
                {
                    return(false);
                }

                float loadedSize = fontSize;

                SpriteFont font = CCSpriteFontCache.SharedInstance.TryLoadFont(fontName, fontSize, out loadedSize);

                if (font == null)
                {
                    CCLog.Log("Failed to load default font. No font supported.");
                    return(false);
                }

                float scale = 1f;

                if (loadedSize != 0)
                {
                    scale = fontSize / loadedSize * CCSpriteFontCache.FontScale;
                }

                if (dimensions.Equals(CCSize.Zero))
                {
                    Vector2 temp = font.MeasureString(text);
                    dimensions.Width  = temp.X * scale;
                    dimensions.Height = temp.Y * scale;
                }

                var textList = new List <String>();
                var nextText = new StringBuilder();

                string[] lineList = text.Split('\n');

                StringBuilder next = new StringBuilder();
                string        last = null;
                for (int j = 0; j < lineList.Length; ++j)
                {
                    string[] wordList = lineList[j].Split(' ');
                    for (int i = 0; i < wordList.Length;)
                    {
                        // Run through the list of words to create a sentence that fits in the dimensions.Width space
                        while (i < wordList.Length)
                        {
                            if ((font.MeasureString(next.ToString()).X *scale) > dimensions.Width)
                            {
                                i--;
                                break;
                            }
                            last = next.ToString();
                            if (next.Length > 0)
                            {
                                next.Append(' ');
                            }
                            next.Append(wordList[i]);
                            i++;
                        }
                        if (i == wordList.Length || i == -1) // -1 means the default width was too small for the string.
                        {
                            string nstr = next.ToString();
                            if ((font.MeasureString(nstr).X *scale) > dimensions.Width)
                            {
                                // Last line could have bleed into the margin
                                if (last != null && last.Length > 0)
                                {
                                    textList.Add(last);                      // Single word label has a null last which can cause problems
                                }
                                textList.Add(wordList[wordList.Length - 1]); // last word bleeds
                            }
                            else if (nstr.Length > 0)
                            {
                                textList.Add(nstr);
                            }
                        }
                        else if (last.Length > 0)
                        {
                            textList.Add(last);
                        }
                        last        = null;
                        next.Length = 0;
                    }

                    textList.Add(nextText.ToString());
#if XBOX || XBOX360
                    nextText.Length = 0;
#else
                    nextText.Clear();
#endif
                }

                if (textList.Count == 0 && text.Length > 0)
                {
                    textList.Add(text);
                }

                if (dimensions.Height == 0)
                {
                    dimensions.Height = textList.Count * font.LineSpacing * scale;
                }

                //*  for render to texture
                RenderTarget2D renderTarget = CCDrawManager.CreateRenderTarget(
                    (int)dimensions.Width, (int)dimensions.Height,
                    DefaultAlphaPixelFormat, RenderTargetUsage.DiscardContents
                    );

                try
                {
                    CCDrawManager.SetRenderTarget(renderTarget);
                }
                catch (Exception)
                {
                    CCTextureCache.SharedTextureCache.RemoveUnusedTextures();
                    CCDrawManager.SetRenderTarget(renderTarget);
                }
                CCDrawManager.Clear(Color.Transparent);

                SpriteBatch sb = CCDrawManager.spriteBatch;
                sb.Begin();

                float textHeight = textList.Count * font.LineSpacing * scale;
                float nextY      = 0;

                if (vAlignment == CCVerticalTextAlignment.Bottom)
                {
                    nextY = dimensions.Height - textHeight;
                }
                else if (vAlignment == CCVerticalTextAlignment.Center)
                {
                    nextY = (dimensions.Height - textHeight) / 2.0f;
                }

                for (int j = 0; j < textList.Count; ++j)
                {
                    string line = textList[j];

                    var position = new Vector2(0, nextY);

                    if (hAlignment == CCTextAlignment.Right)
                    {
                        position.X = dimensions.Width - font.MeasureString(line).X *scale;
                    }
                    else if (hAlignment == CCTextAlignment.Center)
                    {
                        position.X = (dimensions.Width - font.MeasureString(line).X *scale) / 2.0f;
                    }

                    sb.DrawString(font, line, position, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0);

                    nextY += font.LineSpacing * scale;
                }

                sb.End();

                CCDrawManager.graphicsDevice.RasterizerState   = RasterizerState.CullNone;
                CCDrawManager.graphicsDevice.DepthStencilState = DepthStencilState.Default;

                CCDrawManager.SetRenderTarget((RenderTarget2D)null);

                if (InitWithTexture(renderTarget, renderTarget.Format, true, false))
                {
                    m_CacheInfo.CacheType = CCTextureCacheType.String;
                    m_CacheInfo.Data      = new CCStringCache()
                    {
                        Dimensions = dimensions,
                        Text       = text,
                        FontName   = fontName,
                        FontSize   = fontSize,
                        HAlignment = hAlignment,
                        VAlignment = vAlignment
                    };

                    return(true);
                }
            }
            catch (Exception ex)
            {
                CCLog.Log(ex.ToString());
            }
            return(false);
        }
        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;
                }
            }
        }
Example #15
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();
        }
Example #16
0
        public void Touches(List <CCTouch> pTouches, int uIndex)
        {
            m_bLocked = true;
            if (m_bRearrangeTargetedHandlersUponTouch)
            {
                RearrangeHandlers(m_pTargetedHandlers);
            }
            if (m_bRearrangeStandardHandlersUponTouch)
            {
                RearrangeHandlers(m_pStandardHandlers);
            }

            // optimization to prevent a mutable copy when it is not necessary
            int  uTargetedHandlersCount = m_pTargetedHandlers.Count;
            int  uStandardHandlersCount = m_pStandardHandlers.Count;
            bool bNeedsMutableSet       = (uTargetedHandlersCount > 0 && uStandardHandlersCount > 0);

            if (bNeedsMutableSet)
            {
                CCTouch[] tempArray = pTouches.ToArray();
                pMutableTouches = tempArray.ToList();
            }
            else
            {
                pMutableTouches = pTouches;
            }

            var sHelper = (CCTouchType)uIndex;

            // process the target handlers 1st
            if (uTargetedHandlersCount > 0)
            {
                #region CCTargetedTouchHandler

                foreach (CCTouch pTouch in pTouches)
                {
                    foreach (CCTargetedTouchHandler pHandler in m_pTargetedHandlers)
                    {
                        var pDelegate = (ICCTargetedTouchDelegate)(pHandler.Delegate);

                        bool bClaimed = false;
                        if (sHelper == CCTouchType.Began)
                        {
                            bClaimed = pDelegate.TouchBegan(pTouch);

                            if (bClaimed)
                            {
                                pHandler.ClaimedTouches.Add(pTouch);
                            }
                        }
                        else
                        {
                            if (pHandler.ClaimedTouches.Contains(pTouch))
                            {
                                // moved ended cancelled
                                bClaimed = true;

                                switch (sHelper)
                                {
                                case CCTouchType.Moved:
                                    pDelegate.TouchMoved(pTouch);
                                    break;

                                case CCTouchType.Ended:
                                    pDelegate.TouchEnded(pTouch);
                                    pHandler.ClaimedTouches.Remove(pTouch);
                                    break;

                                case CCTouchType.Cancelled:
                                    pDelegate.TouchCancelled(pTouch);
                                    pHandler.ClaimedTouches.Remove(pTouch);
                                    break;
                                }
                            }
                        }

                        if (bClaimed && pHandler.ConsumesTouches)
                        {
                            if (bNeedsMutableSet)
                            {
                                pMutableTouches.Remove(pTouch);
                            }

                            break;
                        }
                    }
                }

                #endregion
            }

            // process standard handlers 2nd
            if (uStandardHandlersCount > 0 && pMutableTouches.Count > 0)
            {
                #region CCStandardTouchHandler

                foreach (CCStandardTouchHandler pHandler in m_pStandardHandlers)
                {
                    var pDelegate = (ICCStandardTouchDelegate)pHandler.Delegate;
                    switch (sHelper)
                    {
                    case CCTouchType.Began:
                        pDelegate.TouchesBegan(pMutableTouches);
                        break;

                    case CCTouchType.Moved:
                        pDelegate.TouchesMoved(pMutableTouches);
                        break;

                    case CCTouchType.Ended:
                        pDelegate.TouchesEnded(pMutableTouches);
                        break;

                    case CCTouchType.Cancelled:
                        pDelegate.TouchesCancelled(pMutableTouches);
                        break;
                    }
                }

                #endregion
            }

            if (bNeedsMutableSet)
            {
                pMutableTouches = null;
            }

            //
            // Optimization. To prevent a [handlers copy] which is expensive
            // the add/removes/quit is done after the iterations
            //
            m_bLocked = false;
            if (m_bToRemove)
            {
                m_bToRemove = false;
                for (int i = 0; i < m_pHandlersToRemove.Count; ++i)
                {
                    ForceRemoveDelegate((ICCTouchDelegate)m_pHandlersToRemove[i]);
                }
                m_pHandlersToRemove.Clear();
            }

            if (m_bToAdd)
            {
                m_bToAdd = false;
                foreach (CCTouchHandler pHandler in m_pHandlersToAdd)
                {
                    if (pHandler is CCTargetedTouchHandler && pHandler.Delegate is ICCTargetedTouchDelegate)
                    {
                        ForceAddHandler(pHandler, m_pTargetedHandlers);
                    }
                    else if (pHandler is CCStandardTouchHandler && pHandler.Delegate is ICCStandardTouchDelegate)
                    {
                        ForceAddHandler(pHandler, m_pStandardHandlers);
                    }
                    else
                    {
                        CCLog.Log("ERROR: inconsistent touch handler and delegate found in m_pHandlersToAdd of CCTouchDispatcher");
                    }
                }

                m_pHandlersToAdd.Clear();
            }

            if (m_bToQuit)
            {
                m_bToQuit = false;
                ForceRemoveAllDelegates();
            }
        }
Example #17
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();
        }
Example #18
0
        public void StartElement(object ctx, string name, string[] atts)
        {
            CCTMXMapInfo pTMXMapInfo   = this;
            string       elementName   = name;
            var          attributeDict = new Dictionary <string, string>();

            if (atts != null && atts[0] != null)
            {
                for (int i = 0; i + 1 < atts.Length; i += 2)
                {
                    string key   = atts[i];
                    string value = atts[i + 1];
                    attributeDict.Add(key, value);
                }
            }
            if (elementName == "map")
            {
                string version = attributeDict["version"];
                if (version != "1.0")
                {
                    CCLog.Log("cocos2d: TMXFormat: Unsupported TMX version: {0}", version);
                }
                string orientationStr = attributeDict["orientation"];
                if (orientationStr == "orthogonal")
                {
                    pTMXMapInfo.Orientation = (int)(CCTMXOrientation.Ortho);
                }
                else if (orientationStr == "isometric")
                {
                    pTMXMapInfo.Orientation = (int)(CCTMXOrientation.Iso);
                }
                else if (orientationStr == "hexagonal")
                {
                    pTMXMapInfo.Orientation = (int)(CCTMXOrientation.Hex);
                }
                else
                {
                    CCLog.Log("cocos2d: TMXFomat: Unsupported orientation: {0}", pTMXMapInfo.Orientation);
                }

                CCSize sMapSize;
                sMapSize.Width      = CCUtils.CCParseFloat(attributeDict["width"]);
                sMapSize.Height     = CCUtils.CCParseFloat(attributeDict["height"]);
                pTMXMapInfo.MapSize = sMapSize;

                CCSize sTileSize;
                sTileSize.Width      = CCUtils.CCParseFloat(attributeDict["tilewidth"]);
                sTileSize.Height     = CCUtils.CCParseFloat(attributeDict["tileheight"]);
                pTMXMapInfo.TileSize = sTileSize;

                // The parent element is now "map"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Map;
            }
            else if (elementName == "tileset")
            {
                // If this is an external tileset then start parsing that

                if (attributeDict.Keys.Contains("source"))
                {
                    string externalTilesetFilename = attributeDict["source"];

                    externalTilesetFilename = CCFileUtils.FullPathFromRelativeFile(externalTilesetFilename, pTMXMapInfo.TMXFileName);

                    m_uCurrentFirstGID = uint.Parse(attributeDict["firstgid"]);

                    pTMXMapInfo.ParseXmlFile(externalTilesetFilename);
                }
                else
                {
                    var tileset = new CCTMXTilesetInfo();

                    tileset.m_sName = attributeDict["name"];

                    if (m_uCurrentFirstGID == 0)
                    {
                        tileset.m_uFirstGid = uint.Parse(attributeDict["firstgid"]);
                    }
                    else
                    {
                        tileset.m_uFirstGid = m_uCurrentFirstGID;
                        m_uCurrentFirstGID  = 0;
                    }

                    if (attributeDict.Keys.Contains("spacing"))
                    {
                        tileset.m_uSpacing = int.Parse(attributeDict["spacing"]);
                    }

                    if (attributeDict.Keys.Contains("margin"))
                    {
                        tileset.m_uMargin = int.Parse(attributeDict["margin"]);
                    }

                    CCSize s;
                    s.Width             = CCUtils.CCParseFloat(attributeDict["tilewidth"]);
                    s.Height            = CCUtils.CCParseFloat(attributeDict["tileheight"]);
                    tileset.m_tTileSize = s;

                    pTMXMapInfo.Tilesets.Add(tileset);
                }
            }
            else if (elementName == "tile")
            {
                CCTMXTilesetInfo info = pTMXMapInfo.Tilesets.LastOrDefault();
                var dict = new Dictionary <string, string>();
                pTMXMapInfo.ParentGID = (info.m_uFirstGid + uint.Parse(attributeDict["id"]));
                pTMXMapInfo.TileProperties.Add(pTMXMapInfo.ParentGID, dict);

                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Tile;
            }
            else if (elementName == "layer")
            {
                var layer = new CCTMXLayerInfo();
                layer.Name = attributeDict["name"];

                CCSize s;
                s.Width         = CCUtils.CCParseFloat(attributeDict["width"]);
                s.Height        = CCUtils.CCParseFloat(attributeDict["height"]);
                layer.LayerSize = s;

                layer.Tiles = new uint[(int)s.Width * (int)s.Height];

                if (attributeDict.Keys.Contains("visible"))
                {
                    string visible = attributeDict["visible"];
                    layer.Visible = !(visible == "0");
                }
                else
                {
                    layer.Visible = true;
                }

                if (attributeDict.Keys.Contains("opacity"))
                {
                    string opacity = attributeDict["opacity"];
                    layer.Opacity = (byte)(255 * CCUtils.CCParseFloat(opacity));
                }
                else
                {
                    layer.Opacity = 255;
                }

                float x = attributeDict.Keys.Contains("x") ? CCUtils.CCParseFloat(attributeDict["x"]) : 0;
                float y = attributeDict.Keys.Contains("y") ? CCUtils.CCParseFloat(attributeDict["y"]) : 0;
                layer.Offset = new CCPoint(x, y);

                pTMXMapInfo.Layers.Add(layer);

                // The parent element is now "layer"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Layer;
            }
            else if (elementName == "objectgroup")
            {
                var objectGroup = new CCTMXObjectGroup();
                objectGroup.GroupName = attributeDict["name"];

                CCPoint positionOffset = CCPoint.Zero;
                if (attributeDict.ContainsKey("x"))
                {
                    positionOffset.X = CCUtils.CCParseFloat(attributeDict["x"]) * pTMXMapInfo.TileSize.Width;
                }
                if (attributeDict.ContainsKey("y"))
                {
                    positionOffset.Y = CCUtils.CCParseFloat(attributeDict["y"]) * pTMXMapInfo.TileSize.Height;
                }
                objectGroup.PositionOffset = positionOffset;

                pTMXMapInfo.ObjectGroups.Add(objectGroup);

                // The parent element is now "objectgroup"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.ObjectGroup;
            }
            else if (elementName == "image")
            {
                CCTMXTilesetInfo tileset = pTMXMapInfo.Tilesets.LastOrDefault();

                // build full path
                string imagename = attributeDict["source"];
                tileset.m_sSourceImage = CCFileUtils.FullPathFromRelativeFile(imagename, pTMXMapInfo.TMXFileName);
            }
            else if (elementName == "data")
            {
                string encoding    = attributeDict.ContainsKey("encoding") ? attributeDict["encoding"] : "";
                string compression = attributeDict.ContainsKey("compression") ? attributeDict["compression"] : "";

                if (encoding == "base64")
                {
                    int layerAttribs = pTMXMapInfo.LayerAttribs;
                    pTMXMapInfo.LayerAttribs      = layerAttribs | (int)CCTMXLayerAttrib.Base64;
                    pTMXMapInfo.StoringCharacters = true;

                    if (compression == "gzip")
                    {
                        layerAttribs             = pTMXMapInfo.LayerAttribs;
                        pTMXMapInfo.LayerAttribs = layerAttribs | (int)CCTMXLayerAttrib.Gzip;
                    }
                    else if (compression == "zlib")
                    {
                        layerAttribs             = pTMXMapInfo.LayerAttribs;
                        pTMXMapInfo.LayerAttribs = layerAttribs | (int)CCTMXLayerAttrib.Zlib;
                    }
                    Debug.Assert(compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method");
                }
                Debug.Assert(pTMXMapInfo.LayerAttribs != (int)CCTMXLayerAttrib.None,
                             "TMX tile map: Only base64 and/or gzip/zlib maps are supported");
            }
            else if (elementName == "object")
            {
                CCTMXObjectGroup objectGroup = pTMXMapInfo.ObjectGroups.LastOrDefault();

                // The value for "type" was blank or not a valid class name
                // Create an instance of TMXObjectInfo to store the object and its properties
                var dict = new Dictionary <string, string>();

                var pArray = new[] { "name", "type", "width", "height", "gid" };

                for (int i = 0; i < pArray.Length; i++)
                {
                    string key = pArray[i];
                    if (attributeDict.ContainsKey(key))
                    {
                        dict.Add(key, attributeDict[key]);
                    }
                }

                // But X and Y since they need special treatment
                // X

                int x = int.Parse(attributeDict["x"]) + (int)objectGroup.PositionOffset.X;
                dict.Add("x", x.ToString());

                int y = int.Parse(attributeDict["y"]) + (int)objectGroup.PositionOffset.Y;
                // Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
                y = (int)(pTMXMapInfo.MapSize.Height * pTMXMapInfo.TileSize.Height) - y -
                    (attributeDict.ContainsKey("height") ? int.Parse(attributeDict["height"]) : 0);
                dict.Add("y", y.ToString());

                // Add the object to the objectGroup
                objectGroup.Objects.Add(dict);

                // The parent element is now "object"
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.Object;
            }
            else if (elementName == "property")
            {
                if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.None)
                {
                    CCLog.Log("TMX tile map: Parent element is unsupported. Cannot add property named '{0}' with value '{1}'",
                              attributeDict["name"], attributeDict["value"]);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Map)
                {
                    // The parent element is the map
                    string value = attributeDict["value"];
                    string key   = attributeDict["name"];
                    pTMXMapInfo.Properties.Add(key, value);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Layer)
                {
                    // The parent element is the last layer
                    CCTMXLayerInfo layer = pTMXMapInfo.Layers.LastOrDefault();
                    string         value = attributeDict["value"];
                    string         key   = attributeDict["name"];
                    // Add the property to the layer
                    layer.Properties.Add(key, value);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.ObjectGroup)
                {
                    // The parent element is the last object group
                    CCTMXObjectGroup objectGroup = pTMXMapInfo.ObjectGroups.LastOrDefault();
                    string           value       = attributeDict["value"];
                    string           key         = attributeDict["name"];
                    objectGroup.Properties.Add(key, value);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Object)
                {
                    // The parent element is the last object
                    CCTMXObjectGroup            objectGroup = pTMXMapInfo.ObjectGroups.LastOrDefault();
                    Dictionary <string, string> dict        = objectGroup.Objects.LastOrDefault();

                    string propertyName  = attributeDict["name"];
                    string propertyValue = attributeDict["value"];
                    dict.Add(propertyName, propertyValue);
                }
                else if (pTMXMapInfo.ParentElement == (int)CCTMXProperty.Tile)
                {
                    Dictionary <string, string> dict = pTMXMapInfo.TileProperties[pTMXMapInfo.ParentGID];

                    string propertyName  = attributeDict["name"];
                    string propertyValue = attributeDict["value"];
                    dict.Add(propertyName, propertyValue);
                }
            }
            else if (elementName == "polygon")
            {
                // find parent object's dict and add polygon-points to it
                CCTMXObjectGroup objectGroup = m_pObjectGroups.LastOrDefault();
                var dict = objectGroup.Objects.LastOrDefault();

                // get points value string
                var value = attributeDict["points"];
                if (!String.IsNullOrEmpty(value))
                {
                    var pPointsArray = new List <CCPoint>();
                    var pointPairs   = value.Split(' ');

                    foreach (var pontPair in pointPairs)
                    {
                        //TODO: Parse points
                        //CCPoint point;
                        //point.X = x + objectGroup.PositionOffset.X;
                        //point.Y = y + objectGroup.PositionOffset.Y;

                        //pPointsArray.Add(point);
                    }

                    //dict.Add("points", pPointsArray);
                }
            }
            else if (elementName == "polyline")
            {
                // find parent object's dict and add polyline-points to it
                // CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)m_pObjectGroups->lastObject();
                // CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject();
                // TODO: dict->setObject:[attributeDict objectForKey:@"points"] forKey:@"polylinePoints"];
            }
        }
Example #19
0
        public bool InitWithString(string text, CCSize dimensions, CCTextAlignment hAlignment,
                                   CCVerticalTextAlignment vAlignment, string fontName,
                                   float fontSize)
        {
            try
            {
                Debug.Assert(dimensions.Width >= 0 || dimensions.Height >= 0);

                if (string.IsNullOrEmpty(text))
                {
                    return(false);
                }

                float loadedSize = fontSize;

                SpriteFont font = CCSpriteFontCache.SharedInstance.TryLoadFont(fontName, fontSize, out loadedSize);

                if (font == null)
                {
                    CCLog.Log("Failed to load default font. No font supported.");
                    return(false);
                }

                float scale = 1f;

                if (loadedSize != 0)
                {
                    scale = fontSize / loadedSize;
                }

                if (dimensions.Equals(CCSize.Zero))
                {
                    Vector2 temp = font.MeasureString(text);
                    dimensions.Width  = temp.X * scale;
                    dimensions.Height = temp.Y * scale;
                }

                var textList = new List <String>();
                var nextText = new StringBuilder();

                string[] lineList = text.Split('\n');

                float spaceWidth = font.MeasureString(" ").X *scale;

                for (int j = 0; j < lineList.Length; ++j)
                {
                    string[] wordList = lineList[j].Split(' ');

                    float lineWidth = 0;
                    bool  firstWord = true;

                    for (int i = 0; i < wordList.Length; ++i)
                    {
                        float wordWidth = font.MeasureString(wordList[i]).X *scale;

                        if ((lineWidth + wordWidth) > dimensions.Width)
                        {
                            lineWidth = wordWidth;

                            if (nextText.Length > 0)
                            {
                                firstWord = true;
                                textList.Add(nextText.ToString());
#if XBOX || XBOX360
                                nextText.Length = 0;
#else
                                nextText.Clear();
#endif
                            }
                            else
                            {
                                lineWidth += wordWidth;
                                firstWord  = false;
                                textList.Add(wordList[i]);
                                continue;
                            }
                        }
                        else
                        {
                            lineWidth += wordWidth;
                        }
                        if (!firstWord)
                        {
                            nextText.Append(' ');
                            lineWidth += spaceWidth;
                        }

                        nextText.Append(wordList[i]);
                        firstWord = false;
                    }

                    textList.Add(nextText.ToString());
#if XBOX || XBOX360
                    nextText.Length = 0;
#else
                    nextText.Clear();
#endif
                }

                if (dimensions.Height == 0)
                {
                    dimensions.Height = textList.Count * font.LineSpacing * scale;
                }

                //*  for render to texture
                RenderTarget2D renderTarget = CCDrawManager.CreateRenderTarget(
                    (int)dimensions.Width, (int)dimensions.Height,
                    DefaultAlphaPixelFormat, RenderTargetUsage.DiscardContents
                    );

                CCDrawManager.SetRenderTarget(renderTarget);
                CCDrawManager.Clear(Color.Transparent);

                SpriteBatch sb = CCDrawManager.spriteBatch;
                sb.Begin();

                float textHeight = textList.Count * font.LineSpacing * scale;
                float nextY      = 0;

                if (vAlignment == CCVerticalTextAlignment.Bottom)
                {
                    nextY = dimensions.Height - textHeight;
                }
                else if (vAlignment == CCVerticalTextAlignment.Center)
                {
                    nextY = (dimensions.Height - textHeight) / 2.0f;
                }

                for (int j = 0; j < textList.Count; ++j)
                {
                    string line = textList[j];

                    var position = new Vector2(0, nextY);

                    if (hAlignment == CCTextAlignment.Right)
                    {
                        position.X = dimensions.Width - font.MeasureString(line).X *scale;
                    }
                    else if (hAlignment == CCTextAlignment.Center)
                    {
                        position.X = (dimensions.Width - font.MeasureString(line).X *scale) / 2.0f;
                    }

                    sb.DrawString(font, line, position, Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0);

                    nextY += font.LineSpacing * scale;
                }

                sb.End();

                CCDrawManager.graphicsDevice.RasterizerState   = RasterizerState.CullNone;
                CCDrawManager.graphicsDevice.DepthStencilState = DepthStencilState.Default;

                CCDrawManager.SetRenderTarget((RenderTarget2D)null);

                if (InitWithTexture(renderTarget, renderTarget.Format, true, false))
                {
                    m_CacheInfo.CacheType = CCTextureCacheType.String;
                    m_CacheInfo.Data      = new CCStringCache()
                    {
                        Dimensions = dimensions,
                        Text       = text,
                        FontName   = fontName,
                        FontSize   = fontSize,
                        HAlignment = hAlignment,
                        VAlignment = vAlignment
                    };

                    return(true);
                }
            }
            catch (Exception ex)
            {
                CCLog.Log(ex.ToString());
            }
            return(false);
        }
Example #20
0
        public void EndElement(object ctx, string elementName)
        {
            CCTMXMapInfo pTMXMapInfo = this;

            byte[] encoded = null;

            if (elementName == "data" && (pTMXMapInfo.LayerAttribs & (int)CCTMXLayerAttrib.Base64) != 0)
            {
                pTMXMapInfo.StoringCharacters = false;
                CCTMXLayerInfo layer = pTMXMapInfo.Layers.LastOrDefault();
                if ((pTMXMapInfo.LayerAttribs & ((int)(CCTMXLayerAttrib.Gzip) | (int)CCTMXLayerAttrib.Zlib)) != 0)
                {
                    //gzip compress
                    if ((pTMXMapInfo.LayerAttribs & (int)CCTMXLayerAttrib.Gzip) != 0)
                    {
                        try
                        {
//#if  WINDOWS || WINDOWSGL || MONOMAC || IOS
                            GZipStream inGZipStream = new GZipStream(new MemoryStream(pTMXMapInfo.CurrentString));
//#elif !XBOX
//                            var inGZipStream = new GZipStream(new MemoryStream(pTMXMapInfo.CurrentString), CompressionMode.Decompress);
//#else
//                        var inGZipStream = new GZipInputStream(new MemoryStream(pTMXMapInfo.CurrentString));
//#endif

                            var outMemoryStream = new MemoryStream();

                            var buffer = new byte[1024];
                            while (true)
                            {
                                int bytesRead = inGZipStream.Read(buffer, 0, buffer.Length);
                                if (bytesRead == 0)
                                {
                                    break;
                                }
                                outMemoryStream.Write(buffer, 0, bytesRead);
                            }
                            encoded = outMemoryStream.ToArray();
                        }
                        catch (Exception ex)
                        {
                            CCLog.Log("failed to decompress embedded data object in TMX file.");
                            CCLog.Log(ex.ToString());
                        }
                    }

                    //zlib
                    if ((pTMXMapInfo.LayerAttribs & (int)CCTMXLayerAttrib.Zlib) != 0)
                    {
                        var inZInputStream = new ZInputStream(new MemoryStream(pTMXMapInfo.CurrentString));

                        var outMemoryStream = new MemoryStream();

                        var buffer = new byte[1024];
                        while (true)
                        {
                            int bytesRead = inZInputStream.Read(buffer, 0, buffer.Length);
                            if (bytesRead == 0)
                            {
                                break;
                            }
                            outMemoryStream.Write(buffer, 0, bytesRead);
                        }

                        encoded = outMemoryStream.ToArray();
                    }
                }
                else
                {
                    encoded = pTMXMapInfo.CurrentString;
                }

                for (int i = 0; i < layer.Tiles.Length; i++)
                {
                    int i4  = i * 4;
                    var gid = (uint)(
                        encoded[i4] |
                        encoded[i4 + 1] << 8 |
                            encoded[i4 + 2] << 16 |
                            encoded[i4 + 3] << 24);

                    layer.Tiles[i] = gid;
                }

                pTMXMapInfo.CurrentString = null;
            }
            else if (elementName == "map")
            {
                // The map element has ended
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.None;
            }
            else if (elementName == "layer")
            {
                // The layer element has ended
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.None;
            }
            else if (elementName == "objectgroup")
            {
                // The objectgroup element has ended
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.None;
            }
            else if (elementName == "object")
            {
                // The object element has ended
                pTMXMapInfo.ParentElement = (int)CCTMXProperty.None;
            }
        }
Example #21
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);
        }
Example #22
0
        internal void update(float dt)
        {
            m_bUpdateHashLocked = true;

            try
            {
                if (TimeScale != 1.0f)
                {
                    dt *= TimeScale;
                }

                LinkedListNode <ListEntry> next;

                // updates with priority < 0
                //foreach (ListEntry entry in _updatesNegList)
                for (LinkedListNode <ListEntry> node = m_pUpdatesNegList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (!node.Value.Paused && !node.Value.MarkedForDeletion)
                    {
                        try
                        {
                            node.Value.Target.Update(dt);
                        }
                        catch (Exception ex)
                        {
                            CCLog.Log("Target of update has crashed with exception {0}", ex);
                        }
                    }
                }

                // updates with priority == 0
                //foreach (ListEntry entry in _updates0List)
                for (LinkedListNode <ListEntry> node = m_pUpdates0List.First; node != null; node = next)
                {
                    next = node.Next;
                    if (!node.Value.Paused && !node.Value.MarkedForDeletion)
                    {
                        try
                        {
                            node.Value.Target.Update(dt);
                        }
                        catch (Exception ex)
                        {
                            CCLog.Log("Target of update has crashed with exception {0}", ex);
                        }
                    }
                }

                // updates with priority > 0
                for (LinkedListNode <ListEntry> node = m_pUpdatesPosList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (!node.Value.Paused && !node.Value.MarkedForDeletion)
                    {
                        try
                        {
                            node.Value.Target.Update(dt);
                        }
                        catch (Exception ex)
                        {
                            CCLog.Log("Target of update has crashed with exception {0}", ex);
                        }
                    }
                }

                // Iterate over all the custom selectors
                var count = m_pHashForTimers.Keys.Count;
                if (s_pTmpSelectorArray.Length < count)
                {
                    s_pTmpSelectorArray = new ICCSelectorProtocol[s_pTmpSelectorArray.Length * 2];
                }
                m_pHashForTimers.Keys.CopyTo(s_pTmpSelectorArray, 0);

                for (int i = 0; i < count; i++)
                {
                    ICCSelectorProtocol key = s_pTmpSelectorArray[i];
                    if (!m_pHashForTimers.ContainsKey(key))
                    {
                        continue;
                    }
                    HashTimeEntry elt = m_pHashForTimers[key];

                    m_pCurrentTarget         = elt;
                    m_bCurrentTargetSalvaged = false;

                    if (elt != null && !m_pCurrentTarget.Paused)
                    {
                        // The 'timers' array may change while inside this loop
                        for (elt.TimerIndex = 0; elt.TimerIndex < elt.Timers.Count; ++elt.TimerIndex)
                        {
                            elt.CurrentTimer = elt.Timers[elt.TimerIndex];
                            if (elt.CurrentTimer != null)
                            {
                                elt.CurrentTimerSalvaged = false;
                                try
                                {
                                    elt.CurrentTimer.Update(dt);
                                }
                                catch (Exception ex)
                                {
                                    CCLog.Log("Timer has crashed during update with exception {0}", ex);
                                }
                                elt.CurrentTimer = null;
                            }
                        }
                    }

                    // only delete currentTarget if no actions were scheduled during the cycle (issue #481)
                    if (m_bCurrentTargetSalvaged && m_pCurrentTarget.Timers.Count == 0)
                    {
                        RemoveHashElement(m_pCurrentTarget);
                    }
                }

                /*
                 * // Iterate over all the script callbacks
                 * if (m_pScriptHandlerEntries)
                 * {
                 *  for (int i = m_pScriptHandlerEntries->count() - 1; i >= 0; i--)
                 *  {
                 *      CCSchedulerScriptHandlerEntry* pEntry = static_cast<CCSchedulerScriptHandlerEntry*>(m_pScriptHandlerEntries->objectAtIndex(i));
                 *      if (pEntry->isMarkedForDeletion())
                 *      {
                 *          m_pScriptHandlerEntries->removeObjectAtIndex(i);
                 *      }
                 *      else if (!pEntry->isPaused())
                 *      {
                 *          pEntry->getTimer()->update(dt);
                 *      }
                 *  }
                 * }
                 */

                // delete all updates that are marked for deletion
                // updates with priority < 0
                for (LinkedListNode <ListEntry> node = m_pUpdatesNegList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (node.Value.MarkedForDeletion)
                    {
                        m_pUpdatesNegList.Remove(node);
                        RemoveUpdateFromHash(node.Value);
                    }
                }

                // updates with priority == 0
                for (LinkedListNode <ListEntry> node = m_pUpdates0List.First; node != null; node = next)
                {
                    next = node.Next;
                    if (node.Value.MarkedForDeletion)
                    {
                        m_pUpdates0List.Remove(node);
                        RemoveUpdateFromHash(node.Value);
                    }
                }

                // updates with priority > 0
                for (LinkedListNode <ListEntry> node = m_pUpdatesPosList.First; node != null; node = next)
                {
                    next = node.Next;
                    if (node.Value.MarkedForDeletion)
                    {
                        m_pUpdatesPosList.Remove(node);
                        RemoveUpdateFromHash(node.Value);
                    }
                }
            }
            finally
            {
                // Always do this just in case there is a problem

                m_bUpdateHashLocked = false;
                m_pCurrentTarget    = null;
            }
        }