Advertisement
Guest User

Untitled

a guest
Feb 8th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. CREATE OR REPLACE FUNCTION left_shift( p_val INT8,
  2.                                       p_shift INT8) returns int8
  3. AS
  4.   $$
  5.   DECLARE
  6.   BEGIN
  7.     RETURN TRUNC(p_val * POWER(2,p_shift));
  8.   END;
  9.   $$ LANGUAGE 'plpgsql' immutable;
  10.  
  11. CREATE OR REPLACE FUNCTION morton (p_col INT8,
  12.                                    p_row INT8) returns int8
  13. AS
  14.   $$
  15.   /*  this procedure calculates the Morton number of a cell
  16. at the given row and col[umn]
  17. Written:  D.M. Mark, Jan 1984;
  18. Converted to Vax/VMS: July 1985
  19. Converted to PostgreSQL, Simon Greener, 2010
  20. */
  21.   DECLARE
  22.     v_row int8 := 0;
  23.     v_col int8 := 0;
  24.     v_key int8;
  25.     v_level int8;
  26.     v_left_bit int8;
  27.     v_right_bit int8;
  28.     v_quadrant int8;
  29.   BEGIN
  30.     v_row := p_row;
  31.     v_col := p_col;
  32.     v_key := 0;
  33.     v_level := 0;
  34.     WHILE ((v_row>0)
  35.     OR
  36.     (
  37.       v_col>0
  38.     )
  39.     )
  40.     LOOP
  41.       /* Split off the row (left_bit) and column (right_bit) bits and
  42. then combine them to form a bit-pair representing the quadrant */
  43.       v_left_bit := v_row % 2;
  44.       v_right_bit := v_col % 2;
  45.       v_quadrant := v_right_bit + 2*v_left_bit;
  46.       v_key := v_key            + left_shift( v_quadrant,( 2 * v_level ) );
  47.       /* row, column, and level are then modified before the loop continues */
  48.       v_row := v_row     / 2;
  49.       v_col := v_col     / 2;
  50.       v_level := v_level + 1;
  51.     END LOOP;
  52.     RETURN (v_key);
  53.   END;
  54.   $$ LANGUAGE 'plpgsql' immutable;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement