= 0. */ function openstation_files_grid_point_to_cell( $x, $y ) { $col = (int) round( ( (int) $x - OPENSTATION_GRID_PADDING ) / OPENSTATION_GRID_CELL_W ); $row = (int) round( ( (int) $y - OPENSTATION_GRID_PADDING ) / OPENSTATION_GRID_CELL_H ); return array( max( 0, $col ), max( 0, $row ) ); } /** * The pixel coordinate of a cell. * * @param int $col Column index. * @param int $row Row index. * @return array{x:int,y:int} Placement coordinates. */ function openstation_files_grid_cell_to_point( $col, $row ) { return array( 'x' => OPENSTATION_GRID_PADDING + max( 0, (int) $col ) * OPENSTATION_GRID_CELL_W, 'y' => OPENSTATION_GRID_PADDING + max( 0, (int) $row ) * OPENSTATION_GRID_CELL_H, ); } /** * Build an occupancy set from rows carrying `x` / `y`. * * Keys are `","`, the same convention `cellKey()` uses on * the client. * * @param array $rows Rows with `x` and `y` keys. * @return array Occupancy set. */ function openstation_files_grid_occupied( $rows ) { $occupied = array(); foreach ( (array) $rows as $row ) { if ( ! isset( $row['x'], $row['y'] ) ) { continue; } list( $col, $r ) = openstation_files_grid_point_to_cell( $row['x'], $row['y'] ); $occupied[ "$col,$r" ] = true; } return $occupied; } /** * First free cell in `$order`, wrapping at the assumed canvas edge. * * Marks the cell it returns, so a caller allocating several in a row * gets consecutive slots without bookkeeping of its own. * * @param array $occupied Occupancy set, by reference. * @param string $order `'column'` or `'row'`. * @return array{0:int,1:int} `array( $col, $row )`. */ function openstation_files_grid_next_free( &$occupied, $order = 'column' ) { if ( 'row' === $order ) { $outer = OPENSTATION_GRID_SCAN_LIMIT; $inner = OPENSTATION_GRID_FALLBACK_COLS; } else { $outer = OPENSTATION_GRID_SCAN_LIMIT; $inner = OPENSTATION_GRID_FALLBACK_ROWS; } for ( $o = 0; $o < $outer; $o++ ) { for ( $i = 0; $i < $inner; $i++ ) { $col = 'row' === $order ? $i : $o; $row = 'row' === $order ? $o : $i; if ( ! isset( $occupied[ "$col,$row" ] ) ) { $occupied[ "$col,$row" ] = true; return array( $col, $row ); } } } $occupied['0,0'] = true; return array( 0, 0 ); }