public string ComputeEncoding(FlowMatrix flowSpec, int maxSelWidth = 6) { var sb = new StringBuilder(); sb.AppendLine("Control word encoding report"); sb.AppendFormat(" Number of c-steps: {0}", flowSpec.NumCSteps); sb.AppendLine(); sb.AppendFormat(" Maximum LUT inputs: {0}", maxSelWidth); sb.AppendLine(); FlowSpec = flowSpec; var flowMap = new Dictionary <SignalRef, List <Flow> >(); var neutralFlow = flowSpec.NeutralFlow; _vcf.AddFlow(neutralFlow); for (int i = 0; i < flowSpec.NumCSteps; i++) { var pflow = flowSpec.GetFlow(i); var nflow = new ParFlow(neutralFlow); nflow.Integrate(pflow); _vcf.AddFlow(nflow); foreach (var flow in nflow.Flows) { List <Flow> flows; if (!flowMap.TryGetValue(flow.Target, out flows)) { flows = new List <Flow>(); flowMap[flow.Target] = flows; } flows.Add(flow); } } _vcf.Encode(); var startTime = DateTime.Now; var encFlows = flowMap.Values .Select((l, i) => new EncodedFlow(l, i)).ToArray(); var uncompressedMuxBits = encFlows.Sum(ef => MathExt.CeilLog2(ef.NumSymbols)); sb.AppendFormat(" Uncompressed CW: {0} MUX bits + {1} value bits", uncompressedMuxBits, _vcf.GetUncompressedValueWordWidth()); sb.AppendLine(); int numTargets = encFlows.Length; var mergeCandidates = new List <Tuple <int, int, MergedFlow> >(); var indices = new SortedSet <int>(Enumerable.Range(0, numTargets)); var curGen = (EncodedFlow[])encFlows.Clone(); bool mergedAny; var nextCandidates = new List <Tuple <int, int, MergedFlow> >(); do { foreach (int i in indices) { if (curGen[i].NumSymbols <= 1) { continue; } var upview = indices.GetViewBetween(i + 1, numTargets); foreach (int j in upview) { if (curGen[j].NumSymbols <= 1) { continue; } var mergedFlow = new MergedFlow(curGen[i], curGen[j]); mergeCandidates.Add(Tuple.Create(i, j, mergedFlow)); } } var orderedMergeCandidates = mergeCandidates.OrderByDescending(t => t.Item3.Score); var nextGen = (EncodedFlow[])curGen.Clone(); var mergedIndices = new HashSet <int>(); var mergedLowIndices = new SortedSet <int>(); var mergedHiIndices = new HashSet <int>(); mergedAny = false; foreach (var tup in orderedMergeCandidates) { Debug.Assert(tup.Item2 > tup.Item1); var mergedFlow = tup.Item3; if (mergedFlow.Score == 0.0) { break; } int selWidth = MathExt.CeilLog2(mergedFlow.NumSymbols); if (selWidth > maxSelWidth) { continue; } if (mergedIndices.Contains(tup.Item1) || mergedIndices.Contains(tup.Item2)) { continue; } mergedIndices.Add(tup.Item1); mergedIndices.Add(tup.Item2); mergedLowIndices.Add(tup.Item1); mergedHiIndices.Add(tup.Item2); indices.Remove(tup.Item2); mergedFlow.Realize(); Debug.Assert(nextGen[tup.Item1].Targets.All(t => mergedFlow.Targets.Contains(t))); Debug.Assert(nextGen[tup.Item2].Targets.All(t => mergedFlow.Targets.Contains(t))); nextGen[tup.Item1] = mergedFlow; mergedAny = true; } nextCandidates.Clear(); curGen = nextGen; mergeCandidates.Clear(); mergeCandidates.AddRange(nextCandidates); }while (mergedAny); _strings = indices.Select(i => new MicroString(curGen[i], _vcf)).ToArray(); // Verification var coveredTargets = _strings.SelectMany(s => s.Targets); var allTargets = encFlows.SelectMany(f => f.Targets); var isect0 = coveredTargets.Except(allTargets); var isect1 = allTargets.Except(coveredTargets); Debug.Assert(!isect0.Any()); Debug.Assert(!isect1.Any()); // int offset = _vcf.ValueWordWidth; int order = 0; foreach (var ms in _strings) { ms.SelOffset = offset; ms.Order = order; offset += ms.SelWidth; order++; } CWWidth = offset; var stopTime = DateTime.Now; var runTime = stopTime - startTime; sb.AppendFormat(" Compressed CW: {0} MUX bits + {1} value bits", offset - _vcf.ValueWordWidth, _vcf.ValueWordWidth); sb.AppendLine(); sb.AppendFormat(" Maximum LUT inputs: {0}", _strings.Max(s => s.SelWidth)); sb.AppendFormat(" Running time: {0} ms", runTime.TotalMilliseconds); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("Number of MUX inputs; Number of occurences"); var histo = _strings.GroupBy(s => s.SelWidth) .OrderByDescending(grp => grp.Key); foreach (var grp in histo) { sb.AppendFormat("{0}; {1}", grp.Key, grp.Count()); sb.AppendLine(); } return(sb.ToString()); }
private void processInputPan(int _event, int[] args) { switch (_event) { case 4: int num1 = args[1]; int num2 = args[2]; this.m_startDragScreenX = num1; this.m_startDragScreenY = num2; this.m_startDragTopLeftTileX = this.m_topLeftTileX; this.m_startDragTopLeftTileY = this.m_topLeftTileY; break; case 5: int num3 = args[1]; int num4 = args[2]; int num5 = (num3 - this.m_startDragScreenX) / this.m_tileSize; int num6 = (num4 - this.m_startDragScreenY) / this.m_tileSize; this.m_topLeftTileX = this.m_startDragTopLeftTileX - num5; this.m_topLeftTileY = this.m_startDragTopLeftTileY - num6; break; case 7: JSystem.println(" double tap"); this.editStateTransition(2); break; case 9: int num7 = args[5]; int num8 = args[6]; int num9 = args[7]; int num10 = args[8]; this.m_tileSize = (int)(5.0 + 45.0 * (double)JMath.min(1f, JMath.max(0.0f, JMath.max(150f, JMath.min(400f, MathExt.mag2((float)(num9 - num7), (float)(num10 - num8)))) / 400f))); break; } }
/// <summary>returns the first value pinned between the second two</summary> public float pin(float value, float min, float max) { return(MathExt.Clamp(value, min, max)); }
private static void GeneratePinImg(Report data) { var genType = "Report"; var bgPath = string.Join(Path.DirectorySeparatorChar.ToString(), new[] { "Resource", "Img", "reports", "bg.png" }); if (!File.Exists(bgPath)) { Console.WriteLine($"{genType}. Нет ресурсов - бекграунд {bgPath}"); return; } using (var bg = Image.FromFile(bgPath)) { using (Graphics graphics = Graphics.FromImage(bg)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.TextRenderingHint = TextRenderingHint.AntiAlias; graphics.DrawText(data.Name, 16, 303, 654, color: Color.FromArgb(255, 2, 2)); graphics.DrawText(data.ObjectsCount, 32, 593, 635); graphics.DrawText($"1:{data.OneObjectPeopleCount}", 32, 593, 774); graphics.DrawText(data.AvgPrice, 32, 593, 929); graphics.DrawText(data.Population, 32, 1000, 635); graphics.DrawText(data.PopulationDensity, 32, 1342, 635); { var sLineX = 1010; var eLineX = 1581; //График 1 var max = data.GrafA.Max(); var avg = data.GrafA.Average(); var nearMax = Math.Round(max - max * 0.005); var nearMaxStr = nearMax < 1000 ? nearMax.ToString() : Math.Round(nearMax / 1000) + "K"; var sLineY = 849; graphics.DrawText(nearMaxStr, 11, sLineX, 832, color: Color.FromArgb(88, 88, 90)); graphics.DrawLine(new Pen(Color.FromArgb(71, 76, 92), 1), new Point(sLineX, sLineY), new Point(eLineX, sLineY)); graphics.DrawLine(new Pen(Color.FromArgb(52, 56, 68), 1), new Point(sLineX, sLineY + 1), new Point(eLineX, sLineY + 1)); //Вторая линия sLineY = 890; graphics.DrawLine(new Pen(Color.FromArgb(22, 22, 29), 1), new Point(sLineX, sLineY), new Point(eLineX, sLineY)); graphics.DrawLine(new Pen(Color.FromArgb(25, 26, 32), 1), new Point(sLineX, sLineY + 1), new Point(eLineX, sLineY + 1)); //Третья линия sLineY = 929; var halfNearMax = nearMax / 2; var halfNearMaxStr = halfNearMax < 1000 ? halfNearMax.ToString() : (halfNearMax / 1000).ToString("N1") + "K"; graphics.DrawText(halfNearMaxStr, 11, sLineX, 912, color: Color.FromArgb(88, 88, 90)); graphics.DrawLine(new Pen(Color.FromArgb(37, 39, 49), 1), new Point(sLineX, sLineY), new Point(eLineX, sLineY)); graphics.DrawLine(new Pen(Color.FromArgb(75, 80, 97), 1), new Point(sLineX, sLineY + 1), new Point(eLineX, sLineY + 1)); graphics.DrawLine(new Pen(Color.FromArgb(26, 27, 34), 1), new Point(sLineX, sLineY + 2), new Point(eLineX, sLineY + 2)); //Предпоследния линия sLineY = 970; graphics.DrawLine(new Pen(Color.FromArgb(27, 28, 35), 1), new Point(sLineX, sLineY), new Point(eLineX, sLineY)); graphics.DrawLine(new Pen(Color.FromArgb(19, 20, 26), 1), new Point(sLineX, sLineY + 1), new Point(eLineX, sLineY + 1)); //Нижняя линия sLineY = 1010; graphics.DrawLine(new Pen(Color.FromArgb(64, 68, 83), 2), new Point(sLineX, sLineY), new Point(eLineX, sLineY)); //Строим столбцы var eLineY = 1000; var grafHeight = eLineY - 840; var grafWidth = eLineX - sLineX + 5 - 20; if (data.GrafA.Length > 0) { var pdx = grafWidth / data.GrafA.Length; for (var i = 0; i < data.GrafA.Length; i++) { var dy = (int)Math.Round(grafHeight * (data.GrafA[i] * 100.0 / max) / 100.0); var stX = sLineX + 4 + i * 33; var colWidth = 4; var rect = new Rectangle(stX, eLineY - dy, colWidth, dy); Brush linearGradientBrush = new LinearGradientBrush( rect, Color.White, Color.Black, 45); graphics.FillRectangle(linearGradientBrush, new Rectangle(stX, eLineY - dy, colWidth, dy - 2)); var b = new SolidBrush(Color.FromArgb(50, 154, 216)); graphics.FillRectangle(b, stX, eLineY - dy, colWidth, colWidth); } } } //График 2 { var max = 211000; //(data.GrafB1.Length > 0 ? data.GrafB1.Max() : 0) + // (data.GrafB2.Length > 0 ? data.GrafB2.Max() : 0); graphics.DrawText("211К", 10, 722, 1235, color: Color.Gray); graphics.DrawText("141К", 10, 722, 1284, color: Color.Gray); graphics.DrawText("70К", 10, 722, 1318, color: Color.Gray); var center = new Point(717, 1392); var angCount = 360 / 24; var radius = 160; var pointsWhite = data.GrafB1.Select((x, i) => { var ang = angCount * i; var proc = (x * 100.0 / max) / 100 * radius; double angle2 = Math.PI * ang / 180.0; var txtX = (int)(radius * Math.Sin(angle2)); var txtY = (int)(radius * Math.Cos(angle2)); var pointOnCircle = new Point(center.X + txtX, center.Y - txtY); return(MathExt.GetPointOnLine(center, pointOnCircle, (int)proc)); }); graphics.DrawPolygon(new Pen(Color.White, 2), pointsWhite.ToArray()); var pointsRed = data.GrafB2.Select((x, i) => { var ang = angCount * i; var proc = (x * 100.0 / max) / 100 * radius; double angle2 = Math.PI * ang / 180.0; var txtX = (int)(radius * Math.Sin(angle2)); var txtY = (int)(radius * Math.Cos(angle2)); var pointOnCircle = new Point(center.X + txtX, center.Y - txtY); return(MathExt.GetPointOnLine(center, pointOnCircle, (int)proc)); }); graphics.DrawPolygon(new Pen(Color.Red, 2), pointsRed.ToArray()); } //График 3 (Кругоыой) { var topLeftX = 1170; var topLeftY = 1270; var width = 260; var radius = width / 2; var centr = new Point(topLeftX + width / 2, topLeftY + width / 2); graphics.DrawText("ОБЪЕКТЫ", 16, topLeftX + width / 2 - 20 * 3, topLeftY + width / 2 - 10, color: Color.FromArgb(217, 217, 217)); var sum = data.GrafC.Sum(); var colorArr = new[] { Color.FromArgb(255, 46, 46), Color.FromArgb(255, 69, 69), Color.FromArgb(255, 163, 163), Color.FromArgb(255, 212, 212), Color.FromArgb(33, 81, 255), Color.FromArgb(46, 147, 255), Color.FromArgb(130, 130, 141), Color.FromArgb(227, 240, 255), }; float lastAngle = 0 - 90; //var angleDx = 0; var prevRec = new Rectangle(); for (var i = 0; i < data.GrafC.Length; i++) { var colorInd = (Math.Abs(i * colorArr.Length) + i) % colorArr.Length; var color = colorArr[colorInd];//GraphicsExt.GetBlendedColor((int)procenrt); var procenrt = data.GrafC[i] * 100.0 / sum; var angle = (float)(360f * procenrt / 100); //graphics.Dyga(new Pen(color, 10), 1300, 1400, 122, lastAngle, lastAngle + angle); graphics.DrawArc(new Pen(color, 12), topLeftX, topLeftY, width, width, lastAngle, angle); //Подпись процентов //var txtX = (int)Math.Floor(radius * Math.Sin(lastAngle + 90)); //var txtY = (int)Math.Floor(radius * Math.Cos(lastAngle + 90)); //// graphics.DrawText(procenrt.ToString(), 12, topLeftX + txtX, topLeftY + txtY, color: Color.Red); //graphics.DrawLine(new Pen(color, 1), centr, new Point(centr.X - txtX, centr.Y - txtY)); //{ var angleTxt = lastAngle + 90 + (angle < 40 ? (lastAngle + 90 > 180 ? angle / 3 : angle * .2) : angle / 2); double angle2 = Math.PI * angleTxt / 180.0; var txtX = (int)(radius * Math.Sin(angle2)); var txtY = (int)(radius * Math.Cos(angle2)); //var txtX = Math.Sin((0 / 180D) * Math.PI); // (int)Math.Floor(radius * Math.Sin(0)); //var txtY = (int)Math.Floor(radius * Math.Cos(0)); // graphics.DrawText(procenrt.ToString(), 12, topLeftX + txtX, topLeftY + txtY, color: Color.Red); var pointOnCircle = new Point(centr.X + txtX, centr.Y - txtY); graphics.DrawLine(new Pen(color, 1), centr, pointOnCircle); // if (angle > 20) angleDx = 0; using (var imgTxt = new Bitmap(150, 100)) { using (Graphics gTxt = Graphics.FromImage(imgTxt)) { gTxt.CompositingQuality = CompositingQuality.HighQuality; gTxt.InterpolationMode = InterpolationMode.HighQualityBicubic; gTxt.SmoothingMode = SmoothingMode.HighQuality; gTxt.TextRenderingHint = TextRenderingHint.AntiAlias; StringFormat format = new StringFormat(); format.LineAlignment = StringAlignment.Near; format.Alignment = angleTxt < 180 ? StringAlignment.Near : StringAlignment.Far; gTxt.DrawText(procenrt.ToString("N2"), 12, 0, 0, imgTxt.Width, imgTxt.Height, color: Color.Red, format: format); int lastEmptyRow = GetLastEmptyRowNum(imgTxt); var title = data.GrafCT?[i]; if (!string.IsNullOrWhiteSpace(title) && lastEmptyRow >= 0) { gTxt.DrawText(title.Replace("/", "/ "), 8, 0, lastEmptyRow, imgTxt.Width, imgTxt.Height, color: Color.FromArgb(65, 65, 65), format: format); } lastEmptyRow = GetLastEmptyRowNum(imgTxt); var maxX = GetLastEmptyColNum(imgTxt); int dx = 0, dy = 0; if (angleTxt < 60) { //dx = (int)(maxX * .2); //dy = (int)(-lastEmptyRow * .6); dx = 0; dy = -lastEmptyRow; } else if (angleTxt > 180) { dx = -maxX; if (angleTxt > 315) { dy = -lastEmptyRow + 10; } } var txtPoint = MathExt.GetPointOnLine(centr, pointOnCircle, radius + 20); txtPoint = new Point(txtPoint.X + dx, txtPoint.Y + dy); if (txtPoint.X > prevRec.X && txtPoint.X < prevRec.X + prevRec.Width && txtPoint.Y > prevRec.Y && txtPoint.Y < prevRec.Y + prevRec.Height) { int newX = txtPoint.X, newY = prevRec.Y - lastEmptyRow; txtPoint = new Point(newX, newY); } graphics.DrawImage(imgTxt, txtPoint.X, txtPoint.Y); /*imgTxt.Save(string.Join(Path.DirectorySeparatorChar.ToString(), * new[] { "reports", "test.png" }));*/ prevRec = new Rectangle(txtPoint.X, txtPoint.Y, maxX, lastEmptyRow); //var imgRet = Bitmap.Fro } } // (angleTxt < 180 ? 25 : 50)); // (angle i % 2 == 0 ? 15 : 0)); /* StringFormat format = new StringFormat(); * format.LineAlignment = StringAlignment.Near; * * if (angleTxt < 180) * { * format.Alignment = StringAlignment.Near; * if (txtPoint.X > prevRec.X && txtPoint.X < prevRec.X + prevRec.Width && txtPoint.Y > prevRec.Y && txtPoint.Y < prevRec.Y + prevRec.Height) * { * int newX = txtPoint.X, newY = txtPoint.Y; * * txtPoint = new Point(txtPoint.X, prevRec.Y - 20); * } * * graphics.DrawText(procenrt.ToString("N2"), 12, txtPoint.X, txtPoint.Y); // - 16 - (angleTxt < 30 && i > 0 && i % 2 == 0 ? 20 : 0), 200, 60, color: Color.Red); * * //var title = data.GrafCT?[i]; * //if (!string.IsNullOrWhiteSpace(title)) * //{ * // graphics.DrawText(title, 8, txtPoint.X, txtPoint.Y, 150, 60, color: Color.FromArgb(65, 65, 65), format: format); * //} * } * else * { * format.Alignment = StringAlignment.Near; * }*/ // if (angle < 20) angleDx += 15; //} //{ // var txtX = (int)Math.Floor(radius * Math.Cos(90)); // var txtY = (int)Math.Floor(radius * Math.Sin(90)); // // graphics.DrawText(procenrt.ToString(), 12, topLeftX + txtX, topLeftY + txtY, color: Color.Red); // graphics.DrawLine(new Pen(color, 1), centr, new Point(centr.X + txtX, centr.Y - txtY)); //} //{ // var txtX = (int)Math.Floor(radius * Math.Cos(180)); // var txtY = (int)Math.Floor(radius * Math.Sin(180)); // // graphics.DrawText(procenrt.ToString(), 12, topLeftX + txtX, topLeftY + txtY, color: Color.Red); // graphics.DrawLine(new Pen(color, 1), centr, new Point(centr.X + txtX, centr.Y - txtY)); //} lastAngle = lastAngle + angle; //graphics.DrawCircle(new Pen(Color.FromArgb(33, 81, 255), 10), 1300, 1400, 122); // prevRec = new Rectangle(txtPoint.X, txtPoint.Y, 100, 20); } } /* foreach (var dt in data) * { * var dtType = (InnoTypes) dt.InnoObjectTypeID; * var pinTypePath = string.Join(Path.DirectorySeparatorChar.ToString(), * new[] {"Resource", "Img", "pins", $"{dtType.ToString().ToLower()}.png"}); * * if (!File.Exists(pinTypePath)) * { * Console.WriteLine($"{genType}. Нет ресурсов - бекграунд {pinTypePath}"); * continue; * } * * using (var pin = Image.FromFile(pinTypePath)) * { * var pinPoint = new PointD() {X = dt.Lon, Y = dt.Lat}.ConverPoint(segment).FixPoint(); * graphics.DrawImage(pin, (int) pinPoint.X, (int) pinPoint.Y, pin.Width, pin.Height); * } * }*/ } if (!Directory.Exists("reports")) { Directory.CreateDirectory("reports"); } bg.Save(string.Join(Path.DirectorySeparatorChar.ToString(), new[] { "reports", $"{data.Area}_{data.Type}.png" })); } }
public void ReadGenericData(BinaryReader br, int version) { FlagGroup f = new FlagGroup(br.ReadInt32()); mCollision = f[5]; mVisible = f[6]; mCanMove = f[7]; mBackground = f[14]; mBaseObject = f[15]; mBallStopReset = f[20]; mForeground = f[22]; mDrawSort = f[24]; mForeground2 = f[25]; mDrawFloat = f[28]; if (f[0]) { mRolly = br.ReadSingle(); } if (f[1]) { mBouncy = br.ReadSingle(); } if (f[4]) { br.ReadInt32(); } if (f[8]) { mSolidColour = Color.FromArgb(br.ReadInt32()); } if (f[9]) { mOutlineColour = Color.FromArgb(br.ReadInt32()); } if (f[10]) { mImageFilename = LevelReader.ReadPopcapString(br); } if (f[11]) { mImageDX = br.ReadSingle(); } if (f[12]) { mImageDY = br.ReadSingle(); } if (f[13]) { mImageRotation = MathExt.ToDegrees(br.ReadSingle()); } if (f[16]) { br.ReadInt32(); } if (f[17]) { mID = LevelReader.ReadPopcapString(br); } if (f[18]) { br.ReadInt32(); } if (f[19]) { mSound = br.ReadByte(); } if (f[21]) { mLogic = LevelReader.ReadPopcapString(br); } if (f[23]) { mMaxBounceVelocity = br.ReadSingle(); } if (f[26]) { mSubID = br.ReadInt32(); } if (f[27]) { mFlipperFlags = br.ReadByte(); } if (f[2]) { mPegInfo = new PegInfo(this); mPegInfo.ReadData(br, version); } if (f[3]) { mMovement = new Movement(mLevel); mMovement.ReadData(br, version); } if (f[30] && version >= 0x50) { mShadow = f[30]; } }
private void DoMemoryClustering() { var lookup = _eqRegs.ToLookup(); int[] indices = lookup.Select(grp => grp.Key).Where(i => !IsUnused(i)).ToArray(); if (indices.Length == 0) { return; } _eqMems = new UnionFind <int>(new IndexedIntSetAdapter(indices), indices); _writeTimes = new SortedSet <int> [_tempRegTypes.Length]; _readTimes = new SortedSet <int> [_tempRegTypes.Length]; for (int i = 0; i < indices.Length; i++) { int j = indices[i]; _writeTimes[j] = new SortedSet <int>(); _readTimes[j] = new SortedSet <int>(); _writeTimes[j].AddRange(_lifeTimes[j].LeftPoints); _readTimes[j].AddRange(_lifeTimes[j].RightPoints); } bool found; do { found = false; for (int i = 0; i < indices.Length; i++) { int slot1 = indices[i]; for (int j = i + 1; j < indices.Length; j++) { int slot2 = indices[j]; if (AreSharableInMemory(slot1, slot2)) { int rep1 = _eqMems.Find(slot1); int rep2 = _eqMems.Find(slot2); if (rep1 == rep2) { continue; } var mergedInputs = _regIn[slot1].Union(_regIn[slot2]); int newRegMuxCost = mergedInputs.Count(); var commonTargets = _regOut[slot1].Intersect(_regOut[slot2]); if (!commonTargets.Any()) { continue; } int newFuMuxCost = commonTargets.Select(t => ComputeFuMuxCost(t) - 1).Max(); if (newFuMuxCost - newRegMuxCost >= -1) { _eqMems.Union(slot1, slot2); _regIn[slot1].UnionWith(_regIn[slot2]); _regIn[slot2] = _regIn[slot1]; int rep = _eqMems.Find(slot1); if (rep != rep1) { _writeTimes[rep].AddRange(_writeTimes[rep1]); _readTimes[rep].AddRange(_readTimes[rep1]); } if (rep != rep2) { _writeTimes[rep].AddRange(_writeTimes[rep2]); _readTimes[rep].AddRange(_readTimes[rep2]); } found = true; } } } } } while (found); _memLookup = _eqMems.ToLookup(); _memAddrs = new StdLogicVector[_tempRegTypes.Length]; foreach (var grp in _memLookup) { var active = grp.Where(i => !IsUnused(i)); if (active.Count() <= 1) { continue; } int addrWidth = MathExt.CeilLog2(active.Count()); uint addr = 0; foreach (var stgSlot in active) { if (IsUnused(stgSlot)) { continue; } _memAddrs[stgSlot] = StdLogicVector.FromUInt(addr, addrWidth); addr++; } } }
protected override void AliveUpdate() { if (_time < 0) { _time = MathExt.Random(0, 0.7f); var value = MathExt.Random(0, 10); for (int i = 0; i < Player.Stat.DnaClass; i++) { var _speed = 0f; switch (value) { case 0: _speed = MathExt.Random(8.0f, 8.5f); break; default: _speed = MathExt.Random(0.4f, 0.5f); break; } var unit = new Ape(Data, new DogInput(), new AccMovement(_speed)); AddUnit(unit); if (value == 0) { unit.Skin.SetColor(Microsoft.Xna.Framework.Color.Red); unit.Stat.SetAttack(30, 0); unit.Collision.Body.Mass = 40; unit.Collision.Body.Restitution = 1.2f; } unit.SetPosition(Player.Position + new Microsoft.Xna.Framework.Vector2(MathExt.Random(-500, 500), MathExt.Random(-500, 500))); } } _time -= TimeExt.ElapsedGameTime; for (int i = 0; i < _Units.Count; i++) { _Units[i].Update(); } base.AliveUpdate(); }
public static float sin(float a) { int num = 65536; return((float)MathExt.Fsin((int)((double)num * (double)a)) / (float)num); }
public void Update() { _player = GameObject.FindGameObjectWithTag("Player"); if (_player == null) { return; } float pdist = (_player.transform.position - transform.position).sqrMagnitude; if (_rb.IsAwake() && pdist >= 800) { _rb.Sleep(); return; } else if (!_rb.IsAwake() && pdist < 800) { _rb.WakeUp(); } if (_state != EnemyState.Chase) { if (PlayerInFieldOfVision() && HasLineOfSight()) { _state = EnemyState.Chase; } } else { if (!PlayerInFieldOfVision()) { _state = EnemyState.Wander; } } switch (_state) { case EnemyState.Wander: var circleCenter = _rb.velocity.normalized * _wanderCircleDistance; var displacement = (new Vector2(0, 1)) * _wanderCircleRadius; var len = displacement.magnitude; displacement.x = Mathf.Cos(_wanderAngle) * len; displacement.y = Mathf.Sin(_wanderAngle) * len; _wanderAngle = Random.value * _wanderAngleChange - _wanderAngleChange * 0.5f; var wanderForce = (circleCenter + displacement); if (wanderForce.magnitude > _wanderForceMax) { wanderForce = wanderForce.normalized * _wanderForceMax; } Movement = _rb.velocity + wanderForce; Rotation = (MathExt.AngleBetweenTwoPoints(_rb.position + _rb.velocity, _rb.position) + 360) % 360; break; case EnemyState.Chase: if (_player != null) { Movement = (_player.transform.position - transform.position) * 100; Rotation = (MathExt.AngleBetweenTwoPoints(_player.transform.position, transform.position) + 360) % 360; } else { _state = EnemyState.Wander; } break; case EnemyState.Attack: break; } }
/// <summary> /// Run method, overwrites FCSComponent.Run() /// </summary> /// <returns>false on success, true on failure. The routine doing the work.</returns> public override bool Run() { double dt0 = dt; input = inputNodes[0].GetDoubleValue(); if (DoScale) { input *= detents[detents.Count - 1]; } if (outputNodes.Count > 0) { output = (double)outputNodes[0].Get(); } input = MathExt.Constrain(detents[0], input, detents[detents.Count - 1]); if (fcs.GetTrimStatus()) { // When trimming the output must be reached in one step output = input; } else { // Process all detent intervals the movement traverses until either the // final value is reached or the time interval has finished. while (dt0 > 0.0 && !MathExt.EqualToRoundoff(input, output)) { // Find the area where Output is in int ind; for (ind = 1; (input < output) ? detents[ind] < output : detents[ind] <= output; ++ind) { if (ind >= detents.Count) { break; } } // A transition time of 0.0 means an infinite rate. // The output is reached in one step if (transitionTimes[ind] <= 0.0) { output = input; break; } else { // Compute the rate in this area double Rate = (detents[ind] - detents[ind - 1]) / transitionTimes[ind]; // Compute the maximum input value inside this area double ThisInput = MathExt.Constrain(detents[ind - 1], input, detents[ind]); // Compute the time to reach the value in ThisInput double ThisDt = Math.Abs((ThisInput - output) / Rate); // and clip to the timestep size if (dt0 < ThisDt) { ThisDt = dt0; if (output < input) { output += ThisDt * Rate; } else { output -= ThisDt * Rate; } } else { // Handle this case separate to make shure the termination condition // is met even in inexact arithmetics ... output = ThisInput; } dt0 -= ThisDt; } } } Clip(); SetOutput(); return(true); }
public void IntPowerLong(long x, uint exp) => Assert.Equal(System.Math.Pow(x, exp), MathExt.IntPower(x, exp));
public Bitmap DisplayOCR(Bitmap shot, HexGrid grid) { shot = new Bitmap(shot); using (Graphics g = Graphics.FromImage(shot)) { g.FillRectangle(new SolidBrush(Color.White), 0, 0, shot.Width, shot.Height); Font fnt = new Font("Arial", 12, FontStyle.Bold); Font fnt_big = new Font("Arial", 22, FontStyle.Bold); Brush fntBush1 = new SolidBrush(Color.Black); Brush fntBush2 = new SolidBrush(Color.FromArgb(32, Color.Black)); Brush fntBush3 = new SolidBrush(Color.Red); Pen bluepen = new Pen(Color.FromArgb(0, 164, 235)); Brush bluebrush = new SolidBrush(Color.FromArgb(128, 0, 164, 235)); StringFormat fmt = new StringFormat { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }; foreach (var hex in grid) { var points = Enumerable.Range(0, 7).Select(p => hex.Value.GetEdge(p)).Select(p => new Point((int)p.X, (int)p.Y)).ToArray(); if (hex.Value.Type == HexagonType.NOCELL) { g.FillPolygon(new SolidBrush(Color.Gainsboro), points); } else { g.FillPolygon(new SolidBrush(Color.SlateGray), points); } if (hex.Value.Hint.Type != CellHintType.NONE) { if (hex.Value.Hint.Area == CellHintArea.CIRCLE) { Vec2d center = hex.Value.Image.OCRCenter; double hexheight = hex.Value.Image.OCRHeight * 0.8; g.FillEllipse(bluebrush, (int)(center.X - hexheight), (int)(center.Y - hexheight), (int)(2 * hexheight), (int)(2 * hexheight)); g.DrawEllipse(bluepen, (int)(center.X - hexheight), (int)(center.Y - hexheight), (int)(2 * hexheight), (int)(2 * hexheight)); } else if (hex.Value.Hint.Area == CellHintArea.COLUMN_LEFT) { Vec2d p1 = hex.Value.Image.GetEdge(0); Vec2d p2 = hex.Value.Image.GetEdge(1); Vec2d pm = p1 - p2; pm.Rotate(MathExt.ToRadians(-90)); pm.SetLength(hex.Value.Image.OCRHeight / 4); Point[] polypoints = new[] { p1, p2, p2 + pm, p1 + pm, p1 }.Select(p => new Point((int)p.X, (int)p.Y)).ToArray(); g.FillPolygon(bluebrush, polypoints); g.DrawPolygon(bluepen, polypoints); } else if (hex.Value.Hint.Area == CellHintArea.COLUMN_DOWN) { Vec2d p1 = hex.Value.Image.GetEdge(5); Vec2d p2 = hex.Value.Image.GetEdge(0); Vec2d pm = p1 - p2; pm.Rotate(MathExt.ToRadians(-90)); pm.SetLength(hex.Value.Image.OCRHeight / 4); Point[] polypoints = new[] { p1, p2, p2 + pm, p1 + pm, p1 }.Select(p => new Point((int)p.X, (int)p.Y)).ToArray(); g.FillPolygon(bluebrush, polypoints); g.DrawPolygon(bluepen, polypoints); } else if (hex.Value.Hint.Area == CellHintArea.COLUMN_RIGHT) { Vec2d p1 = hex.Value.Image.GetEdge(4); Vec2d p2 = hex.Value.Image.GetEdge(5); Vec2d pm = p1 - p2; pm.Rotate(MathExt.ToRadians(-90)); pm.SetLength(hex.Value.Image.OCRHeight / 4); Point[] polypoints = new[] { p1, p2, p2 + pm, p1 + pm, p1 }.Select(p => new Point((int)p.X, (int)p.Y)).ToArray(); g.FillPolygon(bluebrush, polypoints); g.DrawPolygon(bluepen, polypoints); } g.DrawString(hex.Value.Hint.ToString(), fnt, fntBush1, hex.Value.Image.BoundingBox, fmt); } else { if (hex.Value.Type == HexagonType.NOCELL || hex.Value.Type == HexagonType.HIDDEN) { g.DrawString(hex.Value.Hint.ToString(), fnt, fntBush2, hex.Value.Image.BoundingBox, fmt); } else if (hex.Value.Type == HexagonType.UNKNOWN) { g.DrawString(hex.Value.Hint.ToString(), fnt, fntBush3, hex.Value.Image.BoundingBox, fmt); } else { g.DrawString(hex.Value.Hint.ToString(), fnt, fntBush1, hex.Value.Image.BoundingBox, fmt); } } } g.FillRectangle(new SolidBrush(Color.SlateGray), grid.CounterArea.BoundingBox); g.DrawString(grid.CounterArea.Value.Value.ToString(), fnt_big, fntBush1, grid.CounterArea.BoundingBox, fmt); } return(shot); }
public void RotateObjects(float angle) { //Check if all objects are bricks with same geometry if (AreSelectedObjectsBricksWithSameGeometry()) { RotateBricks(angle); return; } LevelEntryCollection objects = new LevelEntryCollection(GetSelectedObjects()); if (objects.Count == 1) { if (objects[0] is Brick) { CreateUndoPoint(); ((Brick)objects[0]).Rotation = MathExt.FixAngle(((Brick)objects[0]).Rotation + angle); UpdateRedraw(); } return; } if (objects.Count < 2) { return; } CreateUndoPoint(); //Get resize rect float left = float.MaxValue; float top = float.MaxValue; float right = float.MinValue; float bottom = float.MinValue; foreach (LevelEntry obj in objects) { if (left > obj.X) { left = obj.X; } if (right < obj.X) { right = obj.X; } if (top > obj.Y) { top = obj.Y; } if (bottom < obj.Y) { bottom = obj.Y; } } float width = right - left; float height = bottom - top; Matrix matrix = new Matrix(); matrix.RotateAt(angle, new PointF(left + (width / 2.0f), top + (height / 2.0f))); foreach (LevelEntry obj in objects) { PointF[] pnts = new PointF[] { new PointF(obj.X, obj.Y) }; matrix.TransformPoints(pnts); obj.X = pnts[0].X; obj.Y = pnts[0].Y; if (obj is Brick) { Brick brick = (Brick)obj; brick.Rotation = MathExt.FixAngle(brick.Rotation); brick.Rotation -= angle; } } UpdateRedraw(); }
public override ScaleXy GetValue(Keyframe <ScaleXy> keyframe, float keyframeProgress) { if (keyframe.StartValue == null || keyframe.EndValue == null) { throw new InvalidOperationException("Missing values for keyframe."); } var startTransform = keyframe.StartValue; var endTransform = keyframe.EndValue; if (ValueCallback != null) { return(ValueCallback.GetValueInternal(keyframe.StartFrame.Value, keyframe.EndFrame.Value, startTransform, endTransform, keyframeProgress, LinearCurrentKeyframeProgress, Progress)); } return(new ScaleXy(MathExt.Lerp(startTransform.ScaleX, endTransform.ScaleX, keyframeProgress), MathExt.Lerp(startTransform.ScaleY, endTransform.ScaleY, keyframeProgress))); }
/// <summary> /// Constructs a new instance. /// </summary> /// <param name="depth">desired capacity (number of data words)</param> /// <param name="width">desired data word width</param> public SimpleDPRAM(uint depth, uint width) { _depth = MathExt.CeilPow2(depth); _width = width; _content = Enumerable.Repeat(StdLogicVector.Us(width), (int)_depth).ToArray(); }
protected override int GetLength() { return(MathExt.NextMultipleOf4(8 + (Name?.Length ?? 0) + (Description?.Length ?? 0))); }
/// <summary> /// Computes the contact forces just before integrating the EOM. /// This routine is using Lagrange multipliers and the projected Gauss-Seidel /// (PGS) method. /// Reference: See Erin Catto, "Iterative Dynamics with Temporal Coherence", /// February 22, 2005 /// In JSBSim there is only one rigid body (the aircraft) and there can be /// multiple points of contact between the aircraft and the ground. As a /// consequence our matrix Jac*M^-1*Jac^T is not sparse and the algorithm /// described in Catto's paper has been adapted accordingly. /// The friction forces are resolved in the body frame relative to the origin /// (Earth center). /// </summary> /// <param name="dt"></param> private void CalculateFrictionForces(double dt) { List <LagrangeMultiplier> multipliers = inputs.MultipliersList; int n = multipliers.Count; vFrictionForces = Vector3D.Zero; vFrictionMoments = Vector3D.Zero; // If no gears are in contact with the ground then return if (n == 0) { return; } List <double> a = new List <double>(n * n); // Will contain Jac*M^-1*Jac^T List <double> rhs = new List <double>(n); // Assemble the linear system of equations for (int i = 0; i < n; i++) { Vector3D U = multipliers[i].ForceJacobian; Vector3D r = multipliers[i].LeverArm; Vector3D v1 = U / inputs.Mass; Vector3D v2 = inputs.Jinv * (r * U); // Should be J^-T but J is symmetric and so is J^-1 for (int j = 0; j < i; j++) { a[i * n + j] = a[j * n + i]; // Takes advantage of the symmetry of Jac^T*M^-1*Jac } for (int j = i; j < n; j++) { U = multipliers[j].ForceJacobian; r = multipliers[j].LeverArm; a[i * n + j] = Vector3D.Dot(U, v1 + v2 * r); } } // Assemble the RHS member // Translation Vector3D vdot = vUVWdot; if (dt > 0.0) // Zeroes out the relative movement between the aircraft and the ground { vdot += (inputs.vUVW - inputs.Tec2b * inputs.TerrainVelocity) / dt; } // Rotation Vector3D wdot = vPQRdot; if (dt > 0.0) // Zeroes out the relative movement between the aircraft and the ground { wdot += (inputs.vPQR - inputs.Tec2b * inputs.TerrainAngularVel) / dt; } // Prepare the linear system for the Gauss-Seidel algorithm : // 1. Compute the right hand side member 'rhs' // 2. Divide every line of 'a' and 'rhs' by a[i,i]. This is in order to save // a division computation at each iteration of Gauss-Seidel. for (int i = 0; i < n; i++) { double d = a[i * n + i]; Vector3D U = multipliers[i].ForceJacobian; Vector3D r = multipliers[i].LeverArm; rhs[i] = -Vector3D.Dot(U, vdot + wdot * r) / d; for (int j = 0; j < n; j++) { a[i * n + j] /= d; } } // Resolve the Lagrange multipliers with the projected Gauss-Seidel method for (int iter = 0; iter < 50; iter++) { double norm = 0.0; for (int i = 0; i < n; i++) { double lambda0 = multipliers[i].value; double dlambda = rhs[i]; for (int j = 0; j < n; j++) { dlambda -= a[i * n + j] * multipliers[j].value; } var tmp = multipliers[i]; tmp.value = MathExt.Constrain(multipliers[i].Min, lambda0 + dlambda, multipliers[i].Max); multipliers[i] = tmp; dlambda = multipliers[i].value - lambda0; norm += Math.Abs(dlambda); } if (norm < 1E-5) { break; } } // Calculate the total friction forces and moments for (int i = 0; i < n; i++) { double lambda = multipliers[i].value; Vector3D U = multipliers[i].ForceJacobian; Vector3D r = multipliers[i].LeverArm; Vector3D F = lambda * U; vFrictionForces += F; vFrictionMoments += r * F; } Vector3D accel = vFrictionForces / inputs.Mass; Vector3D omegadot = inputs.Jinv * vFrictionMoments; vBodyAccel += accel; vUVWdot += accel; vUVWidot += inputs.Tb2i * accel; vPQRdot += omegadot; vPQRidot += omegadot; }
public void min_returns_the_minimum_value_for_value_types(int first, int second, int expected) { Assert.Equal(expected, MathExt.Min(first, second)); }
private PointF GetBrickAngularPoint(PointF circleCentre, float angle, float radius) { return(new PointF((float)Math.Cos(MathExt.ToRadians(angle)) * radius + circleCentre.X, (float)Math.Sin(MathExt.ToRadians(angle)) * radius + circleCentre.Y)); }
public void min_returns_the_minimum_value_for_reference_types(string first, string second, string expected) { Assert.Equal(expected, MathExt.Min(first, second)); }
public static float closestPoints(LineSegment seg1, LineSegment seg2, out float s, out float t, out Vector3 c1, out Vector3 c2) { Vector3 d1 = seg1.myB - seg1.myA; Vector3 d2 = seg2.myB - seg2.myA; Vector3 r = seg1.myA - seg2.myA; float a = Vector3.Dot(d1, d1); float e = Vector3.Dot(d2, d2); float f = Vector3.Dot(d2, r); if (a <= float.Epsilon && e <= float.Epsilon) { s = t = 0; c1 = seg1.myA; c2 = seg2.myA; return(Vector3.Dot(c1 - c2, c1 - c2)); } if (a <= float.Epsilon) { s = 0; t = f / e; t = MathExt.clamp(t, 0.0f, 1.0f); } else { float c = Vector3.Dot(d1, r); if (e <= float.Epsilon) { t = 0.0f; s = MathExt.clamp(-c / a, 0.0f, 1.0f); } else { float b = Vector3.Dot(d1, d2); float denom = a * e - b * b; if (denom != 0.0f) { s = MathExt.clamp((b * f - c * e) / denom, 0.0f, 1.0f); } else { s = 0; } t = (b * s + f) / e; if (t < 0.0f) { t = 0.0f; s = MathExt.clamp(-c / a, 0.0f, 1.0f); } else if (t > 1.0f) { t = 1.0f; s = MathExt.clamp((b - c) / a, 0.0f, 1.0f); } } } c1 = seg1.myA + d1 * s; c2 = seg2.myA + d2 * t; return(Vector3.Dot(c1 - c2, c1 - c2)); }
public void Execute() { ActualResult = MathExt.RemapValue(Value, InMin, InMax, OutMin, OutMax, Clamp); Assert.AreEqual(ExpectedResult, ActualResult); }
public void WriteGenericData(BinaryWriter bw, int version) { //Set flags FlagGroup f = new FlagGroup(); f[0] = (mRolly != 0.0f); f[1] = (mBouncy != 0.0f); f[2] = HasPegInfo; f[3] = HasMovementInfo; f[5] = mCollision; f[6] = mVisible; f[7] = mCanMove; f[8] = (mSolidColour != Color.Black); f[9] = (mOutlineColour != Color.Black); f[10] = !String.IsNullOrEmpty(mImageFilename); f[11] = (mImageDX != 0.0f); f[12] = (mImageDY != 0.0f); f[13] = (mImageRotation != 0.0f); f[14] = mBackground; f[15] = mBaseObject; f[17] = !String.IsNullOrEmpty(mID); f[19] = (mSound != 0); f[20] = mBallStopReset; f[21] = !String.IsNullOrEmpty(mLogic); f[22] = mForeground; f[23] = (mMaxBounceVelocity != 0.0f); f[24] = mDrawSort; f[25] = mForeground2; f[26] = (mSubID != 0); f[27] = (mFlipperFlags != 0); f[28] = mDrawFloat; f[30] = (mShadow && version >= 0x50); //Write data bw.Write(f.Int32); if (f[0]) { bw.Write(mRolly); } if (f[1]) { bw.Write(mBouncy); } if (f[8]) { bw.Write(mSolidColour.ToArgb()); } if (f[9]) { bw.Write(mOutlineColour.ToArgb()); } if (f[10]) { LevelWriter.WritePopcapString(bw, mImageFilename); } if (f[11]) { bw.Write(mImageDX); } if (f[12]) { bw.Write(mImageDY); } if (f[13]) { bw.Write(MathExt.ToRadians(mImageRotation)); } if (f[17]) { LevelWriter.WritePopcapString(bw, mID); } if (f[19]) { bw.Write(mSolidColour.ToArgb()); } if (f[21]) { LevelWriter.WritePopcapString(bw, mLogic); } if (f[23]) { bw.Write(mMaxBounceVelocity); } if (f[26]) { bw.Write(mSubID); } if (f[27]) { bw.Write(mFlipperFlags); } if (f[2]) { mPegInfo.WriteData(bw, version); } if (f[3]) { mMovement.WriteData(bw, version); } }
/// <summary> /// Computes a memory layout for a given type descriptor. /// </summary> /// <param name="td">type descriptor to layout</param> /// <param name="info">marshalling information</param> /// <returns>memory layout</returns> public static MemoryLayout Layout(TypeDescriptor td, IMarshalInfo info) { Type type = td.CILType; ISerializer ser = SLVSerializable.TryGetSerializer(type); if (ser != null) { object sample = td.GetSampleInstance(); return(CreatePrimLayout(ser.Serialize(sample).Size, td, info)); } if (ser == null && td.HasIntrinsicTypeOverride) { throw new InvalidOperationException("Type " + type.Name + " has intrinsic type override but no serializer"); } if (type.IsEnum) { return(new EnumMemoryLayout(td, info)); } if (type.IsArray) { td.AssertStatic(); TypeDescriptor elemTd = td.Element0Type; MemoryLayout elemLayout = Layout(elemTd, info); ulong subStride = elemLayout.SizeInBits; if (subStride == 0) { return(new EmptyMemoryLayout(td) { Size = 0, SizeInBits = 0 }); } ulong[] strides = new ulong[type.GetArrayRank()]; ulong elemsPerWord = (ulong)info.WordSize / elemLayout.SizeInBits; ulong wordsPerElem = elemLayout.Size; if (elemsPerWord > 1) { if (info.UseArraySubWordAlignment) { if (info.UseArrayDimPow2Alignment) { elemsPerWord = MathExt.FloorPow2(elemsPerWord); subStride = info.WordSize / elemsPerWord; } } else { elemsPerWord = 1; } } ulong dimSize = (ulong)(int)td.TypeParams.Last(); ulong dimWords; if (elemsPerWord <= 1) { subStride = 0; if (info.UseArrayDimPow2Alignment) { wordsPerElem = MathExt.CeilPow2(wordsPerElem); } dimWords = wordsPerElem * dimSize; } else { wordsPerElem = 0; dimWords = (dimSize + elemsPerWord - 1) / elemsPerWord; } strides[strides.Length - 1] = wordsPerElem; for (int i = strides.Length - 2; i >= 0; i--) { if (info.UseArrayDimPow2Alignment) { dimWords = MathExt.CeilPow2(dimWords); } strides[i] = dimWords; dimSize = (ulong)(int)td.TypeParams[i]; dimWords *= dimSize; } return(new ArrayMemoryLayout(td, info.WordSize, strides, subStride, (uint)elemsPerWord, (uint)wordsPerElem, elemLayout) { Size = dimWords, SizeInBits = dimWords * info.WordSize }); } if (type.IsValueType && !type.IsPrimitive) { StructMemoryLayout ml = new StructMemoryLayout(td); FieldInfo[] fields = type.GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); ulong offset = 0; foreach (FieldInfo field in fields) { TypeDescriptor fieldTd = td.GetFieldType(field); MemoryLayout fieldLayout = Layout(fieldTd, info); FieldLocation fieldLoc = new FieldLocation(field, fieldLayout, offset); ml.AddLocation(fieldLoc); offset += fieldLayout.Size; } ml.Size = offset; ml.SizeInBits = offset * info.WordSize; return(ml); } throw new InvalidOperationException("Unable to create data layout for type " + type.Name); }
private void CreateStarPath() { var points = _pointsAnimation.Value.Value; double currentAngle = _rotationAnimation?.Value ?? 0f; // Start at +y instead of +x currentAngle -= 90; // convert to radians currentAngle = MathExt.ToRadians(currentAngle); // adjust current angle for partial points var anglePerPoint = (float)(2 * Math.PI / points); var halfAnglePerPoint = anglePerPoint / 2.0f; var partialPointAmount = points - (int)points; if (partialPointAmount != 0) { currentAngle += halfAnglePerPoint * (1f - partialPointAmount); } var outerRadius = _outerRadiusAnimation.Value.Value; var innerRadius = _innerRadiusAnimation.Value.Value; var innerRoundedness = 0f; if (_innerRoundednessAnimation != null) { innerRoundedness = _innerRoundednessAnimation.Value.Value / 100f; } var outerRoundedness = 0f; if (_outerRoundednessAnimation != null) { outerRoundedness = _outerRoundednessAnimation.Value.Value / 100f; } float x; float y; float partialPointRadius = 0; if (partialPointAmount != 0) { partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius); x = (float)(partialPointRadius * Math.Cos(currentAngle)); y = (float)(partialPointRadius * Math.Sin(currentAngle)); _path.MoveTo(x, y); currentAngle += anglePerPoint * partialPointAmount / 2f; } else { x = (float)(outerRadius * Math.Cos(currentAngle)); y = (float)(outerRadius * Math.Sin(currentAngle)); _path.MoveTo(x, y); currentAngle += halfAnglePerPoint; } // True means the line will go to outer radius. False means inner radius. var longSegment = false; var numPoints = (int)Math.Ceiling(points) * 2; for (var i = 0; i < numPoints; i++) { var radius = longSegment ? outerRadius : innerRadius; var dTheta = halfAnglePerPoint; if (partialPointRadius != 0 && i == numPoints - 2) { dTheta = anglePerPoint * partialPointAmount / 2f; } if (partialPointRadius != 0 && i == numPoints - 1) { radius = partialPointRadius; } var previousX = x; var previousY = y; x = (float)(radius * Math.Cos(currentAngle)); y = (float)(radius * Math.Sin(currentAngle)); if (innerRoundedness == 0 && outerRoundedness == 0) { _path.LineTo(x, y); } else { var cp1Theta = (float)(Math.Atan2(previousY, previousX) - Math.PI / 2f); var cp1Dx = (float)Math.Cos(cp1Theta); var cp1Dy = (float)Math.Sin(cp1Theta); var cp2Theta = (float)(Math.Atan2(y, x) - Math.PI / 2f); var cp2Dx = (float)Math.Cos(cp2Theta); var cp2Dy = (float)Math.Sin(cp2Theta); var cp1Roundedness = longSegment ? innerRoundedness : outerRoundedness; var cp2Roundedness = longSegment ? outerRoundedness : innerRoundedness; var cp1Radius = longSegment ? innerRadius : outerRadius; var cp2Radius = longSegment ? outerRadius : innerRadius; var cp1X = cp1Radius * cp1Roundedness * PolystarMagicNumber * cp1Dx; var cp1Y = cp1Radius * cp1Roundedness * PolystarMagicNumber * cp1Dy; var cp2X = cp2Radius * cp2Roundedness * PolystarMagicNumber * cp2Dx; var cp2Y = cp2Radius * cp2Roundedness * PolystarMagicNumber * cp2Dy; if (partialPointAmount != 0) { if (i == 0) { cp1X *= partialPointAmount; cp1Y *= partialPointAmount; } else if (i == numPoints - 1) { cp2X *= partialPointAmount; cp2Y *= partialPointAmount; } } _path.CubicTo(previousX - cp1X, previousY - cp1Y, x + cp2X, y + cp2Y, x, y); } currentAngle += dTheta; longSegment = !longSegment; } var position = _positionAnimation.Value; _path.Offset(position.Value.X, position.Value.Y); _path.Close(); }
public SpectrumAnalyser() { filterParams.Spectrum = new float[Globals.SPECTRUMRES]; filterParams.SpectrumDB = new float[Globals.SPECTRUMRES]; filterParams.Spectrum2 = new float[Globals.SPECTRUM2RES]; filterParams.Spectrum2DB = new float[Globals.SPECTRUM2RES]; filterParams.SpectrumHistory = SpectrumHistory; // The order of these is important as they define where filter outputs end up in the analysis data texture. AddFilter(new PeakFrequencyFilter("PFF", 12, Globals.SPECTRUMRES / 3 - 12)); //AddFilter(new MultiPeakFrequencyFilter("MPFF", 12, Globals.SPECTRUMRES / 3 - 12)); AddFilter(new MultiPeakFrequencyFilter("MPFF", 12, Globals.SPECTRUMRES - 20)); AddFilter(new KickDrumFilter3("KD3", 0, 6)); AddFilter(new KickDrumFilter2("KD2A", 0, 4)); AddFilter(new KickDrumFilter2("KD2B", 0, 8)); AddFilter(new DistributionFilter("DF")); AddFilter(new KickDrumFilter("KD1")); AddFilter(new BroadbandTransientFilter("HH1", (f, i) => f.Spectrum2[i], 96, 128, MathExt.Flat(2)) { TriggerHigh = 0.5f, TriggerLow = 0.45f, MaxGain = 4f }); // 256 spectrum AddFilter(new BroadbandTransientFilter("HH2", (f, i) => f.Spectrum2[i], 96, 128, MathExt.Flat(2)) { TriggerHigh = 0.8f, TriggerLow = 0.75f, MaxGain = 4f }); // 256 spectrum AddFilter(new BroadbandTransientFilter("BD", (f, i) => f.Spectrum[i], 0, 12, MathExt.Flat(4)) { TriggerHigh = 0.5f, TriggerLow = 0.45f, MaxGain = 6f }); // 256 spectrum AddFilter(new BroadbandTransientFilter("SN", (f, i) => f.Spectrum2[i], 32, 96, MathExt.LinearDecay(16)) { TriggerHigh = 0.8f, TriggerLow = 0.75f, MaxGain = 8f }); // 256 spectrum //AddFilter(new BroadbandTransientFilter("HH2", (f, i) => f.Spectrum2DB[i], 128, 96, Enumerable.Range(0, 16).Select(i => i < 8 ? 0.05f : -0.02f).ToArray()) { TriggerHigh = 0.4f, TriggerLow = 0.35f }); // 256 spectrum //AddFilter(new BroadbandTransientFilter("CL1", 8, 16) { Threshold = 0.15f }); //AddFilter(new BroadbandTransientFilter("CL2", 16, 16) { Threshold = 0.15f }); //AddFilter(new NeuralNetworkFilter("NN01")); }
protected override int GetLength() { return(MathExt.NextMultipleOf4(24 + (Filename?.Length ?? 0))); }
public void TestCase() { Assert.AreEqual(MathExt.distance(new Vector2(0, 0), new Vector2(0, 1)), 1.0f); }
private static bool IsPrime(int n) => MathExt.IsPrime(n);
public void SkipToNearestMultipleOf4() { int targetLen = MathExt.NextMultipleOf4((int)pos); Skip((uint)(targetLen - pos)); }