/// <summary> /// Multiplies two dense matrices and returns the resultant matrix (using tiling). /// </summary> /// <param name="accelerator">The Accelerator to run the multiplication on</param> /// <param name="a">A dense MxK matrix</param> /// <param name="b">A dense KxN matrix</param> /// <returns>A dense MxN matrix</returns> static float[,] MatrixMultiplyTiled(Accelerator accelerator, float[,] a, float[,] b) { var m = a.GetLength(0); var ka = a.GetLength(1); var kb = b.GetLength(0); var n = b.GetLength(1); if (ka != kb) { throw new ArgumentException($"Cannot multiply {m}x{ka} matrix by {n}x{kb} matrix", nameof(b)); } var kernel = accelerator.LoadStreamKernel < ArrayView2D <float, Stride2D.DenseX>, ArrayView2D <float, Stride2D.DenseX>, ArrayView2D <float, Stride2D.DenseX> >( MatrixMultiplyTiledKernel); var groupSize = new Index2D(TILE_SIZE, TILE_SIZE); var numGroups = new Index2D((m + TILE_SIZE - 1) / TILE_SIZE, (n + TILE_SIZE - 1) / TILE_SIZE); using (var aBuffer = accelerator.Allocate2DDenseX <float>(new Index2D(m, ka))) using (var bBuffer = accelerator.Allocate2DDenseX <float>(new Index2D(ka, n))) using (var cBuffer = accelerator.Allocate2DDenseX <float>(new Index2D(m, n))) { aBuffer.CopyFromCPU(a); bBuffer.CopyFromCPU(b); kernel((numGroups, groupSize), aBuffer, bBuffer, cBuffer); accelerator.Synchronize(); return(cBuffer.GetAsArray2D()); } }
/// <summary> /// Searches for an item that matches the conditions defined by the specified /// predicate, and returns the <see cref="ItemRequestResult{T}"/> with underlying index /// of the first occurrence searched within the specified sector. Otherwise returns /// <see cref="ItemRequestResult{T}.Fail"/> /// <para> /// Exceptions:<br/> /// <see cref="ArgumentOutOfRangeException"/>: <paramref name="startIndex"/> must /// be within collection bounds;<br/> /// <paramref name="sectorSize"/> must be within collection bounds, beginning from /// <paramref name="startIndex"/>. /// </para> /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TRectCollection"> /// <typeparamref name="TRectCollection"/> is /// <see cref="IRectangularCollection{T}"/> /// </typeparam> /// <typeparam name="TPredicate"> /// <typeparamref name="TPredicate"/> is <see cref="IPredicate{T}"/> and /// <see langword="struct"/> /// </typeparam> /// <param name="source">The collection in which the operation takes place.</param> /// <param name="startIndex">Zero-based index from which searching starts.</param> /// <param name="sectorSize">The rectangular sector size to be searched.</param> /// <param name="match"> /// A <see langword="struct"/> implementing <see cref="IPredicate{T}"/> that defines /// the conditions of the element to search for. /// </param> /// <returns></returns> public static ItemRequestResult <Index2D> FindIndex < T, TRectCollection, TPredicate>( this TRectCollection source, Index2D startIndex, Bounds2D sectorSize, TPredicate match) where TRectCollection : IRectangularCollection <T> where TPredicate : struct, IPredicate <T> { if (!source.IsValidIndex(startIndex)) { throw new ArgumentOutOfRangeException( nameof(startIndex), "startIndex must be within collection bounds."); } var indexAfterEnd = new Index2D( startIndex.Dimension1Index + sectorSize.Length1, startIndex.Dimension2Index + sectorSize.Length2); Bounds2D sourceBounds = source.Boundaries; if (indexAfterEnd.Dimension1Index > sourceBounds.Length1 || indexAfterEnd.Dimension2Index > sourceBounds.Length2) { throw new ArgumentOutOfRangeException( nameof(sectorSize), "sectorSize must be within collection bounds, beginning from startIndex."); } return(source.FindIndexInternal <T, TRectCollection, TPredicate>( startIndex, sectorSize, match)); }
public static void TestRow(int row) { Index2D index = new Index2D(row, 1); Assert.AreEqual(index.Row, row); Assert.AreEqual(index.Dimension1Index, row); }
public void VisualizeSolution(IMatrix <int> matrix, ISolution solution) { var text = new StringBuilder(); var splitted = new SplittedMatrix(matrix, solution); var index = new Index2D(); for (int i = 0; i < splitted.Size(0); i++) //строка разбитой матрицы { if (i != 0) { text.AppendLine(); } for (index.I = splitted.CellLow(i, 0); index.I <= splitted.CellHigh(i, 0); index.I++) //строка исходной матрицы, попавшая в строку разбитой матрицы { for (int j = 0; j < splitted.Size(1); j++) //столбец разбитой матрицы { if (j != 0) { text.AppendFormat(" "); } for (index.J = splitted.CellLow(j, 1); index.J <= splitted.CellHigh(j, 1); index.J++) //столбец исходной матрицы, попавший в столбец разбитой матрицы { text.AppendFormat("{0,3} ", matrix[index]); } } text.AppendLine(); } } MessageBox.Show(text.ToString()); }
public static void TestColumns(int column) { Index2D index = new Index2D(1, column); Assert.AreEqual(index.Column, column); Assert.AreEqual(index.Dimension2Index, column); }
//internal override XElement ToXML() //{ // XElement e = new XElement("Enemy"); // e.SetAttributeValue("Type", this.GetType().ToString()); // e.SetAttributeValue("Name", Name); // e.SetAttributeValue("Speed", Speed); // e.SetAttributeValue("Health", Health); // e.SetAttributeValue("Pos", Pos); // //add other data about this type of enemy here // return e; //} internal static Wasp Parse(XElement e) { #if LEVELEDITOR Wasp g = new Wasp(); foreach (XAttribute attr in e.Attributes()) { if (attr.Name == "Name") { g.Name = attr.Value; } else if (attr.Name == "Health") { g.Health = int.Parse(attr.Value); } else if (attr.Name == "Speed") { g.Speed = float.Parse(attr.Value); } else if (attr.Name == "Pos") { g.Pos = Index2D.Parse(attr.Value); } } #else string name = e.Attribute("Name").Value; int health = int.Parse(e.Attribute("Health").Value); Index2D pos = Index2D.Parse(e.Attribute("Pos").Value); Microsoft.Xna.Framework.Vector2 initpos = new Microsoft.Xna.Framework.Vector2(pos.X, pos.Y); Wasp g = new Wasp(name, initpos); #endif return(g); }
public static void ThrowsExceptionIfSectorSizeIsOutOfBounds( List2D <byte> source, byte[,] destination, Bounds2D sectorSize, Index2D destIndex) => Assert.Throws <ArgumentOutOfRangeException>( () => source.CopyTo(destination, sectorSize, destIndex));
private HexEditor CreateHex(Index2D index) { var hex = ((HexEditor)GameObject.Instantiate(prototype, HexInfo.IndexToVector(index), new Quaternion())); hexMap.Add(index, hex); hex.Initialize(index, container); return hex; }
public BallMovedEventArgs(Board board, Index2D slotFrom, Index2D slotTo, GameObject ball) { Board = board; SlotFrom = slotFrom; SlotTo = slotTo; Ball = ball; }
public static Index2D Get(Index2D index1, Index2D index2, bool roundUp = false) { int x = MathUtilities.IntegerMidpoint(index1.X, index2.X, roundUp); int y = MathUtilities.IntegerMidpoint(index1.Y, index2.Y, roundUp); return(new Index2D(x, y)); }
protected override void SetBitmap() { for (int i = 0; i < solutionSizeColumn; i++) //строка разбитой матрицы { var lastOnI = splittedMatrix.CellHigh(i, 0); var index = new Index2D(); //строка исходной матрицы, попавшая в строку разбитой матрицы for (index.I = splittedMatrix.CellLow(i, 0); index.I <= lastOnI; index.I++) { for (int j = 0; j < solutionSizeRow; j++) //столбец разбитой матрицы { var lastOnJ = splittedMatrix.CellHigh(j, 1); //строка исходной матрицы, попавшая в столбец разбитой матрицы for (index.J = splittedMatrix.CellLow(j, 1); index.J <= lastOnJ; index.J++) { SetPixelToBitmapOfMatrix( (int)(coefficient * GetValueOfMatrixFrom(matrix[index])), index.I + i * zoomShift, index.J + j * zoomShift); } } } } }
/// <summary> /// Returns <see cref="ICollection{T}"/> containing all the elements that match the /// conditions defined by the specified predicate. /// <para> /// Exceptions:<br/> /// <see cref="NotSupportedException"/>: Provided type must support /// <see cref="ICollection{T}.Add(T)"/> method. /// </para> /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TCollection"> /// <typeparamref name = "TCollection"/> is <see cref="ICollection{T}"/> and has a /// parameterless constructor. /// </typeparam> /// <typeparam name="TRectCollection"> /// <typeparamref name="TRectCollection"/> is /// <see cref="IRectangularCollection{T}"/> /// </typeparam> /// <typeparam name="TPredicate"> /// <typeparamref name = "TPredicate"/> is <see cref="IPredicate{T}"/> and /// <see langword="struct"/> /// </typeparam> /// <param name="source">The collection in which the operation takes place.</param> /// <param name="match"> /// A <see langword="struct"/> implementing <see cref="IPredicate{T}"/> that defines /// the conditions of the element to search for. /// </param> /// <returns></returns> public static TCollection FindAll < T, TCollection, TRectCollection, TPredicate>( this TRectCollection source, TPredicate match) where TCollection : ICollection <T>, new() where TRectCollection : IRectangularCollection <T> where TPredicate : struct, IPredicate <T> { var resizableCollection = new TCollection(); try { Bounds2D bounds = source.Boundaries; for (int i = 0; i < bounds.Length1; i++) { for (int j = 0; j < bounds.Length2; j++) { var index = new Index2D(i, j); if (match.Invoke(source[index])) { resizableCollection.Add(source[index]); } } } } catch (NotSupportedException) { throw new NotSupportedException("Provided type must support Add(T) method."); } return(resizableCollection); }
public bool TryMoveBall(Index2D slotFrom, Index2D slotTo) { if (!TryGetBall(slotFrom, out var ballToMove)) { return(false); } if (TryGetBall(slotTo, out _)) { return(false); } ballMap[slotFrom] = null; ballMap[slotTo] = ballToMove; if (!TryGetTile(slotTo, out var tile)) { return(false); } ballToMove.transform.position = ObtainNewBallPosition(tile, ballToMove.transform.position.y); onBallMoved?.Invoke(this, new BallMovedEventArgs(this, slotFrom, slotTo, ballToMove)); return(true); }
/// <summary> /// Handles the array resizing if necessary when an index is accessed. /// </summary> /// <param name="index">The index being accessed.</param> /// <returns>The adjusted index to be used for accessing the backing array.</returns> private Index2D HandleArrayResizing(Index2D index) { int x = index.X; int y = index.Y; if (this.IsIndexInCurrentBounds(index)) { x += this.xOrigin; y += this.yOrigin; return(new Index2D(x, y)); } // determine size of new array int xOffset, yOffset; int xNewSize = DynamicArrayUtilities.HandleAxis(this.GetCurrentLength(Axis2D.X), ref x, ref this.xOrigin, out xOffset); int yNewSize = DynamicArrayUtilities.HandleAxis(this.GetCurrentLength(Axis2D.Y), ref y, ref this.yOrigin, out yOffset); // copy old array into new array T[,] newArray = new T[xNewSize, yNewSize]; foreach (KeyValuePair <Index2D, T> pair in this.array.GetIndexValuePairs()) { newArray[pair.Key.X + xOffset, pair.Key.Y + yOffset] = pair.Value; } this.array = newArray; return(new Index2D(x, y)); }
public static void ThrowsExceptionIfSectorSizeIsOutOfBounds <T>( Array2D <T> source, Array2D <T> destination, Bounds2D sectorSize, Index2D destIndex) => Assert.Throws <ArgumentOutOfRangeException>( () => source.CopyTo(destination, sectorSize, destIndex));
/// <summary> /// Searches for an item that matches the conditions defined by the specified /// predicate, and returns the <see cref="ItemRequestResult{T}"/> with underlying index /// of the last occurrence searched within the specified sector. Otherwise returns /// <see cref="ItemRequestResult{T}.Fail"/> /// <para> /// Exceptions:<br/> /// <see cref="ArgumentOutOfRangeException"/>: <paramref name="startIndex"/> must /// be within collection bounds;<br/> /// <paramref name="sectorSize"/> must be within collection bounds, beginning /// backwardly from <paramref name="startIndex"/>. /// </para> /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TRefRectCollection"> /// <typeparamref name="TRefRectCollection"/> is /// <see cref="IRefRectangularCollection{T}"/> /// </typeparam> /// <typeparam name="TPredicate"> /// <typeparamref name="TPredicate"/> is <see cref="IPredicate{T}"/> and /// <see langword="struct"/> /// </typeparam> /// <param name="source">The collection in which the operation takes place.</param> /// <param name="startIndex">Zero-based starting index of the backward search.</param> /// <param name="sectorSize">The rectangular sector size to be searched.</param> /// <param name="match"> /// A <see langword="struct"/> implementing <see cref="IPredicate{T}"/> that defines /// the conditions of the element to search for. /// </param> /// <returns></returns> public static ItemRequestResult <Index2D> FindLastIndex < T, TRefRectCollection, TPredicate>( this TRefRectCollection source, Index2D startIndex, Bounds2D sectorSize, TPredicate match) where TRefRectCollection : IRefRectangularCollection <T> where TPredicate : struct, IPredicate <T> { if (!source.IsValidIndex(startIndex)) { throw new ArgumentOutOfRangeException( nameof(startIndex), "startIndex must be within collection bounds."); } var indexAfterEnd = new Index2D( startIndex.Row - sectorSize.Rows, startIndex.Column - sectorSize.Columns); if (indexAfterEnd.Row < -1 || indexAfterEnd.Column < -1) { throw new ArgumentOutOfRangeException( nameof(sectorSize), "sectorSize must be within collection bounds, beginning backwardly from " + "startIndex."); } return(source.FindLastIndexInternal <T, TRefRectCollection, TPredicate>( startIndex, indexAfterEnd, match)); }
public static T Get <T>(this T[,] array, Index2D index) { Contracts.Requires.That(array != null); Contracts.Requires.That(array.IsIndexValid(index)); return(array[index.X, index.Y]); }
private static int LocalMaximumDiag(IMatrix <int> matrix, int I, int J) { int max = 0; var index = new Index2D(); for (index.I = I; index.I <= I + 1; index.I++) { for (index.J = 0; index.J < matrix.Size(1); index.J++) { if (max < matrix[index]) { max = matrix[index]; } } } for (index.J = J; index.J <= J + 1; index.J++) { for (index.I = 0; index.I < matrix.Size(0); index.I++) { if (max < matrix[index]) { max = matrix[index]; } } } return(max); }
public static void Set <T>(this T[,] array, Index2D index, T value) { Contracts.Requires.That(array != null); Contracts.Requires.That(array.IsIndexValid(index)); array[index.X, index.Y] = value; }
public void GroupedIndex2EntryPoint(int length) { var end = (int)Math.Sqrt(Accelerator.MaxNumThreadsPerGroup); for (int i = 1; i <= end; i <<= 1) { var stride = new Index2D(i, i); var extent = new KernelConfig( new Index2D(length, length), stride); using var buffer = Accelerator.Allocate1D <int>(extent.Size); buffer.MemSetToZero(Accelerator.DefaultStream); Execute(extent, buffer.View, stride, extent.GridDim.XY); var expected = new int[extent.Size]; for (int j = 0; j < length * length; ++j) { var gridIdx = Index2D.ReconstructIndex(j, extent.GridDim.XY); for (int k = 0; k < i * i; ++k) { var groupIdx = Index2D.ReconstructIndex(k, extent.GroupDim.XY); var idx = (gridIdx * stride + groupIdx).ComputeLinearIndex( extent.GridDim.XY); expected[idx] = idx; } } Verify(buffer.View, expected); } }
private void UpdateGrid(GridContent content, Index2D idx) { var widthDef = content.WidthDef; var heightDef = content.HeightDef; // Validate Spans if (idx.X + widthDef.Span > ColumnCount) { throw new ArgumentException("Column span is out of bound"); } if (idx.Y + heightDef.Span > RowCount) { throw new ArgumentException("Row span is out of bound"); } // Insert content for (int i = idx.X; i < idx.X + widthDef.Span; i++) { for (int j = idx.Y; j < idx.Y + heightDef.Span; j++) { // TODO: Implement auto for containers if (content.IsContent == false && (Columns[i].IsAuto || Rows[j].IsAuto)) { throw new NotImplementedException("Auto not implemented for containers"); } Grid[i, j] = content; } } }
/// <summary> /// Multiplies two dense matrices and returns the resultant matrix (using tiling). /// </summary> /// <param name="accelerator">The Accelerator to run the multiplication on</param> /// <param name="a">A dense MxK matrix</param> /// <param name="b">A dense KxN matrix</param> /// <returns>A dense MxN matrix</returns> static float[,] MatrixMultiplyTiled(Accelerator accelerator, float[,] a, float[,] b) { var m = a.GetLength(0); var ka = a.GetLength(1); var kb = b.GetLength(0); var n = b.GetLength(1); if (ka != kb) { throw new ArgumentException($"Cannot multiply {m}x{ka} matrix by {n}x{kb} matrix", nameof(b)); } var kernel = accelerator.LoadStreamKernel < ArrayView2D <float, Stride2D.DenseX>, ArrayView2D <float, Stride2D.DenseX>, ArrayView2D <float, Stride2D.DenseX> >( MatrixMultiplyTiledKernel); var groupSize = new Index2D(TILE_SIZE, TILE_SIZE); var numGroups = new Index2D((m + TILE_SIZE - 1) / TILE_SIZE, (n + TILE_SIZE - 1) / TILE_SIZE); using var aBuffer = accelerator.Allocate2DDenseX <float>(new Index2D(m, ka)); using var bBuffer = accelerator.Allocate2DDenseX <float>(new Index2D(ka, n)); using var cBuffer = accelerator.Allocate2DDenseX <float>(new Index2D(m, n)); aBuffer.CopyFromCPU(a); bBuffer.CopyFromCPU(b); kernel((numGroups, groupSize), aBuffer, bBuffer, cBuffer); // Reads data from the GPU buffer into a new CPU array. // Implicitly calls accelerator.DefaultStream.Synchronize() to ensure // that the kernel and memory copy are completed first. return(cBuffer.GetAsArray2D()); }
/// <summary> /// Initializes a new instance of the <see cref="OffsetArray2D{TValue}"/> class. /// </summary> /// <param name="array">The array to wrap.</param> /// <param name="offset">The offset of the zero origin.</param> public OffsetArray2D(IBoundedIndexable <Index2D, T> array, Index2D offset) { Contracts.Requires.That(array != null); this.array = array; this.offset = offset; }
public bool TrySpawnBall(Index2D slot = null, Color32?color = null) { if (slot == null) { if (!TryGetRandomAvailableSlot(Board, out slot)) { return(false); } } if (!Board.TryGetTile(slot, out var tile)) { return(false); } color ??= BallColorPool.GetRandomColor(); var ballStyle = ballStyleRepository.ObtainDefault(); var tilePosition = tile.transform.position; var ballPosition = new Vector3( tilePosition.x, (Board.TileStyle.Size + ballStyle.UniformScale) * 0.5f, tilePosition.z ); var ball = ballFactory.Create(ballPosition, color.Value, ballStyle); ball.name = "Ball_" + slot.ColumnIndex + "_" + slot.RowIndex; ball.AddComponent <Rigidbody>(); return(Board.TrySpawnBall(ball, slot)); }
public static ItemRequestResult <Index2D> Test <FloatPredicate>( ReadOnlyMatrix4x4 matrix, Index2D startIndex, Bounds2D sector, FloatPredicate match) where FloatPredicate : struct, IPredicate <float> => matrix.FindIndex <float, ReadOnlyMatrix4x4, FloatPredicate>( startIndex, sector, match);
/// <summary> /// Initializes a new instance of the <see cref="MultidirectionalDynamicArray2D{TValue}"/> class. /// </summary> /// <param name="dimensions">The dimensions of the array.</param> public MultidirectionalDynamicArray2D(Index2D dimensions) { Contracts.Requires.That(dimensions.IsAllPositive()); this.array = new T[dimensions.X, dimensions.Y]; this.xOrigin = dimensions.X / 2; this.yOrigin = dimensions.Y / 2; }
/// <inheritdoc /> protected override void DeserializeValues( Index2D lowerBounds, Index2D dimensions, byte[] buffer, ref int index, TIndexable result) { foreach (var resultIndex in Index.Range(lowerBounds, dimensions)) { result[resultIndex] = this.ValueSerializer.Deserialize(buffer, ref index); } }
/// <inheritdoc /> protected override void SerializeValues( TIndexable value, Index2D lowerBounds, Index2D dimensions, byte[] buffer, ref int index) { foreach (var valueIndex in Index.Range(lowerBounds, dimensions)) { this.ValueSerializer.Serialize(value[valueIndex], buffer, ref index); } }
public static void ThrowsExceptionIfSourceIndexIsOutOfBounds <T>( Array2D <T> src, Index2D srcIndex) => Assert.Throws <ArgumentOutOfRangeException>( () => src.CopyTo( srcIndex, new Array2D <T>(src.Rows, src.Columns), new Bounds2D(), new Index2D()));
public static void ThrowsExceptionIfSectorSizeIsOutOfBounds( Array2D <byte> src, Index2D srcIndex, byte[,] dest, Bounds2D sectorSize, Index2D destIndex) => Assert.Throws <ArgumentOutOfRangeException>( () => src.CopyTo(srcIndex, dest, sectorSize, destIndex));
public static void ThrowsExceptionIfSourceIndexIsOutOfBounds( List2D <byte> src, Index2D srcIndex) => Assert.Throws <ArgumentOutOfRangeException>( () => src.CopyTo( srcIndex, new byte[src.Rows, src.Columns], new Bounds2D(), new Index2D()));
public static Index2D[] GetCircumIndices(Index2D centerIndex) { var circumIndices = new Index2D[] { centerIndex.Offset(0,2), centerIndex.Offset(1,1), centerIndex.Offset(1,-1), centerIndex.Offset(0,-2), centerIndex.Offset(-1,-1), centerIndex.Offset(-1,1) }; return circumIndices; }
public virtual void SetIndex(Index2D index) { Index = index; CircumIndices = HexInfo.GetCircumIndices(index); }
public NullHex(Index2D index) : this(index, true) { }
public NullHex(Index2D index, bool defined) { Defined = defined; Index = index; CircumIndices = HexInfo.GetCircumIndices(index); }
public static Vector3 IndexToVector(Index2D index, float height = 0) { return new Vector3(index.X * X_METRIC_K * A, height, index.Y * R); }
public CopyInfo(Index2D source, Index2D destination, Size2D size) { this.Source = source; this.Destination = destination; this.Size = size; }