예제 #1
0
        protected DeadlockFinder(Level level, Array2D<bool> simpleDeadlockMap)
        {
            this.level = level;
            this.simpleDeadlockMap = simpleDeadlockMap;

            Initialize();
        }
예제 #2
0
        public DijkstraPathFinder(Level level)
            : base(level)
        {
            data = level.Data;
            rowLimit = level.Height - 1;
            insideCoordinates = level.InsideCoordinates;
            int m = level.Height * level.Width;
            q = new FixedQueue<Vertex>(m);

            // Initialize the vertex map.
            vertexMap = new Array2D<Vertex>(level.Height, level.Width);
            foreach (Coordinate2D coord in level.Coordinates)
            {
                Vertex vertex = new Vertex(coord.Row, coord.Column);
                vertex.Distance = DefaultInaccessible;
                vertex.Visited = true;
                vertexMap[coord.Row, coord.Column] = vertex;
            }

            // Calculate the neighbors of each coordinate.
            foreach (Coordinate2D coord in level.InsideCoordinates)
            {
                Vertex vertex = vertexMap[coord];
                List<Vertex> neighbors = new List<Vertex>();
                foreach (Coordinate2D neighbor in coord.FourNeighbors)
                {
                    if (level.IsFloor(neighbor))
                    {
                        neighbors.Add(vertexMap[neighbor]);
                    }
                }
                vertex.Neighbors = neighbors.ToArray();
            }
        }
예제 #3
0
    void Awake()
    {
        tiles_ = new Array2D<char>( size_ );
        colors_ = new Array2D<Color32>( size_ );

        mesh_ = GetComponent<FontMesh>();
    }
예제 #4
0
        protected ArrayPathFinder(Level level)
            : base(level)
        {
            data = level.Data;
            boxCoordinates = level.BoxCoordinates;
            boxCount = boxCoordinates.Length;
            n = level.Width;
            m = level.Height * level.Width;
            q = new FixedQueue<int>(m);

            firstInside = -1;
            lastInside = -1;
            neighborMap = new int[m][];
            foreach (Coordinate2D coord in level.InsideCoordinates)
            {
                lastInside = coord.Row * n + coord.Column;
                if (firstInside == -1)
                {
                    firstInside = lastInside;
                }

                List<int> neighbors = new List<int>();
                foreach (Coordinate2D neighbor in coord.FourNeighbors)
                {
                    if (level.IsFloor(neighbor))
                    {
                        neighbors.Add(neighbor.Row * n + neighbor.Column);
                    }
                }
                neighborMap[coord.Row * n + coord.Column] = neighbors.ToArray();
            }
            insideCount = lastInside - firstInside + 1;
        }
 public WorkingEntry(bool deadlocked, Array2D<bool> map, Coordinate2D coordinate, Coordinate2D[] coordinates)
 {
     Deadlocked = deadlocked;
     Map = map;
     Coordinate = coordinate;
     Coordinates = coordinates;
 }
예제 #6
0
    public TriangleMeshActor(Game game, Vector3 position, float scale,
        Texture2D heightMap,
        float[,] heightData)
        : base(game)
    {
        this.position = position;
        this.scale = new Vector3(1,1,1);

        _body = new Body();

        _body.MoveTo(position, Matrix.Identity);

        Array2D field = new Array2D(heightData.GetUpperBound(0), heightData.GetUpperBound(1));

        int upperZ = heightData.GetUpperBound(1);
        for (int x = 0; x < heightData.GetUpperBound(0); x++)
        {
            for (int z = 0; z < upperZ; z++)
            {
                field.SetAt(x, z, heightData[x, upperZ - 1 - z]);
            }
        }

        _skin = new CollisionSkin(null);

        float X = heightMap.Width / 2 * scale;
        float Z = heightMap.Height / 2 * scale;
        _skin.AddPrimitive(new Heightmap(field, X, -Z, scale, scale), new MaterialProperties(0.7f, 0.7f, 0.6f));

        _skin.ExternalData = this;

        PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(_skin);
    }
 public Entry(bool deadlocked, Array2D<bool> map, Coordinate2D coordinate, Coordinate2D[] coordinates, Entry[] entries)
 {
     Deadlocked = deadlocked;
     Map = map;
     Coordinate = coordinate;
     Coordinates = coordinates;
     Entries = entries;
 }
 public IncrementalRegionFinder(Level level)
     : base(level)
 {
     this.data = level.Data;
     this.pathFinder = new IncrementalAnyPathFinder(level);
     this.rowLimit = level.Height - 1;
     this.accessibleSquaresLimit = level.InsideSquares - level.Boxes;
 }
예제 #9
0
        public BruteForceRegionFinder(Level level)
            : base(level)
        {
            this.pathFinder = PathFinder.CreateInstance(level);

            // Initialize map of coordinates already tried.
            tried = new Array2D<bool>(level.Height, level.Width);
        }
예제 #10
0
        protected SubsetSolver(Level level, bool incremental)
        {
            this.level = level;

            pathFinder = PathFinder.CreateInstance(level,false, incremental);
            regionFinder = RegionFinder.CreateInstance(level);

            sokobanMap = new Array2D<bool>(level.Height, level.Width);
            cancelInfo = new CancelInfo();
        }
예제 #11
0
        public static void DrawTogglesGUILayout(IntVector2 size, List<IntVector2> points = null)
        {
            if (toggleStates_ == null)
                toggleStates_ = new Array2D<bool>(size);

            if( toggleStates_.size_ != size )
            {
            //				var oldStates = new Array2D<bool>(toggleStates_);
                toggleStates_ = new Array2D<bool>(size);
                //toggleStates_.Merge(oldStates);
            }

            var style = new GUIStyle(EditorStyles.toolbarButton);
            style.fixedWidth = 20;
            style.fixedHeight = 20;

            GUILayout.BeginVertical();
            for (int y = 0; y < size.y; ++y)
            {
                GUILayout.BeginHorizontal();
                for (int x = 0; x < size.x; ++x)
                {
                    var pos = new IntVector2(x, y);

                    var toggle = toggleStates_[pos];

                    if( toggle )
                    {
                        var oldColor = GUI.color;
                        GUI.color = Color.blue;

                        toggleStates_[pos] = GUILayout.Toggle(toggleStates_[pos], GUIContent.none, style);
                        GUI.color = oldColor;
                    }
                    else
                    {
                        toggleStates_[pos] = GUILayout.Toggle(toggleStates_[pos], GUIContent.none, style);
                    }

                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();
        }
예제 #12
0
        private Level GenerateLevelBlob(State state, int size, Array2D<Cell> designData, Array2D<bool> designFixed, out int designRow, out int designColumn)
        {
            // Inflate size for extra cells to be subtracted.
            int blobSize = size * (density + 100) / 100;
            // Create larger work array and corresponding fixed map.
            Array2D<Cell> array = new Array2D<Cell>(2 * size, 2 * size);
            array.SetAll(Cell.Outside);
            Array2D<bool> arrayFixed = new Array2D<bool>(array.Height, array.Width);

            // Adjust design data so that outside or undefined cells are empty.
            Array2D<Cell> designDataCopy = new Array2D<Cell>(designData);
            designDataCopy.Replace(Cell.Outside, Cell.Empty);
            designDataCopy.Replace(Cell.Undefined, Cell.Empty);

            // Copy design into middle of work array.
            designRow = size;
            designColumn = size;
            designDataCopy.CopyTo(array, designRow + 1, designColumn + 1, 1, 1, designData.Height - 2, designData.Width - 2);
            designFixed.CopyTo(arrayFixed, designRow + 1, designColumn + 1, 1, 1, designData.Height - 2, designData.Width - 2);

            // Set intial boundaries.
            int rowMin = array.Height;
            int colMin = array.Width;
            int rowMax = -1;
            int colMax = -1;
            int count = 0;
            foreach (Coordinate2D coord in array.Coordinates)
            {
                if (!Level.IsOutside(array[coord]))
                {
                    rowMin = Math.Min(rowMin, coord.Row);
                    colMin = Math.Min(colMin, coord.Column);
                    rowMax = Math.Max(rowMax, coord.Row);
                    colMax = Math.Max(colMax, coord.Column);
                    count++;
                }
            }

            while (count < blobSize)
            {
                // Choose an edge at random.
                int edge = state.Random.Next(4);
                int row = 0;
                int column = 0;
                int limit = 0;
                int hIncr = 0;
                int vIncr = 0;
                switch (edge)
                {
                    case 0:
                        row = rowMin - 1;
                        column = colMin + state.Random.Next(colMax - colMin + 1);
                        limit = rowMax - rowMin + 1;
                        vIncr = 1;
                        hIncr = 0;
                        break;
                    case 1:
                        row = rowMax + 1;
                        column = colMin + state.Random.Next(colMax - colMin + 1);
                        limit = rowMax - rowMin + 1;
                        vIncr = -1;
                        hIncr = 0;
                        break;
                    case 2:
                        row = rowMin + state.Random.Next(rowMax - rowMin + 1);
                        column = colMin - 1;
                        limit = colMax - colMin + 1;
                        vIncr = 0;
                        hIncr = 1;
                        break;
                    case 3:
                        row = rowMin + state.Random.Next(rowMax - rowMin + 1);
                        column = colMax + 1;
                        limit = colMax - colMin + 1;
                        vIncr = 0;
                        hIncr = -1;
                        break;
                }

                // Search along a line until we hit a empty or fixed cell.
                bool found = false;
                for (int i = 0; i < limit; i++)
                {
                    if (array[row + vIncr, column + hIncr] != Cell.Outside || arrayFixed[row + vIncr, column + hIncr])
                    {
                        if (!arrayFixed[row, column])
                        {
                            found = true;
                        }
                        break;
                    }
                    row += vIncr;
                    column += hIncr;
                }

                // If we didn't find anything, try again.
                if (!found)
                {
                    continue;
                }

                // Don't allow the level to grow outside the array.
                if (row < 1 || row >= array.Height - 1 || column < 1 || column >= array.Width - 1)
                {
                    continue;
                }

                // Add the new square and update the boundaries.
                array[row, column] = Cell.Empty;
                rowMin = Math.Min(rowMin, row);
                colMin = Math.Min(colMin, column);
                rowMax = Math.Max(rowMax, row);
                colMax = Math.Max(colMax, column);
                count++;
            }

            int attemptsLeft = 2 * (count - size);
            while (count > size && attemptsLeft > 0)
            {
                // Choose a new square at random.
                int row = rowMin + state.Random.Next(rowMax - rowMin + 1);
                int column = colMin + state.Random.Next(colMax - colMin + 1);
                Coordinate2D coord = new Coordinate2D(row, column);
                if (!array.IsValid(coord))
                {
                    continue;
                }

                // Avoid existing walls and outside areas.
                if (!Level.IsInside(array[coord]))
                {
                    continue;
                }

                // We might get into an infinite loop.
                attemptsLeft--;

                // Avoid fixed cells.
                if (arrayFixed[coord])
                {
                    continue;
                }

                // Avoid cells on the perimeter.
                bool isAdjacent = false;
                foreach (Coordinate2D neighbor in coord.EightNeighbors)
                {
                    if (array[neighbor] == Cell.Outside)
                    {
                        isAdjacent = true;
                        break;
                    }
                }
                if (isAdjacent)
                {
                    continue;
                }

                // Remove the cell.
                array[coord] = Cell.Wall;
                count--;

            }

            // Extract the constructed level.
            Array2D<Cell> subarray = array.GetSubarray(rowMin - 1, colMin - 1, rowMax - rowMin + 3, colMax - colMin + 3);
            subarray.Replace(Cell.Outside, Cell.Wall);
            Level level = new Level(subarray);

            // Adjust design coordinate.
            designRow -= rowMin - 1;
            designColumn -= colMin - 1;

            return level;
        }
예제 #13
0
 /// <summary>
 /// Copy constructor.
 /// </summary>
 /// <param name="that"></param>
 public DistributionArray2D(Array2D <T> that)
     : base(that)
 {
 }
예제 #14
0
        public static WriteableBitmap ToWriteableBitmap <T>(
            this Array2D <T> array,
            int dpiX,
            int dpiY)
            where T : struct
        {
            array.ThrowIfDisposed();

            var width      = array.Columns;
            var height     = array.Rows;
            var rgbReverse = false;
            var format     = new PixelFormat();
            var channels   = 0;

            switch (array.ImageType)
            {
            case ImageTypes.RgbPixel:
                // Dlib RgbPixel data
                // R,G,B,R,G,B,...
                // But .NET Bitmap data
                // B,G,R,B,G,R,...
                rgbReverse = true;
                format     = PixelFormats.Bgr24;
                channels   = 3;
                break;

            case ImageTypes.BgrPixel:
                // Dlib RgbPixel data
                // R,G,B,R,G,B,...
                // But .NET Bitmap data
                // B,G,R,B,G,R,...
                format   = PixelFormats.Bgr24;
                channels = 3;
                break;

            case ImageTypes.RgbAlphaPixel:
                // Dlib RgbAlphaPixel data
                // R,G,B,A,R,G,B,A,,...
                // But .NET Bitmap data
                // B,G,R,A,B,G,R,A,...
                rgbReverse = true;
                format     = PixelFormats.Bgra32;
                channels   = 4;
                break;

            case ImageTypes.UInt8:
            case ImageTypes.Int32:
            case ImageTypes.UInt16:
            case ImageTypes.Int16:
            case ImageTypes.HsiPixel:
            case ImageTypes.Float:
            case ImageTypes.Double:
            case ImageTypes.Matrix:
                throw new NotSupportedException();
            }

            var bitmap = new WriteableBitmap(width, height, dpiX, dpiY, format, null);

            ToManaged(array.ImageType, array.NativePtr, bitmap, rgbReverse, channels);
            return(bitmap);
        }
예제 #15
0
 public static void ThrowsExceptionIfDestIndexIsOutOfBounds <T>(
     Array2D <T> destination, Index2D destIndex)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => new List2D <T>(0, 0).CopyTo(
         destination, new Bounds2D(), destIndex));
예제 #16
0
 public static void ThrowsExceptionIfDestArrayCannotAccommodateAllElements <T>(
     List2D <T> source, Array2D <T> destination)
 => Assert.Throws <ArgumentException>(() => source.CopyTo(destination));
예제 #17
0
        private static void Main()
        {
            using (var img = new Array2D <byte>(400, 400))
                using (var ht = new DlibDotNet.HoughTransform(300))
                    using (var win = new ImageWindow())
                        using (var win2 = new ImageWindow())
                        {
                            var angle1 = 0d;
                            var angle2 = 0d;

                            while (true)
                            {
                                angle1 += Math.PI / 130;
                                angle2 += Math.PI / 400;

                                var rect = img.Rect;
                                var cent = rect.Center;
                                var arc  = Point.Rotate(cent, cent + new Point(90, 0), angle1 * 180 / Math.PI);
                                var tmp2 = arc + new Point(500, 0);
                                var tmp3 = arc - new Point(500, 0);
                                var l    = Point.Rotate(arc, tmp2, angle2 * 180 / Math.PI);
                                var r    = Point.Rotate(arc, tmp3, angle2 * 180 / Math.PI);

                                Dlib.AssignAllPpixels(img, 0);
                                Dlib.DrawLine(img, l, r, 255);

                                using (var himg = new Array2D <int>())
                                {
                                    var offset = new Point(50, 50);
                                    var hrect  = Dlib.GetRect(ht);
                                    var box    = Rectangle.Translate(hrect, offset);

                                    // Now let's compute the hough transform for a subwindow in the image.  In
                                    // particular, we run it on the 300x300 subwindow with an upper left corner at the
                                    // pixel point(50,50).  The output is stored in himg.
                                    ht.Operator(img, box, himg);

                                    // Now that we have the transformed image, the Hough image pixel with the largest
                                    // value should indicate where the line is.  So we find the coordinates of the
                                    // largest pixel:
                                    using (var mat = Dlib.Mat(himg))
                                    {
                                        var p = Dlib.MaxPoint(mat);

                                        // And then ask the ht object for the line segment in the original image that
                                        // corresponds to this point in Hough transform space.
                                        var line = ht.GetLine(p);

                                        // Finally, let's display all these things on the screen.  We copy the original
                                        // input image into a color image and then draw the detected line on top in red.
                                        using (var temp = new Array2D <RgbPixel>())
                                        {
                                            Dlib.AssignImage(img, temp);

                                            var p1 = line.Item1 + offset;
                                            var p2 = line.Item2 + offset;

                                            Dlib.DrawLine(temp, p1, p2, new RgbPixel
                                            {
                                                Red = 255
                                            });
                                            win.ClearOverlay();
                                            win.SetImage(temp);

                                            // Also show the subwindow we ran the Hough transform on as a green box.  You will
                                            // see that the detected line is exactly contained within this box and also
                                            // overlaps the original line.
                                            win.AddOverlay(box, new RgbPixel
                                            {
                                                Green = 255
                                            });

                                            using (var jet = Dlib.Jet(himg))
                                                win2.SetImage(jet);
                                        }
                                    }
                                }
                            }
                        }
        }
예제 #18
0
        //--------------------------------------------------------------------------------------------------------
        /// <summary>
        /// OpenCVとDlib68を併用した推定。Dlib68より高速だが、顔の検出率は低め。
        /// </summary>
        /// <param name="threadNo">走らせるスレッド番号</param>
        /// <param name="est_pos">推定した位置</param>
        /// <param name="est_rot">推定した回転</param>
        /// <returns>推定できたか</returns>
        private bool Mixed(int threadNo, out Vector3 est_pos, out Vector3 est_rot)
        {
            Mat image_r = new Mat();
            Mat image   = new Mat();

            try
            {
                lock (lock_capture)
                {
                    image_r = caputure.Read();
                    if (image_r.Data == null)
                    {
                        throw new NullReferenceException("capture is null");
                    }

                    if (ptr.Contains(image_r.Data))
                    {
                        throw new InvalidOperationException("taken same data");
                    }
                    else
                    {
                        ptr[threadNo] = image_r.Data;
                    }
                }

                if (resolution == 1)
                {
                    image = image_r.Clone();
                }
                else
                {
                    Cv2.Resize(image_r, image, new Size(image_r.Cols / resolution, image_r.Rows / resolution));
                }

                GC.KeepAlive(image_r);

                var faces = cascade.DetectMultiScale(image);

                if (!faces.Any())
                {
                    throw new InvalidOperationException("this contains no elements");
                }

                Array2D <RgbPixel> array2D = new Array2D <RgbPixel>();

                lock (lock_imagebytes[threadNo])
                {
                    Marshal.Copy(image.Data, bytes[threadNo], 0, bytes[threadNo].Length);
                    array2D = Dlib.LoadImageData <RgbPixel>(bytes[threadNo], (uint)image.Height, (uint)image.Width, (uint)(image.Width * image.ElemSize()));
                }

                var rectangles = new Rectangle(faces.First().Left, faces.First().Top, faces.First().Right, faces.First().Bottom);

                DlibDotNet.Point[] points = new DlibDotNet.Point[68];

                using (FullObjectDetection shapes = shape.Detect(array2D, rectangles))
                {
                    for (uint i = 0; i < 68; i++)
                    {
                        points[i] = shapes.GetPart(i);
                    }
                    lock (lock_landmarks)
                    {
                        landmark_detection = points;
                    }
                }

                array2D.Dispose();

                Point2f[] image_points = new Point2f[6];
                image_points[0] = new Point2f(points[30].X, points[30].Y);
                image_points[1] = new Point2f(points[8].X, points[8].Y);
                image_points[2] = new Point2f(points[45].X, points[45].Y);
                image_points[3] = new Point2f(points[36].X, points[36].Y);
                image_points[4] = new Point2f(points[54].X, points[54].Y);
                image_points[5] = new Point2f(points[48].X, points[48].Y);
                var image_points_mat = new Mat(image_points.Length, 1, MatType.CV_32FC2, image_points);
                eye_point_R[threadNo][0] = points[42]; eye_point_L[threadNo][1] = points[36];
                eye_point_R[threadNo][2] = points[43]; eye_point_L[threadNo][2] = points[38];
                eye_point_R[threadNo][3] = points[47]; eye_point_L[threadNo][3] = points[40];
                eye_point_R[threadNo][4] = points[44]; eye_point_L[threadNo][4] = points[37];
                eye_point_R[threadNo][5] = points[46]; eye_point_L[threadNo][5] = points[41];

                Mat rvec_mat       = new Mat();
                Mat tvec_mat       = new Mat();
                Mat projMatrix_mat = new Mat();
                Cv2.SolvePnP(model_points_mat, image_points_mat, camera_matrix_mat, dist_coeffs_mat, rvec_mat, tvec_mat);
                Marshal.Copy(tvec_mat.Data, pos_double[threadNo], 0, 3);
                Cv2.Rodrigues(rvec_mat, projMatrix_mat);
                Marshal.Copy(projMatrix_mat.Data, proj[threadNo], 0, 9);

                est_pos.x = -(float)pos_double[threadNo][0];
                est_pos.y = (float)pos_double[threadNo][1];
                est_pos.z = (float)pos_double[threadNo][2];

                est_rot = RotMatToQuatanion(proj[threadNo]).eulerAngles;

                if (blink_tracking)
                {
                    BlinkTracker(threadNo, eye_point_L[threadNo], eye_point_R[threadNo], est_rot);
                }
                if (eye_tracking)
                {
                    EyeTracker(threadNo, image, points.Skip(42).Take(6), points.Skip(36).Take(6));
                }

                image_points_mat.Dispose();
                rvec_mat.Dispose();
                tvec_mat.Dispose();
                projMatrix_mat.Dispose();
                GC.KeepAlive(image);
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
                est_pos = pos; est_rot = rot;
                if (image.IsEnabledDispose)
                {
                    image.Dispose();
                }
                return(false);
            }
            lock (lock_imagebytes[threadNo])
            {
                if (image.IsEnabledDispose)
                {
                    image.Dispose();
                }
            }

            return(true);
        }
예제 #19
0
 public static void Index2DIntIPredicateThrowsExceptionIfStartIndexIsOutOfBounds <T>
     (Array2D <T> array, Index2D startIndex)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => array.FindLastIndex(startIndex, 0, new AlwaysTruePredicate <T>()));
예제 #20
0
 public static ItemRequestResult <Index2D> TestFindLastIndex <T>(
     Array2D <T> array, Index2D startIndex, Bounds2D sector, Predicate <T> match)
 => array.FindLastIndex(startIndex, sector, match);
예제 #21
0
 public static void Index2DBounds2DThrowsExceptionIfSectorIsOutOfBounds <T>(
     Array2D <T> array, Index2D startIndex, Bounds2D sector)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => array.FindLastIndex(startIndex, sector, o => true));
예제 #22
0
 public static ItemRequestResult <Index2D> Test <T>(
     Array2D <T> array, Index2D startIndex, int count, Predicate <T> match)
 => array.FindLastIndex(startIndex, count, match);
예제 #23
0
 public static void Index2DIntThrowsExceptionIfCountExceedsArray2DCount <T>(
     Array2D <T> array, Index2D startIndex, int count)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => array.FindLastIndex(startIndex, count, o => true));
예제 #24
0
 public static void Index2DIntThrowsExceptionIfStartIndexIsOutOfBounds <T>(
     Array2D <T> array, Index2D startIndex)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => array.FindLastIndex(startIndex, 0, o => true));
예제 #25
0
 public static ItemRequestResult <Index2D> Test <T>(
     Array2D <T> array, Predicate <T> match)
 => array.FindLastIndex(match);
예제 #26
0
 public static void Index2DIntIPredicateThrowsExceptionIfCountExceedsArray2DCount <T>
     (Array2D <T> array, Index2D startIndex, int count)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => array.FindLastIndex(
         startIndex, count, new AlwaysTruePredicate <T>()));
예제 #27
0
 private void Initialize()
 {
     this.data = level.Data;
     this.boxCoordinates = level.BoxCoordinates;
     this.boxes = level.Boxes;
     this.cancelInfo = new CancelInfo();
 }
예제 #28
0
 public static ItemRequestResult <Index2D> Test <T, TPredicate>(
     Array2D <T> array, Index2D startIndex, int count, TPredicate match)
     where TPredicate : struct, IPredicate <T>
 => array.FindLastIndex(startIndex, count, match);
예제 #29
0
        public Level(Level other)
            : base(new Array2D<Cell>(other.Data))
        {
            // Copy state information.
            name = other.name;
            sokobanAssessed = other.sokobanAssessed;
            boxesAssessed = other.boxesAssessed;
            outsideAssessed = other.outsideAssessed;
            sokobanRow = other.sokobanRow;
            sokobanColumn = other.sokobanColumn;
            sokobans = other.sokobans;
            boxes = other.boxes;
            targets = other.targets;
            insideSquares = other.insideSquares;
            isClosed = other.isClosed;
            unfinishedBoxes = other.unfinishedBoxes;
            markAccessible = other.markAccessible;
            validate = other.validate;
            boxMap = new Array2D<int>(other.boxMap);
            boxCoordinates = (Coordinate2D[])other.BoxCoordinates.Clone();
            insideCoordinates = other.insideCoordinates;

            Initialize();
        }
 /// <summary>
 /// Adjust the rectangle to make sure it is inside the range of the image
 /// </summary>
 /// <param name="rect">rectangle to be adjusted</param>
 /// <param name="img">image for reference</param>
 /// <returns></returns>
 public static DlibDotNet.Rectangle RectangleAdjust(DlibDotNet.Rectangle rect, Array2D <RgbPixel> img)
 {
     DlibDotNet.Rectangle fitRect = new DlibDotNet.Rectangle();
     fitRect.Right  = rect.Right < img.Rect.Right ? rect.Right : img.Rect.Right;
     fitRect.Left   = rect.Left > img.Rect.Left ? rect.Left : img.Rect.Left;
     fitRect.Top    = rect.Top > img.Rect.Top ? rect.Top : img.Rect.Top;
     fitRect.Bottom = rect.Bottom < img.Rect.Bottom ? rect.Bottom : img.Rect.Bottom;
     return(fitRect);
 }
예제 #31
0
 public static void ThrowsExceptionIfSectorSizeIsOutOfBounds <T>(
     List2D <T> source, Array2D <T> destination, Bounds2D sectorSize)
 => Assert.Throws <ArgumentOutOfRangeException>(
     () => source.CopyTo(destination, sectorSize));
예제 #32
0
    public override void Generate(int rooms)
    {
        int posY = (int)Random.Range(0.0f, rooms / 2);

        position             = new Vector2(0, posY);
        /* Array2D */ patern = new Array2D(rooms, rooms);
        patern[0, posY]      = 2;

        int roomsBuild = 0;
        int safeExit   = 0;

        while (roomsBuild < rooms && safeExit < rooms * 10)
        {
            bool  build = false;
            float value = Random.Range(0.0f, 1.0f);

            if (value < generateOnLeft)
            {
                if (position.x != 0 && patern[(int)position.x - 1, (int)position.y] == 0)
                {
                    position.x--;
                    build = true;
                    reduceLeftProba();
                }
            }
            else if (value < generateOnTop)
            {
                if (position.y != 0 && patern[(int)position.x, (int)position.y - 1] == 0)
                {
                    position.y--;
                    build = true;
                    reduceRightProba();
                }
            }
            else if (value < generateOnRight)
            {
                if (position.y != rooms - 1 && patern[(int)position.x + 1, (int)position.y] == 0)
                {
                    position.x++;
                    build = true;
                    reduceTopProba();
                }
            }
            else if (value < generateOnBottom)
            {
                if (position.y != rooms - 1 && patern[(int)position.x, (int)position.y + 1] == 0)
                {
                    position.y++;
                    build = true;
                    reduceBottomProba();
                }
            }

            if (build)
            {
                roomsBuild++;
                patern[(int)position.x, (int)position.y] = 1;
            }
            safeExit++;
        }
    }
예제 #33
0
 public static void Test <T>(
     List2D <T> src, Array2D <T> dest, Array2D <T> expected)
 {
     src.CopyTo(dest);
     CollectionAssert.AreEqual(expected, dest);
 }
예제 #34
0
        private Level GenerateLevelBuckshot(State state, int size, Array2D<Cell> designData, Array2D<bool> designFixed, out int designRow, out int designColumn)
        {
            // Create larger work array and corresponding fixed map.
            Array2D<Cell> array = new Array2D<Cell>(2 * size + designData.Height, 2 * size + designData.Width);
            array.SetAll(Cell.Wall);
            Array2D<bool> arrayFixed = new Array2D<bool>(array.Height, array.Width);

            // Adjust design data so that undefined cells are walls.
            Array2D<Cell> designDataCopy = new Array2D<Cell>(designData);
            designDataCopy.Replace(Cell.Undefined, Cell.Wall);

            // Copy design into middle of work array.
            designRow = size;
            designColumn = size;
            designDataCopy.CopyTo(array, designRow, designColumn, 0, 0, designData.Height, designData.Width);
            designFixed.CopyTo(arrayFixed, designRow, designColumn, 0, 0, designData.Height, designData.Width);

            // Set intial boundaries.
            int rowMin = array.Height;
            int colMin = array.Width;
            int rowMax = -1;
            int colMax = -1;
            int count = 0;
            foreach (Coordinate2D coord in array.Coordinates)
            {
                if (!Level.IsWall(array[coord]))
                {
                    rowMin = Math.Min(rowMin, coord.Row);
                    colMin = Math.Min(colMin, coord.Column);
                    rowMax = Math.Max(rowMax, coord.Row);
                    colMax = Math.Max(colMax, coord.Column);
                    count++;
                }
            }

            while (count < size)
            {
                // Choose a new square at random.
                int row = rowMin - growth + state.Random.Next(rowMax - rowMin + 1 + 2 * growth);
                int column = colMin - growth + state.Random.Next(colMax - colMin + 1 + 2 * growth);
                Coordinate2D coord = new Coordinate2D(row, column);
                if (!array.IsValid(coord))
                {
                    continue;
                }

                // Avoid fixed cells.
                if (arrayFixed[coord])
                {
                    continue;
                }

                // Avoid existing squares.
                if (!Level.IsWall(array[coord]))
                {
                    continue;
                }

                // Ensure the new square is adjacent to an existing square.
                bool isAdjacent = false;
                foreach (Coordinate2D neighbor in coord.FourNeighbors)
                {
                    if (!Level.IsWall(array[neighbor]))
                    {
                        isAdjacent = true;
                        break;
                    }
                }
                if (!isAdjacent)
                {
                    continue;
                }

                // Add the new square and update the boundaries.
                array[coord] = Cell.Empty;
                rowMin = Math.Min(rowMin, row);
                colMin = Math.Min(colMin, column);
                rowMax = Math.Max(rowMax, row);
                colMax = Math.Max(colMax, column);
                count++;
            }

            // Extract the constructed level.
            Array2D<Cell> subarray = array.GetSubarray(rowMin - 1, colMin - 1, rowMax - rowMin + 3, colMax - colMin + 3);
            Level level = new Level(subarray);

            // Adjust design coordinate.
            designRow -= rowMin - 1;
            designColumn -= colMin - 1;

            return level;
        }
예제 #35
0
 // Use this for initialization
 void Start()
 {
     testArray = new Array2D <Coordinate>(4, 4);
     Refill();
 }
예제 #36
0
        public bool Generate()
        {
            Initialize();

            designInfo = new DesignInfo[designs.Count];

            designCount = 0;
            foreach (Level design in designs)
            {
                // Extract design data.
                Array2D<Cell> designData = new Array2D<Cell>(design.Data);
                if (useEntireLevel)
                {
                    designData.Replace(Cell.Outside, Cell.Wall);
                }

                // Create a map of all squares that cannot be altered, initialized to false.
                Array2D<bool> designFixed = new Array2D<bool>(designData.Height, designData.Width);
                Coordinate2D sokobanCoord = Coordinate2D.Undefined;
                int designBoxes = 0;
                foreach (Coordinate2D coord in designData.NonPerimeterCoordinates)
                {
                    if (clearDesign)
                    {
                        if (designData[coord] != Cell.Wall)
                        {
                            designData[coord] = Cell.Empty;
                        }
                    }
                    if (designData[coord] != Cell.Undefined)
                    {
                        // Record squares that should not be changed.
                        designFixed[coord] = true;
                    }
                    if (Level.IsSokoban(designData[coord]))
                    {
                        // Remove sokoban if present but record its coordinate.
                        designData[coord] &= ~Cell.Sokoban;
                        sokobanCoord = coord;
                    }
                    if (Level.IsBox(designData[coord]))
                    {
                        // Count boxes included in design.
                        designBoxes++;
                    }
                }

                // Store in design array.
                DesignInfo info = new DesignInfo();
                info.Data = designData;
                info.Fixed = designFixed;
                info.SokobanCoordinate = sokobanCoord;
                info.Boxes = designBoxes;
                designInfo[designCount] = info;
                designCount++;
            }

            // Now generate levels.
            if (threads == 1)
            {
                return GenerateLevels();
            }
            return MultiThreadedGenerateLevels();
        }
 /// <inheritdoc />
 protected override Index2D GetDimensions(Array2D <T> value) => value.Dimensions;
예제 #38
0
        public Terrain(Vector3 posCenter, Vector3 size, int cellsX, int cellsZ, GraphicsDevice g, Texture2D tex) : base()
        {
            numVertsX = cellsX + 1;
            numVertsZ = cellsZ + 1;
            numVerts  = numVertsX * numVertsZ;
            numTriX   = cellsX * 2;
            numTriZ   = cellsZ;
            numTris   = numTriX * numTriZ;
            verts     = new VertexPositionNormalTexture[numVerts];
            int numIndices = numTris * 3;

            indices = new int[numIndices];
            float cellSizeX = (float)size.X / cellsX;
            float cellSizeZ = (float)size.Z / cellsZ;

            texture = tex;

            Random r             = new Random();
            Random r2            = new Random(DateTime.Now.Millisecond);
            double targetHeight  = 0;
            double currentHeight = 0;
            // Fill in the vertices
            int count = 0;

            // distribute height nodes across the map.
            // for each vert, calculate the height by summing (node height / distance)
            int numHeightNodes = 10;

            heightNodes = new Vector3[numHeightNodes];
            for (int i = 0; i < numHeightNodes; i++)
            {
                heightNodes[i] = new Vector3((float)((-size.X / 2) + (r.NextDouble() * size.X)),
                                             (float)(r.NextDouble() * 0),
                                             (float)((-size.Z / 2) + (r.NextDouble() * size.Z)));
            }

            bool  stretchTexture   = false;
            float textureTileCount = 10000;

            float worldZPosition = -(size.Z / 2);

            for (int z = 0; z < numVertsZ; z++)
            {
                float worldXPosition = -(size.X / 2);
                for (int x = 0; x < numVertsX; x++)
                {
                    if (count % numVertsX == 0)
                    {
                        targetHeight = r2.NextDouble();
                    }

                    //currentHeight += (targetHeight - currentHeight) * .009f;

                    float height = GetNodeBasedHeight(worldXPosition, worldZPosition);
                    height = 0;
                    verts[count].Position = new Vector3(worldXPosition, height, worldZPosition);
                    verts[count].Normal   = Vector3.Zero;

                    if (stretchTexture)
                    {
                        verts[count].TextureCoordinate.X = (float)x / (numVertsX - 1);
                        verts[count].TextureCoordinate.Y = (float)z / (numVertsZ - 1);
                    }
                    else
                    {
                        verts[count].TextureCoordinate.X = ((float)x / (numVertsX - 1)) * textureTileCount;
                        verts[count].TextureCoordinate.Y = ((float)z / (numVertsZ - 1)) * textureTileCount;
                    }

                    count++;

                    // Advance in x
                    worldXPosition += cellSizeX;
                }

                currentHeight = 0;
                // Advance in z
                worldZPosition += cellSizeZ;
            }

            int index       = 0;
            int startVertex = 0;

            for (int cellZ = 0; cellZ < cellsZ; cellZ++)
            {
                for (int cellX = 0; cellX < cellsX; cellX++)
                {
                    indices[index]     = startVertex + 0;
                    indices[index + 1] = startVertex + 1;
                    indices[index + 2] = startVertex + numVertsX;
                    SetNormalOfTriangleAtIndices(indices[index], indices[index + 1], indices[index + 2]);
                    meshIndices.Add(new TriangleVertexIndices(index, index + 1, index + 2));
                    meshVertices.Add(verts[indices[index]].Position);
                    meshVertices.Add(verts[indices[index + 1]].Position);
                    meshVertices.Add(verts[indices[index + 2]].Position);
                    index += 3;

                    indices[index]     = startVertex + 1;
                    indices[index + 1] = startVertex + numVertsX + 1;
                    indices[index + 2] = startVertex + numVertsX;
                    SetNormalOfTriangleAtIndices(indices[index], indices[index + 1], indices[index + 2]);
                    meshIndices.Add(new TriangleVertexIndices(index, index + 1, index + 2));
                    meshVertices.Add(verts[indices[index]].Position);
                    meshVertices.Add(verts[indices[index + 1]].Position);
                    meshVertices.Add(verts[indices[index + 2]].Position);
                    index += 3;

                    startVertex++;
                }
                startVertex++;
            }

            try
            {
                Effect = new BasicEffect(g);
                mesh   = new TriangleMesh();
                //mesh.CreateMesh(meshVertices, meshIndices, 2, cellSizeX);
            }
            catch (Exception E)
            {
                System.Diagnostics.Debug.WriteLine(E.StackTrace);
            }

            this.Body          = new Body();
            Skin               = new CollisionSkin(Body);
            Body.CollisionSkin = Skin;
            Body.ExternalData  = this;
            float heightf = 0;

            try
            {
                Array2D field = new Array2D(numVertsX, numVertsZ);

                int i = 0;
                for (int c = 0; c < verts.Length; c++)
                {
                    int x = c / numVertsX;
                    int z = c % numVertsX;

                    if (i >= verts.Length)
                    {
                        i = (i % verts.Length) + 1;
                    }
                    heightf = verts[i].Position.Y + posCenter.Y; // works
                    //heightf = verts[i].Position.Y;
                    i += numVertsX;

                    field.SetAt(x, z, heightf);
                }

                // Body.MoveTo(Position, Matrix.Identity);

                Heightmap hm = new Heightmap(field,
                                             (-size.X / 2) / (cellsX + 0) + cellSizeX / 2,
                                             (-size.Z / 2) / (cellsZ + 0) + cellSizeZ / 2,
                                             size.X / (cellsX + 0),
                                             size.Z / (cellsZ + 0));
                Skin.AddPrimitive(hm, new MaterialProperties(0.7f, 0.7f, 0.6f));
                //Skin.AddPrimitive(GetMesh(), new MaterialProperties(0.7f, 0.7f, 0.6f));
                //VertexPositionColor[] wireFrame = Skin.GetLocalSkinWireframe(); // 1200 across before Z changes to from -7.5/-7.35 to -7.35/-7.2

                PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(Skin);
                CommonInit(posCenter, new Vector3(0, 0, 0), null, false, 0);
            }
            catch (Exception E)
            {
                System.Diagnostics.Debug.WriteLine(E.StackTrace);
            }
        }
예제 #39
0
        private void UnsafeGenerateOneLevel(State state)
        {
            // Randomly select a supplied design.
            state.CurrentDesign = state.Random.Next(designCount);
            Array2D<Cell> designData = designInfo[state.CurrentDesign].Data;
            Array2D<bool> designFixed = designInfo[state.CurrentDesign].Fixed;

            // Choose a size at random between the minimum and maximum limits.
            int size = minSize + state.Random.Next(maxSize - minSize + 1);
            state.CurrentSize = size;

            int designRow;
            int designColumn;
            Level level = null;
            if (useEntireLevel)
            {
                designRow = 0;
                designColumn = 0;
                level = new Level(new Array2D<Cell>(designData));
            }
            else
            {
                level = GenerateLevel(state, size, designData, designFixed, out designRow, out designColumn);
            }

            // Make sure will have something to solve.
            if (designInfo[state.CurrentDesign].Boxes == 0 && boxes == 0)
            {
                state.Log.DebugPrint("level generated with no boxes");
                return;
            }

            // Add islands not included in design.
            for (int i = 0; i < islands; i++)
            {
                AddIsland(state, level);
            }

            // Add boxes not included in design.
            if (designInfo[state.CurrentDesign].Boxes < boxes)
            {
                int boxesToAdd = boxes - designInfo[state.CurrentDesign].Boxes;
                int displacedBoxes = boxesToAdd >= displaced ? displaced : boxesToAdd;
                int inplaceBoxes = boxesToAdd - displacedBoxes;
                for (int i = 0; i < displacedBoxes; i++)
                {
                    AddDisplacedBox(state, level);
                }
                for (int i = 0; i < inplaceBoxes; i++)
                {
                    AddInplaceBox(state, level);
                }
            }

            if (verbose >= 2)
            {
                state.Log.DebugPrint("design = {0}, size = {1}, algorithm = {2}", state.CurrentDesign, state.CurrentSize, state.CurrentAlgorithm);
                state.Log.DebugPrint(level.AsText);
            }

            // Create a map of squares that have already been tried
            // as the starting sokoban coordinate, initialized to false.
            Array2D<bool> tried = new Array2D<bool>(level.Height, level.Width);
            Coordinate2D sokobanCoord = designInfo[state.CurrentDesign].SokobanCoordinate;

            if (!sokobanCoord.IsUndefined)
            {
                // Only try specified sokoban coordinate.
                tried.SetAll(true);
                tried[sokobanCoord.Row + designRow, sokobanCoord.Column + designColumn] = false;
            }

            // For all accessible squares.
            PathFinder finder = PathFinder.CreateInstance(level);
            while (true)
            {
                // Find an untried starting square.
                bool foundSquare = false;
                foreach (Coordinate2D coord in level.InsideCoordinates)
                {
                    if (level.IsEmpty(coord) && !tried[coord])
                    {
                        sokobanCoord = coord;
                        foundSquare = true;
                        break;
                    }
                }
                if (!foundSquare)
                {
                    break;
                }

                // Put sokoban on untried empty square.
                level.AddSokoban(sokobanCoord);

                // Find all squares accessible from this one.
                finder.Find();

                // Mark all accessible squares as tried.
                foreach (Coordinate2D coord in finder.AccessibleCoordinates)
                {
                    tried[coord] = true;
                }

                MoveList moveList = FastSolve(state, level);
                if (moveList != null)
                {
                    int pushes = LevelUtils.SolutionPushes(moveList);
                    if (verbose >= 1)
                    {
                        state.Log.DebugPrint("raw: moves = {0}, pushes = {1}", moveList.Count, pushes);
                    }
                    if (pushes > pushLimit)
                    {
                        // First clean up the level which might have a large number
                        // of excess squares that would stress the final solver.
                        Level cleanLevel = LevelUtils.CleanLevel(level, moveList);

                        // Now get a clean solution using move optimization.
                        MoveList cleanMoveList = FinalSolve(state, cleanLevel);

                        // Although this does have a solution, the solver
                        // could fail for other reasons (out of memory, etc).
                        if (cleanMoveList != null)
                        {
                            // Finally check whether there are any squares we can remove.
                            AddSmallestLevel(state, cleanLevel, cleanMoveList);
                        }
                    }
                }
                else
                {
                    if (verbose >= 2)
                    {
                        state.Log.DebugPrint("no solution");
                    }
                }

                level.RemoveSokoban();
            }
        }
예제 #40
0
 private static Deadlock GetDeadlock(Level level)
 {
     // Decode the map.
     Array2D<bool> map = null;
     if (level.Targets != 0)
     {
         map = new Array2D<bool>(level.Height, level.Width);
         foreach (Coordinate2D coord in level.TargetCoordinates)
         {
             map[coord] = true;
         }
     }
     return new Deadlock(map, level.BoxCoordinates);
 }
예제 #41
0
        private Level GenerateLevel(State state, int size, Array2D<Cell> designData, Array2D<bool> designFixed, out int designRow, out int designColumn)
        {
            Level level = null;
            designRow = 0;
            designColumn = 0;

            if (size == 0)
            {
                designRow = -1;
                designColumn = -1;
                level = new Level(designData.GetSubarray(1, 1, designData.Height - 2, designData.Width - 2));
                if (level.IsClosed)
                {
                    state.Log.DebugPrint("design with no additional squares is not closed");
                }
            }

            // Choose algorithm at random.
            state.CurrentAlgorithm = algorithms[state.Random.Next(algorithms.Length)];

            switch (state.CurrentAlgorithm)
            {
                case AlgorithmType.Buckshot:
                    level = GenerateLevelBuckshot(state, size, designData, designFixed, out designRow, out designColumn);
                    break;

                case AlgorithmType.Blob:
                    level = GenerateLevelBlob(state, size, designData, designFixed, out designRow, out designColumn);
                    break;
            }

            return level;
        }
예제 #42
0
 private static Array2D<bool> GetSetMap(IEnumerable<Coordinate2D> set)
 {
     Coordinate2D maxCoord = new Coordinate2D(0, 0);
     foreach (Coordinate2D coord in set)
     {
         maxCoord.Row = Math.Max(maxCoord.Row, coord.Row);
         maxCoord.Column = Math.Max(maxCoord.Column, coord.Column);
     }
     Array2D<bool> setMap = new Array2D<bool>(maxCoord.Row + 2, maxCoord.Column + 2);
     foreach (Coordinate2D coord in set)
     {
         setMap[coord] = true;
     }
     return setMap;
 }
예제 #43
0
        private void CalculatePullMap()
        {
            // Pre-calculate a map of possible directions in which a box
            // at a given coordinate can be pulled.

            pullMap = new Array2D<Direction[]>(level.Height, level.Width);
            foreach (Coordinate2D coord in level.InsideCoordinates)
            {
                List<Direction> directions = new List<Direction>();
                foreach (Direction direction in Direction.Directions)
                {
                    Coordinate2D sokobanCoood = coord + 2 * direction;
                    Coordinate2D newBoxCoord = coord + direction;

                    if (!level.IsFloor(sokobanCoood))
                    {
                        // The sokoban can never reach to pull this box.
                        continue;
                    }

                    if (!level.IsFloor(newBoxCoord))
                    {
                        // The box cannot be pulled in this direction.
                        continue;
                    }

                    directions.Add(direction);
                }
                pullMap[coord] = directions.ToArray();
            }
        }
예제 #44
0
 public void Mirror()
 {
     Array2D<Cell> newData = new Array2D<Cell>(levelHeight, levelWidth);
     for (int row = 0; row < levelHeight; row++)
     {
         for (int column = 0; column < levelWidth; column++)
         {
             newData[row, column] = Data[row, levelWidth - 1 - column];
         }
     }
     Data = newData;
 }
예제 #45
0
        private void CalculateSimpleDeadlockMap()
        {
            // Create a simple deadlock map with all inside squares initialized to true.
            simpleDeadlockMap = new Array2D<bool>(level.Height, level.Width);
            foreach (Coordinate2D coord in level.InsideCoordinates)
            {
                simpleDeadlockMap[coord] = true;
            }

            // For each target visit as many squares as possible using pulls only.
            foreach (Coordinate2D coord in level.TargetCoordinates)
            {
                VisitAllPulls(coord);
            }
        }
예제 #46
0
 public void Rotate()
 {
     Array2D<Cell> newData = new Array2D<Cell>(levelWidth, levelHeight);
     for (int row = 0; row < levelWidth; row++)
     {
         for (int column = 0; column < levelHeight; column++)
         {
             newData[row, column] = Data[levelHeight - 1 - column, row];
         }
     }
     Data = newData;
 }
 /// <inheritdoc />
 protected override Index2D GetLowerBounds(Array2D <T> value) => value.LowerBounds;
예제 #48
0
        //--------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Dlib5を利用した顔検出                    Face detection using Dlib5
        /// </summary>
        /// <param name="threadNo">スレッド番号      Thread number</param>
        /// <param name="est_pos">推定された位置     Estimated position</param>
        /// <param name="est_rot">推定された回転     Estimated quotation</param>
        /// <returns>推定できたか                    Whether it could be estimated</returns>
        private bool Dlib5(int threadNo, out Vector3 est_pos, out Vector3 est_rot)
        {
            est_rot = rot;
            Mat image_r = new Mat();
            Array2D <RgbPixel> array2D = new Array2D <RgbPixel>();
            Mat image = new Mat();

            try
            {
                lock (lock_capture)
                {
                    image_r = caputure.Read();
                    if (image_r.Data == null)
                    {
                        throw new NullReferenceException("capture is null");
                    }

                    if (ptr.Contains(image_r.Data))
                    {
                        throw new InvalidOperationException("taken same data");
                    }
                    else
                    {
                        ptr[threadNo] = image_r.Data;
                    }
                }
                if (resolution == 1)
                {
                    image = image_r.Clone();
                }
                else
                {
                    Cv2.Resize(image_r, image, new Size(image_r.Cols / resolution, image_r.Rows / resolution));
                }

                GC.KeepAlive(image_r);

                lock (lock_imagebytes[threadNo])
                {
                    Marshal.Copy(image.Data, bytes[threadNo], 0, bytes[threadNo].Length);
                    array2D = Dlib.LoadImageData <RgbPixel>(bytes[threadNo], (uint)image.Height, (uint)image.Width, (uint)(image.Width * image.ElemSize()));
                }

                Rectangle rectangles = default;
                if (un_safe)
                {
                    rectangles = detector[0].Operator(array2D).FirstOrDefault();
                }
                else
                {
                    rectangles = detector[threadNo].Operator(array2D).FirstOrDefault();
                }

                DlibDotNet.Point[] points = new DlibDotNet.Point[5];
                if (rectangles == default)
                {
                    throw new InvalidOperationException("this contains no elements.");
                }

                using (FullObjectDetection shapes = shape.Detect(array2D, rectangles))
                {
                    for (uint i = 0; i < 5; i++)
                    {
                        points[i] = shapes.GetPart(i);
                    }
                }

                est_pos.x = -(image.Width / 2 - points[4].X) / (float)image.Width;
                est_pos.y = (image.Height / 2 - points[4].Y) / (float)image.Height;
                est_pos.z = (points[0].X - points[2].X) / (float)image.Width + (points[0].Y - points[2].Y) / (float)image.Height - z_offset;

                try
                {
                    est_rot.z = Mathf.Rad2Deg * Mathf.Atan2(points[0].Y - points[2].Y, points[0].X - points[2].X);
                }
                catch (DivideByZeroException)
                {
                    est_rot.z = points[0].Y - points[2].Y < 0 ? -90 : 90;
                }
                if (debug_face_image)
                {
                    DetectDebug(threadNo, image, points: points);
                }
                GC.KeepAlive(image);
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
                est_pos = pos;
                if (array2D.IsEnableDispose)
                {
                    array2D.Dispose();
                }
                if (image.IsEnabledDispose)
                {
                    image.Dispose();
                }

                return(false);
            }

            if (array2D.IsEnableDispose)
            {
                array2D.Dispose();
            }
            lock (lock_imagebytes[threadNo])
            {
                if (image.IsEnabledDispose)
                {
                    image.Dispose();
                }
            }
            return(true);
        }
예제 #49
0
 private static Level GetDeadlockAsLevel(Level level, Deadlock deadlock)
 {
     Array2D<Cell> newData = new Array2D<Cell>(level.Data);
     foreach (Coordinate2D coord in level.InsideCoordinates)
     {
         newData[coord] &= ~(Cell.Sokoban | Cell.Box | Cell.Target);
     }
     foreach (Coordinate2D coord in deadlock.Coordinates)
     {
         newData[coord] |= Cell.Box;
     }
     if (deadlock.SokobanMap != null)
     {
         foreach (Coordinate2D coord in level.InsideCoordinates)
         {
             if (deadlock.SokobanMap[coord])
             {
                 newData[coord] |= Cell.Target;
             }
         }
     }
     return new Level(newData);
 }
 public PerEntityVoxelWorldRenderer(Model.World world, Point2 windowSize)
 {
     this.world = world;
     entities   = new Array2D <Entity>(windowSize);
     entities.ForEach((e, p) => entities[p] = new Entity());
 }
예제 #51
0
        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public LightsOut2(IHTMLElement DataElement)
        {

            // based on http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx

            // what happens in beta2 when the anonymous types are immutable? :)


            var usersettings = new  { x = 5, y = 5, tile = new  { w = 64, h = 64, cold = 0.8 } };

    
            var a = new Array2D<IHTMLDiv>(usersettings.x, usersettings.y);
            var m = a.ToBooleanArray();



            var r = new System.Random();

            m.ForEach(
                (x, y) =>
                {
                    m[x, y] = r.NextDouble() > 0.5;
                }
            );


            var canvas = new IHTMLDiv();

            canvas.className = "canvas";

            var canvas_size = new __Type1 { x = ((a.XLength + 1) * usersettings.tile.w), y = ((a.YLength + 1) * usersettings.tile.h) };

            canvas.style.position = IStyle.PositionEnum.relative;
            canvas.style.border = "2px solid black";
            canvas.style.width = canvas_size.x + "px";
            canvas.style.height = canvas_size.y + "px";

            var canvas_bg = new IHTMLDiv();
            //var canvas_bg_tween = new TweenDataDouble();

            //canvas_bg_tween.Value = 1;
            //canvas_bg_tween.ValueChanged += delegate { canvas_bg.style.Opacity = canvas_bg_tween.Value; };

            new HTML.Images.FromAssets.background().ToBackground(canvas_bg.style);
            //canvas_bg.style.backgroundImage = Assets.Default.Background.StyleSheetURL;
            canvas_bg.style.SetLocation(0, 0, canvas_size.x * 2, canvas_size.y);

            canvas.appendChild(canvas_bg);


            IStyleSheet.Default.AddRule(".info").style
                .Aggregate(s =>
                               {
                                   s.backgroundColor = Color.Black;
                                   s.color = Color.White;
                                   s.padding = "2em";
                                   s.fontFamily = IStyle.FontFamilyEnum.Tahoma;
                                   s.Float = IStyle.FloatEnum.right;
                               })
                ;

            IStyleSheet.Default.AddRule(".canvas").style
                .Aggregate(s => s.overflow = IStyle.OverflowEnum.hidden)
                .Aggregate(s => s.backgroundColor = Color.Black)
                ;

            IStyleSheet.Default.AddRule(".on").style
                .Aggregate(s =>
                    
                        new HTML.Images.FromAssets.vistaLogoOn().ToBackground(s)
                    
                   )
                //.Aggregate(s => s.Opacity = 0.8)
                ;

            IStyleSheet.Default.AddRule(".off").style
                .Aggregate(s => 
                    
                        new HTML.Images.FromAssets.vistaLogoOff().ToBackground(s)
                    
                  )
                //.Aggregate(s => s.Opacity = 0.5)
                ;




            Action<int, int> UpdateColor =
                (x, y) =>
                {
                    var n = a[x, y];

                    if (m[x, y])
                    {
                        n.className = "on";
                    }
                    else
                    {
                        n.className = "off";
                    }

                };

            Action<int, int> ToggleDirect =
                (x, y) =>
                {
                    var n = a[x, y];

                    if (n == null)
                        return;

                    m[x, y] = !m[x, y];
                    UpdateColor(x, y);
                };

            Action<int, int> Toggle =
                (x, y) =>
                {
                    //Console.WriteLine("click at: " + new { x, y } + " = " + m[x, y]);

                    var f = ToggleDirect.WithOffset(x, y);

                    f(-1, 0);
                    f(0, -1);
                    f(0, 0);
                    f(0, 1);
                    f(1, 0);
                };


            var info_stats_clicks = new IHTMLDiv();
            var info_stats_clicks_count = 0;
            var info_stats_off = new IHTMLDiv();
            var info_stats_on = new IHTMLDiv();

            Action info_stats_update =
                () =>
                {
                    info_stats_clicks.innerHTML = info_stats_clicks_count + " clicks made so far";
                    info_stats_on.innerHTML = m.Count(i => i) + " blocks are on";
                    info_stats_off.innerHTML = m.Count(i => !i) + " blocks are off";

                };

            var info_stats = new IHTMLDiv(info_stats_clicks, info_stats_off, info_stats_on);
            info_stats.className = "info";


            a.ForEach(
                (x, y) =>
                {
                    var n = new IHTMLDiv();

                    n.style.left = (x * usersettings.tile.w + usersettings.tile.w / 2) + "px";
                    n.style.top = (y * usersettings.tile.h + usersettings.tile.h / 2) + "px";
                    n.style.width = usersettings.tile.w + "px";
                    n.style.height = usersettings.tile.h + "px";
                    n.style.position = IStyle.PositionEnum.absolute;
                    n.style.overflow = IStyle.OverflowEnum.hidden;

                    //n.style.border = "1px solid black";
                    n.style.cursor = IStyle.CursorEnum.pointer;

                    canvas.appendChild(n);

                    var tween = new TweenDataDouble();


                    tween.ValueChanged += () => n.style.Opacity = tween.Value;
                    tween.Value = usersettings.tile.cold;

                    n.style.Opacity = tween.Value;

                    n.onmouseover += delegate
                    {
                        tween.Value = 1;
                        //canvas_bg_tween.Value = 0.5;
                    };

                    n.onmouseout += delegate
                    {
                        tween.Value = usersettings.tile.cold;
                        //canvas_bg_tween.Value = 1;
                    };

                    n.onclick += delegate
                    {
                        info_stats_clicks_count++;

                        Toggle(x, y);


                        info_stats_update();
                    };


                    a[x, y] = n;

                    UpdateColor(x, y);

                }
            );

            var ani = new Timer(t =>
                               canvas_bg.style.left = -(int)System.Math.Floor((double)((IDate.Now.getTime() / 75) % canvas_size.x)) + "px");




            var info = new IHTMLDiv();

            var info_header_text = "Lights out 2";

            Native.Document.title = info_header_text;

            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, info_header_text));

            info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "based on SilverlightsOut"));
            info.appendChild(new IHTMLBreak());
            info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/CommentView,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "cjcraft blog post"));

            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.p,
                @"Lights out is a one player puzzle that is played on a 5 by 5 grid of squares in which every square has two states: on and off. The game starts off with all squares off, where the goal is to turn on every square. By selecting a square, all the surrounding squares' (up, down, left, right) state is turned toggled. For example, on a 3 by 3 grid of squares with all squares off, if the center one is selected, it will turn 'on' the 4 up, down, left, right squares from it."));

            info.appendChild(new IHTMLDiv("Mozilla based browsers seem to suffer in performance while animating contents under semitransparent elements."));

            info.appendChild(new IHTMLButton("Animate background").Aggregate(btn => btn.onclick += delegate { ani.StartInterval(50); }));
            info.appendChild(new IHTMLButton("Freeze background").Aggregate(btn => btn.onclick += delegate { ani.Stop(); }));
            info.appendChild(info_stats);
            info.appendChild(canvas);

            info_stats_update();

            DataElement.insertNextSibling(info);

        }
예제 #52
0
 public static Cell[,] Deserialize(string s) => Array2D.ConvertTo2DArray(s.Split(RowSeperator)
                                                                         .Select(row => row.Split(CellSeperator).Select(DeserializeCell).ToArray())
                                                                         .ToArray());
예제 #53
0
 private Array2D<bool> GetMap()
 {
     // Create the map if it hasn't been created yet or is the wrong size.
     if (map == null || map.Height != levelHeight || map.Width != levelWidth)
     {
         map = new Array2D<bool>(levelHeight, levelWidth);
     }
     return map;
 }
예제 #54
0
 public static void Test <T>(
     Array2D <T> src, Array2D <T> dest, Bounds2D sectorSize, Array2D <T> expected)
 {
     src.CopyTo(dest, sectorSize);
     CollectionAssert.AreEqual(expected, dest);
 }
예제 #55
0
 public Level(Array2D<Cell> data)
     : base(data)
 {
     Initialize();
 }
예제 #56
0
 public static void Test <T>(
     Array2D <T> src, Array2D <T> dest, Index2D destIndex, Array2D <T> expected)
 {
     src.CopyTo(dest, destIndex);
     CollectionAssert.AreEqual(expected, dest);
 }
예제 #57
0
        private void AssessBoxes()
        {
            boxesAssessed = true;

            sokobans = 0;
            boxes = 0;
            targets = 0;
            unfinishedBoxes = 0;
            boxMap = new Array2D<int>(levelHeight, levelWidth);
            List<Coordinate2D> boxList = new List<Coordinate2D>();

            int rowLimit = levelHeight - 1;
            int columnLimit = levelWidth - 1;

            for (int row = 1; row < rowLimit; row++)
            {
                for (int column = 1; column < columnLimit; column++)
                {
                    Cell cell = data[row, column];
                    if (IsSokobanBoxOrTarget(cell))
                    {
                        if (IsSokoban(cell))
                        {
                            // While we're at it, record the sokoban square.
                            if (!sokobanAssessed)
                            {
                                sokobanAssessed = true;
                                sokobanRow = row;
                                sokobanColumn = column;
                            }
                            sokobans++;
                        }
                        else if (IsBox(cell))
                        {
                            boxMap[row, column] = boxes;
                            boxList.Add(new Coordinate2D(row, column));
                            boxes++;

                            if (!IsTarget(cell))
                            {
                                unfinishedBoxes++;
                            }
                        }
                        if (IsTarget(cell))
                        {
                            targets++;
                        }
                    }
                }
            }

            boxCoordinates = boxList.ToArray();
        }
예제 #58
0
 public DefinitionNodeGrid(Array2D <DefinitionNode> nodeGrid, Vector2 scale, Vector2 offset = default)
 {
     Transformer = new GridTransformer(new Point2(nodeGrid.Width, nodeGrid.Height), scale, offset);
     NodeGrid    = nodeGrid;
 }
예제 #59
0
        protected void CalculateLowerBoundMaps()
        {
            // Create the pre-calculated lower bound data structures.

            // Create work arrays for matching lower bound function.
            boxTarget = new int[boxes];
            targetBox = new int[targets];
            distance = new int[boxes];

            // Create an empty level with path finder for measuring distances.
            Level emptyLevel = LevelUtils.GetEmptyLevel(originalLevel);
            PathFinder emptyPathFinder = PathFinder.CreateInstance(emptyLevel, true);

            // Create the target distance maps and target index map.
            targetDistanceMaps = new Array2D<int>[targets];
            targetIndexMap = new Array2D<int>(level.Height, level.Width);
            targetIndexMap.SetAll(-1);
            for (int i = 0; i < targets; i++)
            {
                targetDistanceMaps[i] = new Array2D<int>(level.Height, level.Width);
                targetIndexMap[targetCoordinates[i]] = i;
            }

            // For each inside square calculate the sorted list of nearest targets and
            // the distance to the nearest target.
            nearestTargetsMap = new Array2D<int[]>(level.Height, level.Width);
            nearestTargetDistanceMap = new Array2D<int>(level.Height, level.Width);
            foreach (Coordinate2D boxCoord in level.InsideCoordinates)
            {
                List<int> nearestTargets = new List<int>();
                for (int j = 0; j < targets; j++)
                {
                    Coordinate2D targetCoord = targetCoordinates[j];
                    targetDistanceMaps[j][boxCoord] = emptyPathFinder.FindAndGetDistance(boxCoord, targetCoord);
                    nearestTargets.Add(j);
                }
                nearestTargets.Sort(delegate(int index1, int index2)
                    {
                        int distance1 = targetDistanceMaps[index1][boxCoord];
                        int distance2 = targetDistanceMaps[index2][boxCoord];
                        return distance1.CompareTo(distance2);
                    });
                nearestTargetDistanceMap[boxCoord] = targetDistanceMaps[nearestTargets[0]][boxCoord];
                nearestTargetsMap[boxCoord] = nearestTargets.ToArray();
            }
        }
예제 #60
0
 public static WriteableBitmap ToWriteableBitmap <T>(this Array2D <T> array)
     where T : struct
 {
     return(ToWriteableBitmap(array, 96, 96));
 }