Пример #1
0
        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

                    frameRect.Origin += spriteOffset;

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

                    spriteFrame.TextureFilename = name;
                    spriteFrames [name]         = spriteFrame;
                }
            }
            AutoCreateAliasList();
        }
Пример #2
0
 public CCLabelBMFont(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                      CCPoint imageOffset, CCTexture2D texture)
 {
     InitCCLabelBMFont(str, fntFile, dimensions, hAlignment, vAlignment, imageOffset, texture);
 }
Пример #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(labelText))
            {
                return;
            }

            int stringLen = labelText.Length;

            var charSet = FontConfiguration.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 (labelText[i] == '\n')
                {
                    quantityOfLines++;
                }
            }

            LineHeight = FontConfiguration.CommonHeight;

            totalHeight       = LineHeight * quantityOfLines;
            nextFontPositionY = 0 -
                                (LineHeight - LineHeight * quantityOfLines);

            CCBMFontConfiguration.CCBMGlyphDef fontDef = null;
            CCRect fontCharTextureRect;
            CCSize fontCharContentSize;

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

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

                if (charSet.IndexOf(c) == -1)
                {
                    CCLog.Log("CocosSharp: 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 (!FontConfiguration.Glyphs.TryGetValue(c, out fontDef))
                {
                    CCLog.Log("CocosSharp: CCLabelBMFont: character not found {0}", (int)c);
                    continue;
                }

                fontCharTextureRect           = fontDef.Subrect;
                fontCharTextureRect.Origin.X += ImageOffset.X;
                fontCharTextureRect.Origin.Y += ImageOffset.Y;

                fontCharContentSize = fontCharTextureRect.Size / DefaultTexelToContentSizeRatios;

                CCSprite fontChar;

                //bool hasSprite = true;
                fontChar = (CCSprite)(this[i]);
                if (fontChar != null)
                {
                    // Reusing previous Sprite
                    fontChar.Visible = true;

                    // updating previous sprite
                    fontChar.IsTextureRectRotated = false;
                    fontChar.ContentSize          = fontCharContentSize;
                    fontChar.TextureRectInPixels  = fontCharTextureRect;
                }
                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(TextureAtlas.Texture, fontCharTextureRect);
                        fontChar.ContentSize = fontCharContentSize;
                        AddChild(fontChar, i, i);
                    }

                    // Apply label properties
                    fontChar.IsColorModifiedByOpacity = IsColorModifiedByOpacity;

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

                // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
                int yOffset = FontConfiguration.CommonHeight - fontDef.YOffset;

                var fontPos =
                    new CCPoint(
                        (float)nextFontPositionX + fontDef.XOffset + fontDef.Subrect.Size.Width * 0.5f + kerningAmount,
                        (float)nextFontPositionY + yOffset - fontCharTextureRect.Size.Height * 0.5f);

                fontChar.Position = fontPos;

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

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

            // 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 != null && fontDef.XAdvance < fontDef.Subrect.Size.Width)
            {
                tmpSize.Width = longestLine + fontDef.Subrect.Size.Width - fontDef.XAdvance;
            }
            else
            {
                tmpSize.Width = longestLine;
            }

            tmpSize.Height = totalHeight;
            var tmpDimensions = labelDimensions;

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

            ContentSize     = labelDimensions;
            labelDimensions = tmpDimensions;
        }
Пример #4
0
 public static void DrawPoint(CCPoint point, float size)
 {
     DrawPoint(point, size, DrawColor);
 }
Пример #5
0
 public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset, CCTexture2D texture)
     : this(str, fntFile, width, alignment, CCVerticalTextAlignment.Top, imageOffset, null)
 {
 }
Пример #6
0
 public static void DrawQuadBezier(CCPoint origin, CCPoint control, CCPoint destination, int segments)
 {
     DrawQuadBezier(origin, control, destination, segments, DrawColor);
 }
Пример #7
0
        /// <summary>
        /// draws a cubic bezier path
        /// @since v0.8
        /// </summary>
        public static void DrawCubicBezier(CCPoint origin, CCPoint control1, CCPoint control2, CCPoint destination, int segments, CCColor4B color)
        {
            float t         = 0;
            float increment = 1.0f / segments;

            var vertices = new CCPoint[segments];

            vertices[0] = origin;

            for (int i = 1; i < segments; ++i, t += increment)
            {
                vertices[i].X = CCSplineMath.CubicBezier(origin.X, control1.X, control2.X, destination.X, t);
                vertices[i].Y = CCSplineMath.CubicBezier(origin.Y, control1.Y, control2.Y, destination.Y, t);
            }

            vertices[segments - 1] = destination;
            DrawPoly(vertices, color);
        }
Пример #8
0
        public static CCPhysicsJointDistance Construct(CCPhysicsBody a, CCPhysicsBody b, CCPoint anchr1, CCPoint anchr2)
        {
            CCPhysicsJointDistance joint = new CCPhysicsJointDistance();

            if (joint != null && joint.Init(a, b, PhysicsHelper.CCPointToCpVect(anchr1), PhysicsHelper.CCPointToCpVect(anchr2)))
            {
                return(joint);
            }
            return(null);
        }
Пример #9
0
        public static CCPhysicsJointSpring Construct(CCPhysicsBody a, CCPhysicsBody b, CCPoint anchr1, CCPoint anchr2, float stiffness, float damping)
        {
            CCPhysicsJointSpring joint = new CCPhysicsJointSpring();

            if (joint != null && joint.Init(a, b, anchr1, anchr2, stiffness, damping))
            {
                return(joint);
            }
            return(null);
        }
Пример #10
0
        // static PhysicsJointFixed* ruct(PhysicsBody* a, PhysicsBody* b,  cpVect anchr);

        #region PUBLIC FUNC

        public static CCPhysicsJointLimit Construct(CCPhysicsBody a, CCPhysicsBody b, CCPoint anchr1, CCPoint anchr2, float min, float max)
        {
            CCPhysicsJointLimit joint = new CCPhysicsJointLimit();

            if (joint != null && joint.Init(a, b, anchr1, anchr2, min, max))
            {
                return(joint);
            }

            return(null);
        }
Пример #11
0
 public static CCPhysicsJointLimit Construct(CCPhysicsBody a, CCPhysicsBody b, CCPoint anchr1, CCPoint anchr2)
 {
     return(Construct(a, b, anchr1, anchr2, 0,
                      cpVect.cpvdist(b.Local2World(PhysicsHelper.CCPointToCpVect(anchr1)), a.Local2World(PhysicsHelper.CCPointToCpVect(anchr2)))));
 }
Пример #12
0
        public static CCPhysicsJointFixed Construct(CCPhysicsBody a, CCPhysicsBody b, CCPoint anchr)
        {
            CCPhysicsJointFixed joint = new CCPhysicsJointFixed();

            if (joint != null && joint.Init(a, b, anchr))
            {
                return(joint);
            }

            // CC_SAFE_DELETE(joint);
            return(null);
        }
Пример #13
0
        void UpdateSpriteTextureQuads()
        {
            if (!Visible)
            {
                quad.BottomRight.Vertices =
                    quad.TopLeft.Vertices = quad.TopRight.Vertices = quad.BottomLeft.Vertices = new CCVertex3F(0, 0, 0);
            }
            else
            {
                CCPoint relativeOffset = unflippedOffsetPositionFromCenter;

                if (flipX)
                {
                    relativeOffset.X = -relativeOffset.X;
                }
                if (flipY)
                {
                    relativeOffset.Y = -relativeOffset.Y;
                }

                CCPoint centerPoint = UntrimmedSizeInPixels.Center + relativeOffset;
                CCPoint subRectOrigin;
                subRectOrigin.X = centerPoint.X - textureRectInPixels.Size.Width / 2.0f;
                subRectOrigin.Y = centerPoint.Y - textureRectInPixels.Size.Height / 2.0f;

                CCRect subRectRatio = CCRect.Zero;

                if (UntrimmedSizeInPixels.Width > 0 && UntrimmedSizeInPixels.Height > 0)
                {
                    subRectRatio = new CCRect(
                        subRectOrigin.X / UntrimmedSizeInPixels.Width,
                        subRectOrigin.Y / UntrimmedSizeInPixels.Height,
                        textureRectInPixels.Size.Width / UntrimmedSizeInPixels.Width,
                        textureRectInPixels.Size.Height / UntrimmedSizeInPixels.Height);
                }

                // Atlas: Vertex
                float x1 = subRectRatio.Origin.X * ContentSize.Width;
                float y1 = subRectRatio.Origin.Y * ContentSize.Height;
                float x2 = x1 + (subRectRatio.Size.Width * ContentSize.Width);
                float y2 = y1 + (subRectRatio.Size.Height * ContentSize.Height);

                // Don't set z-value: The node's transform will be set to include z offset
                quad.BottomLeft.Vertices  = new CCVertex3F(x1, y1, 0);
                quad.BottomRight.Vertices = new CCVertex3F(x2, y1, 0);
                quad.TopLeft.Vertices     = new CCVertex3F(x1, y2, 0);
                quad.TopRight.Vertices    = new CCVertex3F(x2, y2, 0);

                CCTexture2D tex = batchNode != null ? TextureAtlas.Texture : texture;
                if (tex == null)
                {
                    return;
                }

                float atlasWidth  = tex.PixelsWide;
                float atlasHeight = tex.PixelsHigh;

                float left, right, top, bottom;

                if (IsTextureRectRotated)
                {
                    #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
                    left   = (2 * textureRectInPixels.Origin.X + 1) / (2 * atlasWidth);
                    right  = left + (textureRectInPixels.Size.Height * 2 - 2) / (2 * atlasWidth);
                    top    = (2 * textureRectInPixels.Origin.Y + 1) / (2 * atlasHeight);
                    bottom = top + (textureRectInPixels.Size.Width * 2 - 2) / (2 * atlasHeight);
                    #else
                    left   = textureRectInPixels.Origin.X / atlasWidth;
                    right  = (textureRectInPixels.Origin.X + textureRectInPixels.Size.Height) / atlasWidth;
                    top    = textureRectInPixels.Origin.Y / atlasHeight;
                    bottom = (textureRectInPixels.Origin.Y + textureRectInPixels.Size.Width) / atlasHeight;
                    #endif

                    if (flipX)
                    {
                        CCMacros.CCSwap(ref top, ref bottom);
                    }

                    if (flipY)
                    {
                        CCMacros.CCSwap(ref left, ref right);
                    }

                    quad.BottomLeft.TexCoords.U  = left;
                    quad.BottomLeft.TexCoords.V  = top;
                    quad.BottomRight.TexCoords.U = left;
                    quad.BottomRight.TexCoords.V = bottom;
                    quad.TopLeft.TexCoords.U     = right;
                    quad.TopLeft.TexCoords.V     = top;
                    quad.TopRight.TexCoords.U    = right;
                    quad.TopRight.TexCoords.V    = bottom;
                }
                else
                {
                    #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
                    left   = (2 * textureRectInPixels.Origin.X + 1) / (2 * atlasWidth);
                    right  = left + (textureRectInPixels.Size.Width * 2 - 2) / (2 * atlasWidth);
                    top    = (2 * textureRectInPixels.Origin.Y + 1) / (2 * atlasHeight);
                    bottom = top + (textureRectInPixels.Size.Height * 2 - 2) / (2 * atlasHeight);
                    #else
                    left   = textureRectInPixels.Origin.X / atlasWidth;
                    right  = (textureRectInPixels.Origin.X + textureRectInPixels.Size.Width) / atlasWidth;
                    top    = textureRectInPixels.Origin.Y / atlasHeight;
                    bottom = (textureRectInPixels.Origin.Y + textureRectInPixels.Size.Height) / atlasHeight;
                    #endif

                    if (flipX)
                    {
                        CCMacros.CCSwap(ref left, ref right);
                    }

                    if (flipY)
                    {
                        CCMacros.CCSwap(ref top, ref bottom);
                    }

                    quad.BottomLeft.TexCoords.U  = left;
                    quad.BottomLeft.TexCoords.V  = bottom;
                    quad.BottomRight.TexCoords.U = right;
                    quad.BottomRight.TexCoords.V = bottom;
                    quad.TopLeft.TexCoords.U     = left;
                    quad.TopLeft.TexCoords.V     = top;
                    quad.TopRight.TexCoords.U    = right;
                    quad.TopRight.TexCoords.V    = top;
                }
            }

            UpdateTransformedSpriteTextureQuads();
        }
Пример #14
0
        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(
                        new CCSize(ow, oh),
                        texture,
                        new CCRect(x + ox, y + oy, w, h),
                        false
                        );
                }
                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);

                    frame.Origin += offset;

                    // create frame
                    spriteFrame = new CCSpriteFrame(sourceSize, texture, frame, rotated);
                }
                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("CocosSharp: WARNING: an alias with name {0} already exists", oneAlias);
                            }
                        }

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

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

                spriteFrame.TextureFilename = pair.Key;
                spriteFrames[pair.Key]      = spriteFrame;
            }
            AutoCreateAliasList();
        }
Пример #15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="center"></param>
 /// <param name="radius"></param>
 /// <param name="angle">The amount of the circle to draw, in radiians</param>
 /// <param name="segments"></param>
 /// <param name="drawLineToCenter"></param>
 /// <param name="color"></param>
 public static void DrawCircle(CCPoint center, float radius, float angle, int segments, bool drawLineToCenter, float scaleX = 1.0f, float scaleY = 1.0f)
 {
     DrawCircle(center, radius, angle, segments, drawLineToCenter, DrawColor, scaleX, scaleY);
 }
Пример #16
0
        public static CCPhysicsJointGroove Construct(CCPhysicsBody a, CCPhysicsBody b, CCPoint grooveA, CCPoint grooveB, CCPoint anchr2)
        {
            CCPhysicsJointGroove joint = new CCPhysicsJointGroove();

            if (joint != null && joint.Init(a, b, grooveA, grooveB, anchr2))
            {
                return(joint);
            }

            return(null);
        }
Пример #17
0
 public static void DrawSolidCircle(CCPoint center, float radius, float angle, int segments, float scaleX = 1.0f, float scaleY = 1.0f)
 {
     DrawSolidCircle(center, radius, angle, segments, DrawColor, scaleX, scaleY);
 }
Пример #18
0
 public void SetGrooveB(CCPoint grooveB)
 {
     _info.getJoints().FirstOrDefault().SetGrooveB(PhysicsHelper.CCPointToCpVect(grooveB));
 }
Пример #19
0
 public static void DrawCubicBezier(CCPoint origin, CCPoint control1, CCPoint control2, CCPoint destination, int segments)
 {
     DrawCubicBezier(origin, control1, control2, destination, segments, DrawColor);
 }
Пример #20
0
 public void SetAnchr2(CCPoint anchr2)
 {
     _info.getJoints().FirstOrDefault().SetAnchorB(PhysicsHelper.CCPointToCpVect(anchr2));
 }
Пример #21
0
 public static void DrawPoint(CCPoint point)
 {
     DrawPoint(point, PointSize, DrawColor);
 }
Пример #22
0
        protected bool Init(CCPhysicsBody a, CCPhysicsBody b, CCPoint grooveA, CCPoint grooveB, CCPoint anchr)
        {
            if (!base.Init(a, b))
            {
                return(false);
            }

            cpConstraint joint = new cpGrooveJoint(GetBodyInfo(a).Body,
                                                   GetBodyInfo(b).Body,
                                                   PhysicsHelper.CCPointToCpVect(grooveA),
                                                   PhysicsHelper.CCPointToCpVect(grooveB),
                                                   PhysicsHelper.CCPointToCpVect(anchr));


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

            _info.Add(joint);


            return(true);
        }
Пример #23
0
 public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset)
     : this(str, fntFile, width, alignment, imageOffset, null)
 {
 }
 /** Build an elliptical arc from its canonical geometrical elements.
  * @param center center of the ellipse
  * @param a semi-major axis
  * @param b semi-minor axis
  * @param theta orientation of the major axis with respect to the x axis
  * @param lambda1 start angle of the arc
  * @param lambda2 end angle of the arc
  * @param isPieSlice if true, the lines between the center of the ellipse
  * and the endpoints are part of the shape (it is pie slice like)
  */
 internal static void DrawEllipticalArc(CCPoint center, double a, double b,
                                        double theta, double lambda1, double lambda2,
                                        bool isPieSlice, CCColor4B color)
 {
     DrawEllipticalArc(center.X, center.Y, a, b, theta, lambda1, lambda2, isPieSlice, color);
 }
Пример #25
0
 public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                      CCPoint imageOffset, CCTexture2D texture)
     : this(str, fntFile, new CCSize(width, 0), hAlignment, vAlignment, imageOffset, texture)
 {
 }
        /** Build an approximation of the instance outline.
         * @param degree degree of the Bézier curve to use
         * @param threshold acceptable error
         */
        public static void drawEllipticalArcToContext(int degree, double threshold, CCColor4B color)
        {
            // find the number of Bézier curves needed
            bool found = false;
            int  n     = 1;

            while ((!found) && (n < 1024))
            {
                double dEta2 = (eta2 - eta1) / n;
                if (dEta2 <= 0.5 * Math.PI)
                {
                    double etaB2 = eta1;
                    found = true;
                    for (int i = 0; found && (i < n); ++i)
                    {
                        double etaA = etaB2;
                        etaB2 += dEta2;
                        found  = (estimateError(degree, etaA, etaB2) <= threshold);
                    }
                }
                n = n << 1;
            }

            double dEta = (eta2 - eta1) / n;
            double etaB = eta1;

            double cosEtaB  = Math.Cos(etaB);
            double sinEtaB  = Math.Sin(etaB);
            double aCosEtaB = a * cosEtaB;
            double bSinEtaB = b * sinEtaB;
            double aSinEtaB = a * sinEtaB;
            double bCosEtaB = b * cosEtaB;
            double xB       = cx + aCosEtaB * cosTheta - bSinEtaB * sinTheta;
            double yB       = cy + aCosEtaB * sinTheta + bSinEtaB * cosTheta;
            double xBDot    = -aSinEtaB * cosTheta - bCosEtaB * sinTheta;
            double yBDot    = -aSinEtaB * sinTheta + bCosEtaB * cosTheta;

            CCPoint startPoint = CCPoint.Zero;
            CCPoint piePoint   = CCPoint.Zero;

            if (isPieSlice)
            {
                startPoint.X = (float)cx;
                startPoint.Y = (float)cy;
                piePoint.X   = (float)cx;
                piePoint.Y   = (float)cy;
            }
            else
            {
                startPoint.X = (float)xB;
                startPoint.Y = (float)yB;
            }

            double t     = Math.Tan(0.5 * dEta);
            double alpha = Math.Sin(dEta) * (Math.Sqrt(4 + 3 * t * t) - 1) / 3;

            CCPoint destinationPoint = CCPoint.Zero;
            CCPoint controlPoint1    = CCPoint.Zero;
            CCPoint controlPoint2    = CCPoint.Zero;

            for (int i = 0; i < n; ++i)
            {
                //double etaA = etaB;
                double xA    = xB;
                double yA    = yB;
                double xADot = xBDot;
                double yADot = yBDot;

                etaB    += dEta;
                cosEtaB  = Math.Cos(etaB);
                sinEtaB  = Math.Sin(etaB);
                aCosEtaB = a * cosEtaB;
                bSinEtaB = b * sinEtaB;
                aSinEtaB = a * sinEtaB;
                bCosEtaB = b * cosEtaB;
                xB       = cx + aCosEtaB * cosTheta - bSinEtaB * sinTheta;
                yB       = cy + aCosEtaB * sinTheta + bSinEtaB * cosTheta;
                xBDot    = -aSinEtaB * cosTheta - bCosEtaB * sinTheta;
                yBDot    = -aSinEtaB * sinTheta + bCosEtaB * cosTheta;

                destinationPoint.X = (float)xB;
                destinationPoint.Y = (float)yB;

                if (degree == 1)
                {
                    DrawLine(startPoint, destinationPoint, color);
                }
                else if (degree == 2)
                {
                    double k = (yBDot * (xB - xA) - xBDot * (yB - yA))
                               / (xADot * yBDot - yADot * xBDot);

                    controlPoint1.X = (float)(xA + k * xADot);
                    controlPoint1.Y = (float)(yA + k * yADot);

                    DrawQuadBezier(startPoint, controlPoint1, destinationPoint, SEGMENTS, color);
                }
                else
                {
                    controlPoint1.X = (float)(xA + alpha * xADot);
                    controlPoint1.Y = (float)(yA + alpha * yADot);

                    controlPoint2.X = (float)(xB - alpha * xBDot);
                    controlPoint2.Y = (float)(yB - alpha * yBDot);


                    DrawCubicBezier(startPoint, controlPoint1, controlPoint2, destinationPoint, SEGMENTS, color);
                }

                startPoint.X = (float)xB;
                startPoint.Y = (float)yB;
            }

            if (isPieSlice)
            {
                DrawLine(piePoint, destinationPoint, color);
            }
        }
Пример #27
0
        protected void InitCCLabelBMFont(string theString, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment,
                                         CCPoint imageOffset, CCTexture2D texture)
        {
            Debug.Assert(FontConfiguration == 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;
                }

                FontConfiguration = newConf;

                fntConfigFile = fntFile;

                if (texture == null)
                {
                    try
                    {
                        texture = CCTextureCache.SharedTextureCache.AddImage(FontConfiguration.AtlasName);
                    }
                    catch (Exception)
                    {
                        // Try the 'images' ref location just in case.
                        try
                        {
                            texture =
                                CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images",
                                                                                                  FontConfiguration
                                                                                                  .AtlasName));
                        }
                        catch (Exception)
                        {
                            // Lastly, try <font_path>/images/<font_name>
                            string dir     = System.IO.Path.GetDirectoryName(FontConfiguration.AtlasName);
                            string fname   = System.IO.Path.GetFileName(FontConfiguration.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;
            }

            TextureAtlas = new CCTextureAtlas(texture, theString.Length);

            this.labelDimensions = dimensions;

            horzAlignment = hAlignment;
            vertAlignment = vAlignment;

            IsOpacityCascaded = true;

            ContentSize = CCSize.Zero;

            IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha;
            AnchorPoint = CCPoint.AnchorMiddle;

            ImageOffset = imageOffset;

            SetString(theString, true);
        }
Пример #28
0
 public static void DrawLine(CCPoint origin, CCPoint destination)
 {
     DrawLine(origin, destination, DrawColor);
 }
Пример #29
0
        public void OnInterfaceMoveLocation(float x, float y, CCNode container)
        {
            var tmp_position = new CCPoint(x, y);

            UpdatePositionLocation(tmp_position, container);
        }
Пример #30
0
        ///
        //    Update does the work of mapping the texture onto the triangles
        //    It now doesn't occur the cost of free/alloc data every update cycle.
        //    It also only changes the percentage point but no other points if they have not
        //    been modified.
        //
        //    It now deals with flipped texture. If you run into this problem, just use the
        //    sprite property and enable the methods flipX, flipY.
        ///
        void UpdateRadial()
        {
            if (Sprite == null)
            {
                return;
            }

            float alpha = Percentage / 100f;

            float angle = 2f * (MathHelper.Pi) * (ReverseDirection ? alpha : 1.0f - alpha);

            //    We find the vector to do a hit detection based on the percentage
            //    We know the first vector is the one @ 12 o'clock (top,mid) so we rotate
            //    from that by the progress angle around the m_tMidpoint pivot
            var     topMid       = new CCPoint(Midpoint.X, 1f);
            CCPoint percentagePt = CCPoint.RotateByAngle(topMid, Midpoint, angle);


            int     index = 0;
            CCPoint hit;

            if (alpha == 0f)
            {
                //    More efficient since we don't always need to check intersection
                //    If the alpha is zero then the hit point is top mid and the index is 0.
                hit   = topMid;
                index = 0;
            }
            else if (alpha == 1f)
            {
                //    More efficient since we don't always need to check intersection
                //    If the alpha is one then the hit point is top mid and the index is 4.
                hit   = topMid;
                index = 4;
            }
            else
            {
                //    We run a for loop checking the edges of the texture to find the
                //    intersection point
                //    We loop through five points since the top is split in half

                float min_t = float.MaxValue;

                for (int i = 0; i <= ProgressTextureCoordsCount; ++i)
                {
                    int pIndex = (i + (ProgressTextureCoordsCount - 1)) % ProgressTextureCoordsCount;

                    CCPoint edgePtA = BoundaryTexCoord(i % ProgressTextureCoordsCount);
                    CCPoint edgePtB = BoundaryTexCoord(pIndex);

                    //    Remember that the top edge is split in half for the 12 o'clock position
                    //    Let's deal with that here by finding the correct endpoints
                    if (i == 0)
                    {
                        edgePtB = CCPoint.Lerp(edgePtA, edgePtB, 1 - Midpoint.X);
                    }
                    else if (i == 4)
                    {
                        edgePtA = CCPoint.Lerp(edgePtA, edgePtB, 1 - Midpoint.X);
                    }

                    //    s and t are returned by ccpLineIntersect
                    float s = 0, t = 0;
                    if (CCPoint.LineIntersect(edgePtA, edgePtB, Midpoint, percentagePt, ref s, ref t))
                    {
                        //    Since our hit test is on rays we have to deal with the top edge
                        //    being in split in half so we have to test as a segment
                        if ((i == 0 || i == 4))
                        {
                            //    s represents the point between edgePtA--edgePtB
                            if (!(0f <= s && s <= 1f))
                            {
                                continue;
                            }
                        }
                        //    As long as our t isn't negative we are at least finding a
                        //    correct hitpoint from m_tMidpoint to percentagePt.
                        if (t >= 0f)
                        {
                            //    Because the percentage line and all the texture edges are
                            //    rays we should only account for the shortest intersection
                            if (t < min_t)
                            {
                                min_t = t;
                                index = i;
                            }
                        }
                    }
                }

                //    Now that we have the minimum magnitude we can use that to find our intersection
                hit = Midpoint + ((percentagePt - Midpoint) * min_t);
            }


            //    The size of the vertex data is the index from the hitpoint
            //    the 3 is for the m_tMidpoint, 12 o'clock point and hitpoint position.

            bool sameIndexCount = true;

            if (vertexData != null && vertexData.Length != index + 3)
            {
                sameIndexCount = false;
                vertexData     = null;
            }

            if (vertexData == null)
            {
                sameIndexCount = false;
                vertexData     = new CCV3F_C4B_T2F[index + 3];
            }

            if (!sameIndexCount)
            {
                //    First we populate the array with the m_tMidpoint, then all
                //    vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint
                vertexData[0].TexCoords = TextureCoordFromAlphaPoint(Midpoint);
                vertexData[0].Vertices  = VertexFromAlphaPoint(Midpoint);

                vertexData[1].TexCoords = TextureCoordFromAlphaPoint(topMid);
                vertexData[1].Vertices  = VertexFromAlphaPoint(topMid);

                for (int i = 0; i < index; ++i)
                {
                    CCPoint alphaPoint = BoundaryTexCoord(i);
                    vertexData[i + 2].TexCoords = TextureCoordFromAlphaPoint(alphaPoint);
                    vertexData[i + 2].Vertices  = VertexFromAlphaPoint(alphaPoint);
                }
            }

            // hitpoint will go last
            vertexData[vertexData.Length - 1].TexCoords = TextureCoordFromAlphaPoint(hit);
            vertexData[vertexData.Length - 1].Vertices  = VertexFromAlphaPoint(hit);
        }