/// <summary> /// Creates a new quad tree broadphase with the specified span. /// </summary> /// <param name="span">the maximum span of the tree (world size)</param> public QuadTreeBroadPhase(AABB span) { _quadTree = new QuadTree<FixtureProxy>(span, 5, 10); _idRegister = new Dictionary<int, Element<FixtureProxy>>(); _moveBuffer = new CCRawList<Element<FixtureProxy>>(); _pairBuffer = new List<Pair>(); }
public CCGeometryNode(int bufferSize=DefaultBufferSize) { geomRenderCommand = new CCCustomCommand(RenderBatch); indicesArray = new CCRawList<short>(bufferSize * 2); verticesArray = new CCRawList<CCV3F_C4B_T2F>(bufferSize); batchItemList = new CCRawList<CCGeometryInstance>(bufferSize); }
public DrawNodeBuffer() { TriangleVertices = new CCRawList<CCV3F_C4B>(DefaultBufferSize); LineVertices = new CCRawList<CCV3F_C4B>(DefaultBufferSize); Color = CCColor3B.White; Opacity = 255; }
public override bool Init() { base.Init(); m_sBlendFunc = CCBlendFunc.AlphaBlend; m_pVertices = new CCRawList<VertexPositionColor>(512); return true; }
private string CreateFont(string fontName, float fontSize, CCRawList<char> charset) { if (_defaultFont == null) { _defaultFont = new Font(FontFamily.GenericSansSerif, 12); } FontFamily fontFamily; if (!_fontFamilyCache.TryGetValue(fontName, out fontFamily)) { var ext = Path.GetExtension(fontName); _currentFont = _defaultFont; if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { var appPath = AppDomain.CurrentDomain.BaseDirectory; var contentPath = Path.Combine(appPath, CCApplication.SharedApplication.Content.RootDirectory); var fontPath = Path.Combine(contentPath, fontName); if (File.Exists(fontPath)) { try { _loadedFonts.AddFontFile(fontPath); fontFamily = _loadedFonts.Families[_loadedFonts.Families.Length - 1]; _currentFont = new Font(fontFamily, fontSize); } catch { _currentFont = _defaultFont; } } } else { _currentFont = new Font(fontName, fontSize); } _fontFamilyCache.Add(fontName, _currentFont.FontFamily); } else { _currentFont = new Font(fontFamily, fontSize); } GetKerningInfo(charset); CreateBitmap(1, 1); return _currentFont.Name; }
/* * init with CCTexture2D */ public bool InitWithTexture(CCTexture2D tex, int capacity) { TextureAtlas.InitWithTexture(tex, capacity); // no lazy alloc in this node m_pChildren = new CCRawList<CCNode>(capacity); m_tBlendFunc = CCBlendFunc.AlphaBlend; return true; }
internal CCRenderer(CCDrawManager drawManager) { DrawManager = drawManager; RenderQueue = new RenderQueue<CCRenderQueueId, CCRenderCommand>(); quads = new CCRawList<CCV3F_C4B_T2F_Quad>(); batchCommands = new List<CCRenderCommand>(BATCH_QUADCOMMAND_RESEVER_SIZE); batchQuadCommands = new List<CCQuadCommand>(BATCH_QUADCOMMAND_RESEVER_SIZE); }
public CCDrawNode() { renderTriangles = new CCCustomCommand(FlushTriangles); renderLines = new CCCustomCommand(FlushLines); renderStrings = new CCCustomCommand(DrawStrings); BlendFunc = CCBlendFunc.AlphaBlend; triangleVertices = new CCRawList<CCV3F_C4B>(DefaultBufferSize); lineVertices = new CCRawList<CCV3F_C4B>(DefaultBufferSize); verticeBounds = CCRect.Zero; }
internal CCRenderer(CCDrawManager drawManagerIn) { currentBatchedQuads = new CCRawList<CCV3F_C4B_T2F_Quad>(256, true); quadCommands = new CCRawList<CCQuadCommand>(256, true); renderQueue = new CCRawList<CCRenderCommand>(); drawManager = drawManagerIn; viewportGroupStack = new Viewport[MaxStackDepth]; layerGroupViewMatrixStack = new Matrix[MaxStackDepth]; layerGroupProjMatrixStack = new Matrix[MaxStackDepth]; viewportGroupIdStack = new byte[MaxStackDepth]; layerGroupIdStack = new byte[MaxStackDepth]; groupIdStack = new byte[MaxStackDepth]; }
/* * init with CCTexture2D */ public bool InitWithTexture(CCTexture2D tex, int capacity) { TextureAtlas.InitWithTexture(tex, capacity); // no lazy alloc in this node m_pChildren = new CCRawList<CCNode>(capacity); m_tBlendFunc.Source = CCMacros.CCDefaultSourceBlending; m_tBlendFunc.Destination = CCMacros.CCDefaultDestinationBlending; //setShaderProgram(CCShaderCache::sharedShaderCache().programForKey(kCCShader_PositionTextureColor)); return true; }
public CCSpriteBatchNode(CCTexture2D tex, int capacity=defaultSpriteBatchCapacity) { BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } TextureAtlas = new CCTextureAtlas(tex, capacity); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); }
internal CCPrimitiveBatch(CCDrawManager drawManager, int bufferSize=DefaultBufferSize) { DrawManager = drawManager; if (drawManager.XnaGraphicsDevice == null) { throw new ArgumentNullException("graphicsDevice"); } triangleVertices = new CCV3F_C4B[bufferSize - bufferSize % 3]; lineVertices = new CCV3F_C4B[bufferSize - bufferSize % 2]; triangleVerts = new CCRawList<CCV3F_C4B[]>(100, true); lineVerts = new CCRawList<CCV3F_C4B[]>(100, true); }
private void CreateFont(string fontName, float fontSize, CCRawList<char> charset) { _font = CCLabelUtilities.CreateFont (fontName, fontSize); var value = new CCLabelUtilities.ABCFloat[1]; _abcValues.Clear();; for (int i = 0; i < charset.Count; i++) { var ch = charset[i]; CCLabelUtilities.GetCharABCWidthsFloat(ch, _font, out value); _abcValues.Add(ch, new KerningInfo() { A = value[0].abcfA, B = value[0].abcfB, C = value[0].abcfC }); } }
private void CreateFont(string fontName, float fontSize, CCRawList<char> charset) { if (_paint == null) { var display = Game.Activity.WindowManager.DefaultDisplay; var metrics = new DisplayMetrics(); display.GetMetrics(metrics); _fontScaleFactor = metrics.ScaledDensity; _paint = new Paint(PaintFlags.AntiAlias); _paint.Color = Android.Graphics.Color.White; _paint.TextAlign = Paint.Align.Left; // _paint.LinearText = true; } _paint.TextSize = fontSize; var ext = System.IO.Path.GetExtension(fontName); if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { var path = System.IO.Path.Combine(CCContentManager.SharedContentManager.RootDirectory, fontName); var activity = Game.Activity; try { var typeface = Typeface.CreateFromAsset(activity.Assets, path); _paint.SetTypeface(typeface); } catch (Exception) { _paint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal)); } } else { _paint.SetTypeface(Typeface.Create(fontName, TypefaceStyle.Normal)); } _fontMetrix = _paint.GetFontMetrics(); }
internal Body() { FixtureList = new CCRawList<Fixture>(32); }
public Body(World world, object userData) { FixtureList = new CCRawList<Fixture>(32); BodyId = _bodyIdCounter++; World = world; UserData = userData; FixedRotation = false; IsBullet = false; SleepingAllowed = true; Awake = true; BodyType = BodyType.Static; Enabled = true; Xf.R.Set(0); world.AddBody(this); }
public CCDrawNode() { BlendFunc = CCBlendFunc.AlphaBlend; triangleVertices = new CCRawList<VertexPositionColor>(DefaultBufferSize); lineVertices = new CCRawList<VertexPositionColor>(DefaultBufferSize); }
protected virtual bool InitWithTexture(CCTexture2D tex, int capacity) { m_blendFunc = CCBlendFunc.AlphaBlend; m_pobTextureAtlas = new CCTextureAtlas(); if (capacity == 0) { capacity = kDefaultSpriteBatchCapacity; } ContentSize= tex.ContentSize; // @@ TotallyEvil - contentSize should return the size of the sprite sheet m_pobTextureAtlas.InitWithTexture(tex, capacity); UpdateBlendFunc(); // no lazy alloc in this node m_pChildren = new CCRawList<CCNode>(capacity); m_pobDescendants = new CCRawList<CCSprite>(capacity); return true; }
private static void GetKerningInfo(CCRawList<char> charset) { _abcValues.Clear(); var fontFace = new FontFace(_currentFont); var value = new ABCFloat[1]; var glyphRun = new GlyphRun(); glyphRun.FontFace = fontFace; glyphRun.FontSize = _currentDIP; var BrushColor = SharpDX.Color.White; /* SharpDX.DirectWrite.Matrix mtrx = new SharpDX.DirectWrite.Matrix(); mtrx.M11 = 1F; mtrx.M12 = 0; mtrx.M21 = 0; mtrx.M22 = 1F; mtrx.Dx = 0; mtrx.Dy = 0; */ //GlyphMetrics[] metrics = fontFace.GetGdiCompatibleGlyphMetrics(23, 1, mtrx, false, glyphIndices, false); //FontMetrics metr = fontFace.GetGdiCompatibleMetrics(23, 1, new SharpDX.DirectWrite.Matrix()); //_pRenderTarget.DrawGlyphRun(new SharpDX.DrawingPointF(left, top), glyphRun, new SharpDX.Direct2D1.SolidColorBrush(_pRenderTarget, BrushColor), MeasuringMode.GdiClassic); int[] codePoints = new int[1]; var unitsPerEm = fontFace.Metrics.DesignUnitsPerEm; var familyName = _currentFont.ToString(); for (int i = 0; i < charset.Count; i++) { var ch = charset[i]; if (!_abcValues.ContainsKey(ch)) { var textLayout = new TextLayout(FactoryDWrite, ch.ToString(), textFormat, unitsPerEm, unitsPerEm); var tlMetrics = textLayout.Metrics; var tlmWidth = tlMetrics.Width; var tllWidth = tlMetrics.LayoutWidth; codePoints[0] = (int)ch; short[] glyphIndices = fontFace.GetGlyphIndices(codePoints); glyphRun.Indices = glyphIndices; var metrics = fontFace.GetDesignGlyphMetrics(glyphIndices, false); //var width = metrics[0].AdvanceWidth + metrics[0].LeftSideBearing + metrics[0].RightSideBearing; //var glyphWidth = _currentFontSizeEm * (float)metrics[0].AdvanceWidth / unitsPerEm; //var abcWidth = _currentDIP * (float)width / unitsPerEm; //value[0].abcfA = _currentFontSizeEm * (float)metrics[0].LeftSideBearing / unitsPerEm; //value[0].abcfB = _currentFontSizeEm * (float)metrics[0].AdvanceWidth / unitsPerEm; //value[0].abcfC = _currentFontSizeEm * (float)metrics[0].RightSideBearing / unitsPerEm; // The A and C values are throwing the spacing off //value[0].abcfA = _currentDIP * (float)metrics[0].LeftSideBearing / unitsPerEm; value[0].abcfB = _currentDIP * (float)metrics[0].AdvanceWidth / unitsPerEm; //value[0].abcfC = _currentDIP * (float)metrics[0].RightSideBearing / unitsPerEm; _abcValues.Add( ch, new KerningInfo() { A = value[0].abcfA, B = value[0].abcfB, C = value[0].abcfC }); } } }
// don't use lazy sorting, reordering the particle systems quads afterwards would be too complex // XXX research whether lazy sorting + freeing current quads and calloc a new block with size of capacity would be faster // XXX or possibly using vertexZ for reordering, that would be fastest // this helper is almost equivalent to CCNode's addChild, but doesn't make use of the lazy sorting private int AddChildHelper(CCParticleSystem child, int z, int aTag) { Debug.Assert(child != null, "Argument must be non-nil"); Debug.Assert(child.Parent == null, "child already added. It can't be added again"); if (m_pChildren == null) { m_pChildren = new CCRawList<CCNode>(4); } //don't use a lazy insert int pos = SearchNewPositionInChildrenForZ(z); m_pChildren.Insert(pos, child); child.Parent = this; child.Tag = aTag; child.m_nZOrder = z; if (m_bRunning) { child.OnEnter(); child.OnEnterTransitionDidFinish(); } return pos; }
protected void UpdateLabel() { SetString(m_sInitialString, false); if (m_sString == null) { return; } if (m_tDimensions.Width > 0) { // Step 1: Make multiline string str_whole = m_sString; int stringLength = str_whole.Length; var multiline_string = new StringBuilder(stringLength); var last_word = new StringBuilder(stringLength); int line = 1, i = 0; bool start_line = false, start_word = false; float startOfLine = -1, startOfWord = -1; int skip = 0; CCRawList<CCNode> children = m_pChildren; for (int j = 0; j < children.count; j++) { CCSprite characterSprite; int justSkipped = 0; while ((characterSprite = (CCSprite) GetChildByTag(j + skip + justSkipped)) == null) { justSkipped++; } skip += justSkipped; if (!characterSprite.Visible) { continue; } if (i >= stringLength) { break; } char character = str_whole[i]; if (!start_word) { startOfWord = GetLetterPosXLeft(characterSprite); start_word = true; } if (!start_line) { startOfLine = startOfWord; start_line = true; } // Newline. if (character == '\n') { int len = last_word.Length; while (len > 0 && Char.IsWhiteSpace(last_word[len - 1])) { len--; last_word.Remove(len, 1); } multiline_string.Append(last_word); multiline_string.Append('\n'); #if XBOX || XBOX360 last_word.Length = 0; #else last_word.Clear(); #endif start_word = false; start_line = false; startOfWord = -1; startOfLine = -1; i += justSkipped; line++; if (i >= stringLength) break; character = str_whole[i]; if (startOfWord == 0) { startOfWord = GetLetterPosXLeft(characterSprite); start_word = true; } if (startOfLine == 0) { startOfLine = startOfWord; start_line = true; } } // Whitespace. if (Char.IsWhiteSpace(character)) { last_word.Append(character); multiline_string.Append(last_word); #if XBOX || XBOX360 last_word.Length = 0; #else last_word.Clear(); #endif start_word = false; startOfWord = -1; i++; continue; } // Out of bounds. if (GetLetterPosXRight(characterSprite) - startOfLine > m_tDimensions.Width) { if (!m_bLineBreakWithoutSpaces) { last_word.Append(character); int len = multiline_string.Length; while (len > 0 && Char.IsWhiteSpace(multiline_string[len - 1])) { len--; multiline_string.Remove(len, 1); } if (multiline_string.Length > 0) { multiline_string.Append('\n'); } line++; start_line = false; startOfLine = -1; i++; } else { int len = last_word.Length; while (len > 0 && Char.IsWhiteSpace(last_word[len - 1])) { len--; last_word.Remove(len, 1); } multiline_string.Append(last_word); multiline_string.Append('\n'); #if XBOX || XBOX360 last_word.Length = 0; #else last_word.Clear(); #endif start_word = false; start_line = false; startOfWord = -1; startOfLine = -1; line++; if (i >= stringLength) break; if (startOfWord == 0) { startOfWord = GetLetterPosXLeft(characterSprite); start_word = true; } if (startOfLine == 0) { startOfLine = startOfWord; start_line = true; } j--; } continue; } else { // Character is normal. last_word.Append(character); i++; continue; } } multiline_string.Append(last_word); SetString(multiline_string.ToString(), false); } // Step 2: Make alignment if (m_pHAlignment != CCTextAlignment.Left) { int i = 0; int lineNumber = 0; int str_len = m_sString.Length; var last_line = new CCRawList<char>(); for (int ctr = 0; ctr <= str_len; ++ctr) { if (ctr == str_len || m_sString[ctr] == '\n') { float lineWidth = 0.0f; int line_length = last_line.Count; // if last line is empty we must just increase lineNumber and work with next line if (line_length == 0) { lineNumber++; continue; } int index = i + line_length - 1 + lineNumber; if (index < 0) continue; var lastChar = (CCSprite) GetChildByTag(index); if (lastChar == null) continue; lineWidth = lastChar.Position.X + lastChar.ContentSize.Width / 2.0f; float shift = 0; switch (m_pHAlignment) { case CCTextAlignment.Center: shift = ContentSize.Width / 2.0f - lineWidth / 2.0f; break; case CCTextAlignment.Right: shift = ContentSize.Width - lineWidth; break; default: break; } if (shift != 0) { for (int j = 0; j < line_length; j++) { index = i + j + lineNumber; if (index < 0) continue; var characterSprite = (CCSprite) GetChildByTag(index); characterSprite.Position = characterSprite.Position + new CCPoint(shift, 0.0f); } } i += line_length; lineNumber++; last_line.Clear(); continue; } last_line.Add(m_sString[ctr]); } } if (m_pVAlignment != CCVerticalTextAlignment.Bottom && m_tDimensions.Height > 0) { int lineNumber = 1; int str_len = m_sString.Length; for (int ctr = 0; ctr < str_len; ++ctr) { if (m_sString[ctr] == '\n') { lineNumber++; } } float yOffset = 0; if (m_pVAlignment == CCVerticalTextAlignment.Center) { yOffset = m_tDimensions.Height / 2f - (m_pConfiguration.m_nCommonHeight * lineNumber) / 2f; } else { yOffset = m_tDimensions.Height - m_pConfiguration.m_nCommonHeight * lineNumber; } for (int i = 0; i < str_len; i++) { var characterSprite = GetChildByTag(i); characterSprite.PositionY += yOffset; } } }
private static void GetKerningInfo(CCRawList<char> charset) { _abcValues.Clear(); var hDC = CreateCompatibleDC(IntPtr.Zero); var hFont = _currentFont.ToHfont(); SelectObject(hDC, hFont); var value = new ABCFloat[1]; for (int i = 0; i < charset.Count; i++) { var ch = charset[i]; if (!_abcValues.ContainsKey(ch)) { GetCharABCWidthsFloat(hDC, ch, ch, value); _abcValues.Add( ch, new KerningInfo() { A = value[0].abcfA, B = value[0].abcfB, C = value[0].abcfC }); } } DeleteObject(hFont); ReleaseDC(IntPtr.Zero, hDC); }
public CCParticleBatchNode(CCTexture2D tex, int capacity = ParticleDefaultCapacity) { BlendFunc = CCBlendFunc.AlphaBlend; TextureAtlas = new CCTextureAtlas(tex, capacity); Children = new CCRawList<CCNode>(capacity); }
/** * Returns the CCInvocation list for the given control event. If the list does * not exist, it'll create an empty array before returning it. * * @param controlEvent A control events for which the action message is sent. * See "CCControlEvent" for constants. * * @return the CCInvocation list for the given control event. */ //<CCInvocation*> protected CCRawList<CCInvocation> DispatchListforControlEvent(CCControlEvent controlEvent) { CCRawList<CCInvocation> invocationList; if (!dispatchTable.TryGetValue(controlEvent, out invocationList)) { invocationList = new CCRawList<CCInvocation>(1); dispatchTable.Add(controlEvent, invocationList); } return invocationList; }
/// <summary> /// This makes the explosive explode /// </summary> /// <param name="pos"> /// The position where the explosion happens /// </param> /// <param name="radius"> /// The explosion radius /// </param> /// <param name="maxForce"> /// The explosion force at the explosion point /// (then is inversely proportional to the square of the distance) /// </param> /// <returns> /// A dictionnary containing all the "exploded" fixtures /// with a list of the applied impulses /// </returns> public Dictionary <Fixture, List <Vector2> > Activate(Vector2 pos, float radius, float maxForce) { _exploded.Clear(); AABB aabb = new AABB(pos + new Vector2(-radius, -radius), pos + new Vector2(radius, radius)); Fixture[] shapes = new Fixture[MaxShapes]; // More than 5 shapes in an explosion could be possible, but still strange. Fixture[] containedShapes = new Fixture[5]; bool exit = false; int shapeCount = 0; int containedShapeCount = 0; // Query the world for overlapping shapes. World.QueryAABB( fixture => { if (fixture.TestPoint(ref pos)) { if (IgnoreWhenInsideShape) { exit = true; } else { containedShapes[containedShapeCount++] = fixture; } } else { shapes[shapeCount++] = fixture; } // Continue the query. return(true); }, ref aabb); if (exit) { return(_exploded); } // Per shape max/min angles for now. float[] vals = new float[shapeCount * 2]; int valIndex = 0; for (int i = 0; i < shapeCount; ++i) { PolygonShape ps; CircleShape cs = shapes[i].Shape as CircleShape; if (cs != null) { // We create a "diamond" approximation of the circle Vertices v = new Vertices(); Vector2 vec = Vector2.Zero + new Vector2(cs.Radius, 0); v.Add(vec); vec = Vector2.Zero + new Vector2(0, cs.Radius); v.Add(vec); vec = Vector2.Zero + new Vector2(-cs.Radius, cs.Radius); v.Add(vec); vec = Vector2.Zero + new Vector2(0, -cs.Radius); v.Add(vec); ps = new PolygonShape(v, 0); } else { ps = shapes[i].Shape as PolygonShape; } if ((shapes[i].Body.BodyType == BodyType.Dynamic) && ps != null) { Vector2 toCentroid = shapes[i].Body.GetWorldPoint(ps.MassData.Centroid) - pos; float angleToCentroid = (float)Math.Atan2(toCentroid.Y, toCentroid.X); float min = float.MaxValue; float max = float.MinValue; float minAbsolute = 0.0f; float maxAbsolute = 0.0f; for (int j = 0; j < (ps.Vertices.Count()); ++j) { Vector2 toVertex = (shapes[i].Body.GetWorldPoint(ps.Vertices[j]) - pos); float newAngle = (float)Math.Atan2(toVertex.Y, toVertex.X); float diff = (newAngle - angleToCentroid); diff = (diff - MathHelper.Pi) % (2 * MathHelper.Pi); // the minus pi is important. It means cutoff for going other direction is at 180 deg where it needs to be if (diff < 0.0f) { diff += 2 * MathHelper.Pi; // correction for not handling negs } diff -= MathHelper.Pi; if (Math.Abs(diff) > MathHelper.Pi) { throw new ArgumentException("OMG!"); } // Something's wrong, point not in shape but exists angle diff > 180 if (diff > max) { max = diff; maxAbsolute = newAngle; } if (diff < min) { min = diff; minAbsolute = newAngle; } } vals[valIndex] = minAbsolute; ++valIndex; vals[valIndex] = maxAbsolute; ++valIndex; } } Array.Sort(vals, 0, valIndex, _rdc); _data.Clear(); bool rayMissed = true; for (int i = 0; i < valIndex; ++i) { Fixture shape = null; float midpt; int iplus = (i == valIndex - 1 ? 0 : i + 1); if (vals[i] == vals[iplus]) { continue; } if (i == valIndex - 1) { // the single edgecase midpt = (vals[0] + MathHelper.Pi * 2 + vals[i]); } else { midpt = (vals[i + 1] + vals[i]); } midpt = midpt / 2; Vector2 p1 = pos; Vector2 p2 = radius * new Vector2((float)Math.Cos(midpt), (float)Math.Sin(midpt)) + pos; // RaycastOne bool hitClosest = false; World.RayCast((f, p, n, fr) => { Body body = f.Body; if (!IsActiveOn(body)) { return(0); } if (body.UserData != null) { int index = (int)body.UserData; if (index == 0) { // filter return(-1.0f); } } hitClosest = true; shape = f; return(fr); }, p1, p2); //draws radius points if ((hitClosest) && (shape.Body.BodyType == BodyType.Dynamic)) { if ((_data.Count() > 0) && (_data.Last().Body == shape.Body) && (!rayMissed)) { int laPos = _data.Count - 1; ShapeData la = _data[laPos]; la.Max = vals[iplus]; _data[laPos] = la; } else { // make new ShapeData d; d.Body = shape.Body; d.Min = vals[i]; d.Max = vals[iplus]; _data.Add(d); } if ((_data.Count() > 1) && (i == valIndex - 1) && (_data.Last().Body == _data.First().Body) && (_data.Last().Max == _data.First().Min)) { ShapeData fi = _data[0]; fi.Min = _data.Last().Min; _data.RemoveAt(_data.Count() - 1); _data[0] = fi; while (_data.First().Min >= _data.First().Max) { fi.Min -= MathHelper.Pi * 2; _data[0] = fi; } } int lastPos = _data.Count - 1; ShapeData last = _data[lastPos]; while ((_data.Count() > 0) && (_data.Last().Min >= _data.Last().Max)) // just making sure min<max { last.Min = _data.Last().Min - 2 * MathHelper.Pi; _data[lastPos] = last; } rayMissed = false; } else { rayMissed = true; // raycast did not find a shape } } for (int i = 0; i < _data.Count(); ++i) { if (!IsActiveOn(_data[i].Body)) { continue; } float arclen = _data[i].Max - _data[i].Min; float first = MathHelper.Min(MaxEdgeOffset, EdgeRatio * arclen); int insertedRays = (int)Math.Ceiling(((arclen - 2.0f * first) - (MinRays - 1) * MaxAngle) / MaxAngle); if (insertedRays < 0) { insertedRays = 0; } float offset = (arclen - first * 2.0f) / ((float)MinRays + insertedRays - 1); //Note: This loop can go into infinite as it operates on floats. //Added FloatEquals with a large epsilon. for (float j = _data[i].Min + first; j < _data[i].Max || MathUtils.FloatEquals(j, _data[i].Max, 0.0001f); j += offset) { Vector2 p1 = pos; Vector2 p2 = pos + radius * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)); Vector2 hitpoint = Vector2.Zero; float minlambda = float.MaxValue; CCRawList <Fixture> fl = _data[i].Body.FixtureList; for (int x = 0; x < fl.Count; x++) { Fixture f = fl[x]; RayCastInput ri; ri.Point1 = p1; ri.Point2 = p2; ri.MaxFraction = 50f; RayCastOutput ro; if (f.RayCast(out ro, ref ri, 0)) { if (minlambda > ro.Fraction) { minlambda = ro.Fraction; hitpoint = ro.Fraction * p2 + (1 - ro.Fraction) * p1; } } // the force that is to be applied for this particular ray. // offset is angular coverage. lambda*length of segment is distance. float impulse = (arclen / (MinRays + insertedRays)) * maxForce * 180.0f / MathHelper.Pi * (1.0f - Math.Min(1.0f, minlambda)); // We Apply the impulse!!! Vector2 vectImp = Vector2.Dot(impulse * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)), -ro.Normal) * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)); _data[i].Body.ApplyLinearImpulse(ref vectImp, ref hitpoint); // We gather the fixtures for returning them Vector2 val = Vector2.Zero; List <Vector2> vectorList; if (_exploded.TryGetValue(f, out vectorList)) { val.X += Math.Abs(vectImp.X); val.Y += Math.Abs(vectImp.Y); vectorList.Add(val); } else { vectorList = new List <Vector2>(); val.X = Math.Abs(vectImp.X); val.Y = Math.Abs(vectImp.Y); vectorList.Add(val); _exploded.Add(f, vectorList); } if (minlambda > 1.0f) { hitpoint = p2; } } } } // We check contained shapes for (int i = 0; i < containedShapeCount; ++i) { Fixture fix = containedShapes[i]; if (!IsActiveOn(fix.Body)) { continue; } float impulse = MinRays * maxForce * 180.0f / MathHelper.Pi; Vector2 hitPoint; CircleShape circShape = fix.Shape as CircleShape; if (circShape != null) { hitPoint = fix.Body.GetWorldPoint(circShape.Position); } else { PolygonShape shape = fix.Shape as PolygonShape; hitPoint = fix.Body.GetWorldPoint(shape.MassData.Centroid); } Vector2 vectImp = impulse * (hitPoint - pos); List <Vector2> vectorList = new List <Vector2>(); vectorList.Add(vectImp); fix.Body.ApplyLinearImpulse(ref vectImp, ref hitPoint); if (!_exploded.ContainsKey(fix)) { _exploded.Add(fix, vectorList); } } return(_exploded); }
public virtual void AddChild(CCNode child, int zOrder, int tag) { Debug.Assert(child != null, "Argument must be non-null"); Debug.Assert(child.m_pParent == null, "child already added. It can't be added again"); Debug.Assert(child != this, "Can not add myself to myself."); if (m_pChildren == null) { m_pChildren = new CCRawList<CCNode>(); } InsertChild(child, zOrder); child.m_nTag = tag; child.Parent = this; child.m_nOrderOfArrival = s_globalOrderOfArrival++; if (m_bIsRunning) { child.OnEnter(); child.OnEnterTransitionDidFinish(); } }
/// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> private World() { Flags = WorldFlags.ClearForces; ControllerList = new CCRawList<Controller>(); BreakableBodyList = new CCRawList<BreakableBody>(); BodyList = new CCRawList<Body>(32); JointList = new CCRawList<Joint>(32); }
protected void InitSpriteFont(string theString, string fntFile, float fontSize, CCSize dimensions, CCLabelFormat labelFormat, CCPoint imageOffset, CCTexture2D texture) { Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null), "Invalid params for CCLabel SpriteFont"); if (!String.IsNullOrEmpty(fntFile)) { try { FontAtlas = CCFontAtlasCache.GetFontAtlasSpriteFont(fntFile, fontSize, imageOffset); Scale = FontAtlas.Font.FontScale; } catch {} if (FontAtlas == null) { CCLog.Log("SpriteFont CCLabel: Impossible to create font. Please check file: '{0}'", fntFile); return; } } AnchorPoint = CCPoint.AnchorMiddle; LabelType = CCLabelType.SpriteFont; if (String.IsNullOrEmpty(theString)) { theString = String.Empty; } // Initialize the TextureAtlas along with children. var capacity = theString.Length; BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); this.labelDimensions = dimensions; horzAlignment = labelFormat.Alignment; vertAlignment = labelFormat.LineAlignment; IsOpacityCascaded = true; ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = imageOffset; Text = theString; }
/// <summary> /// Initializes a new instance of the <see cref="CocosSharp.CCLabel"/> class. /// </summary> /// <param name="str">Initial text of the label.</param> /// <param name="fntFile">Font definition file to use.</param> /// <param name="size">Font point size.</param> /// <param name="dimensions">Dimensions that the label should use to layout it's text.</param> /// <param name="labelFormat">Label format <see cref="CocosSharp.CCLabelFormat"/>.</param> /// <param name="imageOffset">Image offset.</param> /// <param name="texture">Texture atlas to be used.</param> public CCLabel(CCFontFNT fntFontConfig, string str, CCSize dimensions, CCLabelFormat labelFormat) { quadCommand = new CCQuadCommand(str.Length); labelFormat.FormatFlags = CCLabelFormatFlags.BitmapFont; AnchorPoint = CCPoint.AnchorMiddle; try { FontAtlas = CCFontAtlasCache.GetFontAtlasFNT(fntFontConfig); } catch { } if (FontAtlas == null) { CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check CCFontFNT file: "); return; } LabelType = CCLabelType.BitMapFont; this.labelFormat = labelFormat; if (String.IsNullOrEmpty(str)) { str = String.Empty; } // Initialize the TextureAtlas along with children. var capacity = str.Length; BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); this.labelDimensions = dimensions; horzAlignment = labelFormat.Alignment; vertAlignment = labelFormat.LineAlignment; IsOpacityCascaded = true; // We use base here so we do not trigger an update internally. base.ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = CCPoint.Zero; Text = str; }
private string CreateFont(string fontName, float fontSize, CCRawList<char> charset) { if (Factory2D == null) { Factory2D = new SharpDX.Direct2D1.Factory(); FactoryDWrite = new SharpDX.DirectWrite.Factory(); FactoryImaging = new SharpDX.WIC.ImagingFactory(); dpi = Factory2D.DesktopDpi; dpiScale = dpi.Height / 72f; } if (_defaultFont == null) { _defaultFont = GenericSanSerif(); //_defaultDIP = ConvertPointSizeToDIP(_defaultFontSizeEm); } FontFamily fontFamily = GetFontFamily(fontName); if (!_fontFamilyCache.TryGetValue(fontName, out fontFamily)) { var ext = Path.GetExtension(fontName); _currentFont = _defaultFont; if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { //var appPath = AppDomain.CurrentDomain.BaseDirectory; //var contentPath = Path.Combine(appPath, CCApplication.SharedApplication.Content.RootDirectory); //var fontPath = Path.Combine(contentPath, fontName); //if (File.Exists(fontPath)) //{ // try //{ //var fontFileReference = new FontCollection( //_loadedFonts.AddFontFile(fontPath); // //fontFamily = _loadedFonts.Families[_loadedFonts.Families.Length - 1]; // //_currentFont = new Font(fontFamily, fontSize); // } // catch // { // _currentFont = _defaultFont; // } //} //else //{ _currentFont = _defaultFont; _currentFontSizeEm = fontSize; _currentDIP = ConvertPointSizeToDIP(fontSize); //} } else { _currentFont = GetFont(fontName, fontSize); _currentFontSizeEm = fontSize; _currentDIP = ConvertPointSizeToDIP(fontSize); } _fontFamilyCache.Add(fontName, _currentFont.FontFamily); } else { _currentFont = fontFamily.GetFirstMatchingFont(FontWeight.Regular, FontStretch.Normal, FontStyle.Normal); _currentFontSizeEm = fontSize; _currentDIP = ConvertPointSizeToDIP(fontSize); } fontName = _currentFont.FontFamily.FamilyNames.GetString(0); textFormat = new TextFormat(FactoryDWrite, fontName, _currentDIP); GetKerningInfo(charset); return _currentFont.ToString(); }
internal Body() { FixtureList = new CCRawList <Fixture>(32); }
protected void InitBMFont(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)) { try { FontAtlas = CCFontAtlasCache.GetFontAtlasFNT(fntFile, imageOffset); } catch {} if (FontAtlas == null) { CCLog.Log("Bitmap Font CCLabel: Impossible to create font. Please check file: '{0}'", fntFile); return; } } AnchorPoint = CCPoint.AnchorMiddle; FontConfiguration = CCBMFontConfiguration.FontConfigurationWithFile(fntFile); LabelType = CCLabelType.BitMapFont; if (String.IsNullOrEmpty(theString)) { theString = String.Empty; } // Initialize the TextureAtlas along with children. var capacity = theString.Length; BlendFunc = CCBlendFunc.AlphaBlend; if (capacity == 0) { capacity = defaultSpriteBatchCapacity; } UpdateBlendFunc(); // no lazy alloc in this node Children = new CCRawList<CCNode>(capacity); Descendants = new CCRawList<CCSprite>(capacity); this.labelDimensions = dimensions; horzAlignment = hAlignment; vertAlignment = vAlignment; IsOpacityCascaded = true; // We use base here so we do not trigger an update internally. base.ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = imageOffset; Text = theString; }