Ejemplo n.º 1
0
void QgsCustomProjectionDialog::on_pbnCalculate_clicked()
{


  //
  // We must check the prj def is valid!
  //

  projPJ myProj = pj_init_plus( teParameters->toPlainText().toLocal8Bit().data() );

  QgsDebugMsg( QString( "My proj: %1" ).arg( teParameters->toPlainText() ) );

  if ( !myProj )
  {
    QMessageBox::information( this, tr( "QGIS Custom Projection" ),
                              tr( "This proj4 projection definition is not valid." ) );
    projectedX->setText( "" );
    projectedY->setText( "" );
    pj_free( myProj );
    return;

  }
  // Get the WGS84 coordinates
  bool okN, okE;
  double northing = northWGS84->text().toDouble( &okN ) * DEG_TO_RAD;
  double easthing = eastWGS84->text().toDouble( &okE )  * DEG_TO_RAD;

  if ( !okN || !okE )
  {
    QMessageBox::information( this, tr( "QGIS Custom Projection" ),
                              tr( "Northing and Easthing must be in decimal form." ) );
    projectedX->setText( "" );
    projectedY->setText( "" );
    pj_free( myProj );
    return;
  }

  projPJ wgs84Proj = pj_init_plus( GEOPROJ4.toLocal8Bit().data() ); //defined in qgis.h

  if ( !wgs84Proj )
  {
    QMessageBox::information( this, tr( "QGIS Custom Projection" ),
                              tr( "Internal Error (source projection invalid?)" ) );
    projectedX->setText( "" );
    projectedY->setText( "" );
    pj_free( wgs84Proj );
    return;
  }

  double z = 0.0;

  int projResult = pj_transform( wgs84Proj, myProj, 1, 0, &easthing, &northing, &z );
  if ( projResult != 0 )
  {
    projectedX->setText( tr( "Error" ) );
    projectedY->setText( tr( "Error" ) );
    QgsDebugMsg( pj_strerrno( projResult ) );
  }
  else
  {
    QString tmp;

    tmp = QLocale::system().toString( northing, 'f', 4 );
    projectedX->setText( tmp );
    tmp = QLocale::system().toString( easthing, 'f', 4 );
    projectedY->setText( tmp );
  }

  //
  pj_free( myProj );
  pj_free( wgs84Proj );

}
Ejemplo n.º 2
0
PJ *
pj_init(int argc, char **argv) {
	char *s, *name;
        paralist *start = NULL;
	PJ *(*proj)(PJ *);
	paralist *curr;
	int i;
	PJ *PIN = 0;

	errno = pj_errno = 0;
        start = NULL;

	/* put arguments into internal linked list */
	if (argc <= 0) { pj_errno = -1; goto bum_call; }
	for (i = 0; i < argc; ++i)
		if (i)
			curr = curr->next = pj_mkparam(argv[i]);
		else
			start = curr = pj_mkparam(argv[i]);
	if (pj_errno) goto bum_call;

	/* check if +init present */
	if (pj_param(start, "tinit").i) {
		paralist *last = curr;

		if (!(curr = get_init(&start, curr, pj_param(start, "sinit").s)))
			goto bum_call;
		if (curr == last) { pj_errno = -2; goto bum_call; }
	}

	/* find projection selection */
	if (!(name = pj_param(start, "sproj").s))
		{ pj_errno = -4; goto bum_call; }
	for (i = 0; (s = pj_list[i].id) && strcmp(name, s) ; ++i) ;
	if (!s) { pj_errno = -5; goto bum_call; }

	/* set defaults, unless inhibited */
	if (!pj_param(start, "bno_defs").i)
		curr = get_defaults(&start, curr, name);
	proj = (PJ *(*)(PJ *)) pj_list[i].proj;

	/* allocate projection structure */
	if (!(PIN = (*proj)(0))) goto bum_call;
	PIN->params = start;
        PIN->is_latlong = 0;
        PIN->is_geocent = 0;
        PIN->long_wrap_center = 0.0;

        /* set datum parameters */
        if (pj_datum_set(start, PIN)) goto bum_call;

	/* set ellipsoid/sphere parameters */
	if (pj_ell_set(start, &PIN->a, &PIN->es)) goto bum_call;

	PIN->e = sqrt(PIN->es);
	PIN->ra = 1. / PIN->a;
	PIN->one_es = 1. - PIN->es;
	if (PIN->one_es == 0.) { pj_errno = -6; goto bum_call; }
	PIN->rone_es = 1./PIN->one_es;

        /* Now that we have ellipse information check for WGS84 datum */
        if( PIN->datum_type == PJD_3PARAM 
            && PIN->datum_params[0] == 0.0
            && PIN->datum_params[1] == 0.0
            && PIN->datum_params[2] == 0.0
            && PIN->a == 6378137.0
            && ABS(PIN->es - 0.006694379990) < 0.000000000050 )/*WGS84/GRS80*/
        {
            PIN->datum_type = PJD_WGS84;
        }
        
	/* set PIN->geoc coordinate system */
	PIN->geoc = (PIN->es && pj_param(start, "bgeoc").i);

	/* over-ranging flag */
	PIN->over = pj_param(start, "bover").i;

	/* longitude center for wrapping */
	PIN->long_wrap_center = pj_param(start, "rlon_wrap").f;

	/* central meridian */
	PIN->lam0=pj_param(start, "rlon_0").f;

	/* central latitude */
	PIN->phi0 = pj_param(start, "rlat_0").f;

	/* false easting and northing */
	PIN->x0 = pj_param(start, "dx_0").f;
	PIN->y0 = pj_param(start, "dy_0").f;

	/* general scaling factor */
	if (pj_param(start, "tk_0").i)
		PIN->k0 = pj_param(start, "dk_0").f;
	else if (pj_param(start, "tk").i)
		PIN->k0 = pj_param(start, "dk").f;
	else
		PIN->k0 = 1.;
	if (PIN->k0 <= 0.) {
		pj_errno = -31;
		goto bum_call;
	}

	/* set units */
	s = 0;
	if (name = pj_param(start, "sunits").s) { 
		for (i = 0; (s = pj_units[i].id) && strcmp(name, s) ; ++i) ;
		if (!s) { pj_errno = -7; goto bum_call; }
		s = pj_units[i].to_meter;
	}
	if (s || (s = pj_param(start, "sto_meter").s)) {
		PIN->to_meter = strtod(s, &s);
		if (*s == '/') /* ratio number */
			PIN->to_meter /= strtod(++s, 0);
		PIN->fr_meter = 1. / PIN->to_meter;
	} else
		PIN->to_meter = PIN->fr_meter = 1.;

	/* prime meridian */
	s = 0;
	if (name = pj_param(start, "spm").s) { 
            const char *value = NULL;
            char *next_str = NULL;

            for (i = 0; pj_prime_meridians[i].id != NULL; ++i )
            {
                if( strcmp(name,pj_prime_meridians[i].id) == 0 )
                {
                    value = pj_prime_meridians[i].defn;
                    break;
                }
            }
            
            if( value == NULL 
                && (dmstor(name,&next_str) != 0.0  || *name == '0')
                && *next_str == '\0' )
                value = name;

            if (!value) { pj_errno = -46; goto bum_call; }
            PIN->from_greenwich = dmstor(value,NULL);
	}
        else
            PIN->from_greenwich = 0.0;

	/* projection specific initialization */
	if (!(PIN = (*proj)(PIN)) || errno || pj_errno) {
bum_call: /* cleanup error return */
		if (!pj_errno)
			pj_errno = errno;
		if (PIN)
			pj_free(PIN);
		else
			for ( ; start; start = curr) {
				curr = start->next;
				pj_dalloc(start);
			}
		PIN = 0;
	}
	return PIN;
}
Ejemplo n.º 3
0
static void proj_free(void* p){
  _wrap_pj * wpj = (_wrap_pj*) p;
  if(wpj->pj != 0)
    pj_free(wpj->pj);
  free(p);
}
Ejemplo n.º 4
0
Datum transform_geom(PG_FUNCTION_ARGS)
{
	GSERIALIZED *geom;
	GSERIALIZED *result=NULL;
	LWGEOM *lwgeom;
	projPJ input_pj, output_pj;
	char *input_proj4, *output_proj4;
	text *input_proj4_text;
	text *output_proj4_text;
	int32 result_srid ;
	char *pj_errstr;



	result_srid = PG_GETARG_INT32(3);
	if (result_srid == SRID_UNKNOWN)
	{
		elog(ERROR,"tranform: destination SRID = %d",SRID_UNKNOWN);
		PG_RETURN_NULL();
	}

	geom = (GSERIALIZED *)PG_DETOAST_DATUM_COPY(PG_GETARG_DATUM(0));
	if (gserialized_get_srid(geom) == SRID_UNKNOWN)
	{
		pfree(geom);
		elog(ERROR,"transform_geom: source SRID = %d",SRID_UNKNOWN);
		PG_RETURN_NULL();
	}

	/* Set the search path if we haven't already */
	SetPROJ4LibPath();

	/* Read the arguments */
	input_proj4_text  = (PG_GETARG_TEXT_P(1));
	output_proj4_text = (PG_GETARG_TEXT_P(2));

	/* Convert from text to cstring for libproj */
	input_proj4 = text2cstring(input_proj4_text);
	output_proj4 = text2cstring(output_proj4_text);

	/* make input and output projection objects */
	input_pj = lwproj_from_string(input_proj4);
	if ( input_pj == NULL )
	{
		pj_errstr = pj_strerrno(*pj_get_errno_ref());
		if ( ! pj_errstr ) pj_errstr = "";

		/* we need this for error reporting */
		/* pfree(input_proj4); */
		pfree(output_proj4);
		pfree(geom);
		
		elog(ERROR,
		    "transform_geom: could not parse proj4 string '%s' %s",
		    input_proj4, pj_errstr);
		PG_RETURN_NULL();
	}
	pfree(input_proj4);

	output_pj = lwproj_from_string(output_proj4);

	if ( output_pj == NULL )
	{
		pj_errstr = pj_strerrno(*pj_get_errno_ref());
		if ( ! pj_errstr ) pj_errstr = "";

		/* we need this for error reporting */
		/* pfree(output_proj4); */
		pj_free(input_pj);
		pfree(geom);

		elog(ERROR,
			"transform_geom: couldn't parse proj4 output string: '%s': %s",
			output_proj4, pj_errstr);
		PG_RETURN_NULL();
	}
	pfree(output_proj4);

	/* now we have a geometry, and input/output PJ structs. */
	lwgeom = lwgeom_from_gserialized(geom);
	lwgeom_transform(lwgeom, input_pj, output_pj);
	lwgeom->srid = result_srid;

	/* clean up */
	pj_free(input_pj);
	pj_free(output_pj);

	/* Re-compute bbox if input had one (COMPUTE_BBOX TAINTING) */
	if ( lwgeom->bbox )
	{
		lwgeom_drop_bbox(lwgeom);
		lwgeom_add_bbox(lwgeom);
	}

	result = geometry_serialize(lwgeom);

	lwgeom_free(lwgeom);
	PG_FREE_IF_COPY(geom, 0);

	PG_RETURN_POINTER(result); /* new geometry */
}
Ejemplo n.º 5
0
int libcs2cs(int argc,char** argv,double* input1,double* input2,double* input3) 
{
    char *arg, **eargv = argv, *from_argv[MAX_PARGS], *to_argv[MAX_PARGS],
        **iargv = argv;
    FILE *fid;
    int from_argc=0, to_argc=0, iargc = argc, eargc = 0, c, mon = 0;
    int have_to_flag = 0, inverse = 0, i;
	projUV data;
	double z;

    if (emess_dat.Prog_name = strrchr(*argv,DIR_CHAR))
        ++emess_dat.Prog_name;
    else emess_dat.Prog_name = *argv;
    inverse = ! strncmp(emess_dat.Prog_name, "inv", 3);
    if (argc <= 1 ) {
        (void)fprintf(stderr, usage, pj_get_release(), emess_dat.Prog_name);
        exit (0);
    }
    /* process run line arguments */
    while (--argc > 0) { /* collect run line arguments */
        if(**++argv == '-') for(arg = *argv;;) {
            switch(*++arg) {
              case '\0': /* position of "stdin" */
                if (arg[-1] == '-') eargv[eargc++] = "-";
                break;
              case 'v': /* monitor dump of initialization */
                mon = 1;
                continue;
              case 'I': /* alt. method to spec inverse */
                inverse = 1;
                continue;
              case 'E': /* echo ascii input to ascii output */
                echoin = 1;
                continue;
              case 't': /* set col. one char */
                if (arg[1]) tag = *++arg;
                else emess(1,"missing -t col. 1 tag");
                continue;
              case 'l': /* list projections, ellipses or units */
                if (!arg[1] || arg[1] == 'p' || arg[1] == 'P') {
                    /* list projections */
                    struct PJ_LIST *lp;
                    int do_long = arg[1] == 'P', c;
                    char *str;

                    for (lp = pj_get_list_ref() ; lp->id ; ++lp) {
                        (void)printf("%s : ", lp->id);
                        if (do_long)  /* possibly multiline description */
                            (void)puts(*lp->descr);
                        else { /* first line, only */
                            str = *lp->descr;
                            while ((c = *str++) && c != '\n')
                                putchar(c);
                            putchar('\n');
                        }
                    }
                } else if (arg[1] == '=') { /* list projection 'descr' */
                    struct PJ_LIST *lp;

                    arg += 2;
                    for (lp = pj_get_list_ref() ; lp->id ; ++lp)
                        if (!strcmp(lp->id, arg)) {
                            (void)printf("%9s : %s\n", lp->id, *lp->descr);
                            break;
                        }
                } else if (arg[1] == 'e') { /* list ellipses */
                    struct PJ_ELLPS *le;

                    for (le = pj_get_ellps_ref(); le->id ; ++le)
                        (void)printf("%9s %-16s %-16s %s\n",
                                     le->id, le->major, le->ell, le->name);
                } else if (arg[1] == 'u') { /* list units */
                    struct PJ_UNITS *lu;

                    for (lu = pj_get_units_ref(); lu->id ; ++lu)
                        (void)printf("%12s %-20s %s\n",
                                     lu->id, lu->to_meter, lu->name);
                } else if (arg[1] == 'd') { /* list datums */
                    struct PJ_DATUMS *ld;

                    printf("__datum_id__ __ellipse___ __definition/comments______________________________\n" );
                    for (ld = pj_get_datums_ref(); ld->id ; ++ld)
                    {
                        printf("%12s %-12s %-30s\n",
                               ld->id, ld->ellipse_id, ld->defn);
                        if( ld->comments != NULL && strlen(ld->comments) > 0 )
                            printf( "%25s %s\n", " ", ld->comments );
                    }
                } else if( arg[1] == 'm') { /* list prime meridians */
                    struct PJ_PRIME_MERIDIANS *lpm;

                    for (lpm = pj_get_prime_meridians_ref(); lpm->id ; ++lpm)
                        (void)printf("%12s %-30s\n",
                                     lpm->id, lpm->defn);
                } else
                    emess(1,"invalid list option: l%c",arg[1]);
                exit(0);
                continue; /* artificial */
              case 'e': /* error line alternative */
                if (--argc <= 0)
                    noargument:			   
                emess(1,"missing argument for -%c",*arg);
                oterr = *++argv;
                continue;
              case 'W': /* specify seconds precision */
              case 'w': /* -W for constant field width */
                if ((c = arg[1]) != 0 && isdigit(c)) {
                    set_rtodms(c - '0', *arg == 'W');
                    ++arg;
                } else
                    emess(1,"-W argument missing or non-digit");
                continue;
              case 'f': /* alternate output format degrees or xy */
                if (--argc <= 0) goto noargument;
                oform = *++argv;
                continue;
              case 'r': /* reverse input */
                reversein = 1;
                continue;
              case 's': /* reverse output */
                reverseout = 1;
                continue;
              default:
                emess(1, "invalid option: -%c",*arg);
                break;
            }
            break;

        } else if (strcmp(*argv,"+to") == 0 ) {
            have_to_flag = 1;

        } else if (**argv == '+') { /* + argument */
            if( have_to_flag )
            {
                if( to_argc < MAX_PARGS )
                    to_argv[to_argc++] = *argv + 1;
                else
                    emess(1,"overflowed + argument table");
            }
            else 
            {
                if (from_argc < MAX_PARGS)
                    from_argv[from_argc++] = *argv + 1;
                else
                    emess(1,"overflowed + argument table");
            }
        } else /* assumed to be input file name(s) */
            eargv[eargc++] = *argv;
    }
    if (eargc == 0 ) /* if no specific files force sysin */
        eargv[eargc++] = "-";

    /* 
     * If the user has requested inverse, then just reverse the
     * coordinate systems.
     */
    if( inverse )
    {
        int     argcount;
        
        for( i = 0; i < MAX_PARGS; i++ )
        {
            char *arg;

            arg = from_argv[i];
            from_argv[i] = to_argv[i];
            to_argv[i] = arg;
        }

        argcount = from_argc;
        from_argc = to_argc;
        to_argc = argcount;
    }

    if (!(fromProj = pj_init(from_argc, from_argv)))
    {
        printf( "Using from definition: " );
        for( i = 0; i < from_argc; i++ )
            printf( "%s ", from_argv[i] );
        printf( "\n" );

        emess(3,"projection initialization failure\ncause: %s",
              pj_strerrno(pj_errno));
    }

    if( to_argc == 0 )
    {
        if (!(toProj = pj_latlong_from_proj( fromProj )))
        {
            printf( "Using to definition: " );
            for( i = 0; i < to_argc; i++ )
                printf( "%s ", to_argv[i] );
            printf( "\n" );
            
            emess(3,"projection initialization failure\ncause: %s",
                  pj_strerrno(pj_errno));
        }   
    }
    else if (!(toProj = pj_init(to_argc, to_argv)))
    {
        printf( "Using to definition: " );
        for( i = 0; i < to_argc; i++ )
            printf( "%s ", to_argv[i] );
        printf( "\n" );

        emess(3,"projection initialization failure\ncause: %s",
              pj_strerrno(pj_errno));
    }

    if (mon) {
        printf( "%c ---- From Coordinate System ----\n", tag );
        pj_pr_list(fromProj);
        printf( "%c ---- To Coordinate System ----\n", tag );
        pj_pr_list(toProj);
    }

	if (reversein)
	{
		data.v = *input1;
		data.u = *input2;
	}
	else
	{
		data.u = *input1;
		data.v = *input2;
	}
	z = *input3;
	if (data.v == HUGE_VAL) data.u = HUGE_VAL;
	if (data.u != HUGE_VAL)
	{
		if( pj_transform( fromProj, toProj, 1, 0, &(data.u), &(data.v), &z ) != 0 )
		{
			data.u = HUGE_VAL;
			data.v = HUGE_VAL;
		}
	}
	if (data.u == HUGE_VAL) return(1);/* error output */
	*input1=data.u;
	*input2=data.v;
	*input3=z;

    if( fromProj != NULL )
        pj_free( fromProj );
    if( toProj != NULL )
        pj_free( toProj );

    pj_deallocate_grids();

    return(0); /* normal completion */
}
Ejemplo n.º 6
0
Archivo: pj_init.c Proyecto: aleaf/swb
PJ *
pj_init_ctx(projCtx ctx, int argc, char **argv) {
    char *s, *name;
    paralist *start = NULL;
    PJ *(*proj)(PJ *);
    paralist *curr;
    int i;
    PJ *PIN = 0;
    char *old_locale;

    ctx->last_errno = 0;
    start = NULL;

    old_locale = strdup(setlocale(LC_NUMERIC, NULL));
    if( strcmp(old_locale,"C") != 0 )
        setlocale(LC_NUMERIC,"C");

    /* put arguments into internal linked list */
    if (argc <= 0) { pj_ctx_set_errno( ctx, -1 ); goto bum_call; }
    for (i = 0; i < argc; ++i)
        if (i)
            curr = curr->next = pj_mkparam(argv[i]);
        else
            start = curr = pj_mkparam(argv[i]);
    if (ctx->last_errno) goto bum_call;

    /* check if +init present */
    if (pj_param(ctx, start, "tinit").i) {
        paralist *last = curr;

        if (!(curr = get_init(ctx,&start, curr, pj_param(ctx, start, "sinit").s)))
            goto bum_call;
        if (curr == last) { pj_ctx_set_errno( ctx, -2); goto bum_call; }
    }

    /* find projection selection */
    if (!(name = pj_param(ctx, start, "sproj").s))
    { pj_ctx_set_errno( ctx, -4 ); goto bum_call; }
    for (i = 0; (s = pj_list[i].id) && strcmp(name, s) ; ++i) ;
    if (!s) { pj_ctx_set_errno( ctx, -5 ); goto bum_call; }

    /* set defaults, unless inhibited */
    if (!pj_param(ctx, start, "bno_defs").i)
        curr = get_defaults(ctx,&start, curr, name);
    proj = (PJ *(*)(PJ *)) pj_list[i].proj;

    /* allocate projection structure */
    if (!(PIN = (*proj)(0))) goto bum_call;
    PIN->ctx = ctx;
    PIN->params = start;
    PIN->is_latlong = 0;
    PIN->is_geocent = 0;
    PIN->is_long_wrap_set = 0;
    PIN->long_wrap_center = 0.0;
    strcpy( PIN->axis, "enu" );

    PIN->gridlist = NULL;
    PIN->gridlist_count = 0;

    PIN->vgridlist_geoid = NULL;
    PIN->vgridlist_geoid_count = 0;

    /* set datum parameters */
    if (pj_datum_set(ctx, start, PIN)) goto bum_call;

    /* set ellipsoid/sphere parameters */
    if (pj_ell_set(ctx, start, &PIN->a, &PIN->es)) goto bum_call;

    PIN->a_orig = PIN->a;
    PIN->es_orig = PIN->es;

    PIN->e = sqrt(PIN->es);
    PIN->ra = 1. / PIN->a;
    PIN->one_es = 1. - PIN->es;
    if (PIN->one_es == 0.) { pj_ctx_set_errno( ctx, -6 ); goto bum_call; }
    PIN->rone_es = 1./PIN->one_es;

    /* Now that we have ellipse information check for WGS84 datum */
    if( PIN->datum_type == PJD_3PARAM
        && PIN->datum_params[0] == 0.0
        && PIN->datum_params[1] == 0.0
        && PIN->datum_params[2] == 0.0
        && PIN->a == 6378137.0
        && ABS(PIN->es - 0.006694379990) < 0.000000000050 )/*WGS84/GRS80*/
    {
        PIN->datum_type = PJD_WGS84;
    }

    /* set PIN->geoc coordinate system */
    PIN->geoc = (PIN->es && pj_param(ctx, start, "bgeoc").i);

    /* over-ranging flag */
    PIN->over = pj_param(ctx, start, "bover").i;

    /* vertical datum geoid grids */
    PIN->has_geoid_vgrids = pj_param(ctx, start, "tgeoidgrids").i;
    if( PIN->has_geoid_vgrids ) /* we need to mark it as used. */
        pj_param(ctx, start, "sgeoidgrids");

    /* longitude center for wrapping */
    PIN->is_long_wrap_set = pj_param(ctx, start, "tlon_wrap").i;
    if (PIN->is_long_wrap_set)
        PIN->long_wrap_center = pj_param(ctx, start, "rlon_wrap").f;

    /* axis orientation */
    if( (pj_param(ctx, start,"saxis").s) != NULL )
    {
        static const char *axis_legal = "ewnsud";
        const char *axis_arg = pj_param(ctx, start,"saxis").s;
        if( strlen(axis_arg) != 3 )
        {
            pj_ctx_set_errno( ctx, PJD_ERR_AXIS );
            goto bum_call;
        }

        if( strchr( axis_legal, axis_arg[0] ) == NULL
            || strchr( axis_legal, axis_arg[1] ) == NULL
            || strchr( axis_legal, axis_arg[2] ) == NULL)
        {
            pj_ctx_set_errno( ctx, PJD_ERR_AXIS );
            goto bum_call;
        }

        /* it would be nice to validate we don't have on axis repeated */
        strcpy( PIN->axis, axis_arg );
    }

    PIN->is_long_wrap_set = pj_param(ctx, start, "tlon_wrap").i;
    if (PIN->is_long_wrap_set)
        PIN->long_wrap_center = pj_param(ctx, start, "rlon_wrap").f;

    /* central meridian */
    PIN->lam0=pj_param(ctx, start, "rlon_0").f;

    /* central latitude */
    PIN->phi0 = pj_param(ctx, start, "rlat_0").f;

    /* false easting and northing */
    PIN->x0 = pj_param(ctx, start, "dx_0").f;
    PIN->y0 = pj_param(ctx, start, "dy_0").f;

    /* general scaling factor */
    if (pj_param(ctx, start, "tk_0").i)
        PIN->k0 = pj_param(ctx, start, "dk_0").f;
    else if (pj_param(ctx, start, "tk").i)
        PIN->k0 = pj_param(ctx, start, "dk").f;
    else
        PIN->k0 = 1.;
    if (PIN->k0 <= 0.) {
        pj_ctx_set_errno( ctx, -31 );
        goto bum_call;
    }

    /* set units */
    s = 0;
    if ((name = pj_param(ctx, start, "sunits").s) != NULL) {
        for (i = 0; (s = pj_units[i].id) && strcmp(name, s) ; ++i) ;
        if (!s) { pj_ctx_set_errno( ctx, -7 ); goto bum_call; }
        s = pj_units[i].to_meter;
    }
    if (s || (s = pj_param(ctx, start, "sto_meter").s)) {
        PIN->to_meter = strtod(s, &s);
        if (*s == '/') /* ratio number */
            PIN->to_meter /= strtod(++s, 0);
        PIN->fr_meter = 1. / PIN->to_meter;
    } else
        PIN->to_meter = PIN->fr_meter = 1.;

    /* set vertical units */
    s = 0;
    if ((name = pj_param(ctx, start, "svunits").s) != NULL) {
        for (i = 0; (s = pj_units[i].id) && strcmp(name, s) ; ++i) ;
        if (!s) { pj_ctx_set_errno( ctx, -7 ); goto bum_call; }
        s = pj_units[i].to_meter;
    }
    if (s || (s = pj_param(ctx, start, "svto_meter").s)) {
        PIN->vto_meter = strtod(s, &s);
        if (*s == '/') /* ratio number */
            PIN->vto_meter /= strtod(++s, 0);
        PIN->vfr_meter = 1. / PIN->vto_meter;
    } else {
        PIN->vto_meter = PIN->to_meter;
        PIN->vfr_meter = PIN->fr_meter;
    }

    /* prime meridian */
    s = 0;
    if ((name = pj_param(ctx, start, "spm").s) != NULL) {
        const char *value = NULL;
        char *next_str = NULL;

        for (i = 0; pj_prime_meridians[i].id != NULL; ++i )
        {
            if( strcmp(name,pj_prime_meridians[i].id) == 0 )
            {
                value = pj_prime_meridians[i].defn;
                break;
            }
        }

        if( value == NULL
            && (dmstor_ctx(ctx,name,&next_str) != 0.0  || *name == '0')
            && *next_str == '\0' )
            value = name;

        if (!value) { pj_ctx_set_errno( ctx, -46 ); goto bum_call; }
        PIN->from_greenwich = dmstor_ctx(ctx,value,NULL);
    }
    else
        PIN->from_greenwich = 0.0;

    /* projection specific initialization */
    if (!(PIN = (*proj)(PIN)) || ctx->last_errno) {
      bum_call: /* cleanup error return */
        if (PIN)
            pj_free(PIN);
        else
            for ( ; start; start = curr) {
                curr = start->next;
                pj_dalloc(start);
            }
        PIN = 0;
    }

    if( strcmp(old_locale,"C") != 0 )
        setlocale(LC_NUMERIC,old_locale);
    free( (char*)old_locale );

    return PIN;
}
Ejemplo n.º 7
0
Projection::~Projection()
{
  pj_free(pj);
}
Ejemplo n.º 8
0
int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len)
{
    if( len > 1000 )
    {
#ifdef STANDALONE
        fprintf(stderr, "Input too large\n");
#endif
        return 0;
    }

    /* We expect the blob to be 3 lines: */
    /* source proj string\ndestination proj string\nx y */
    char* buf_dup = (char*)malloc(len+1);
    memcpy(buf_dup, buf, len);
    buf_dup[len] = 0;
    char* first_line = buf_dup;
    char* first_newline = strchr(first_line, '\n');
    if( !first_newline )
    {
        free(buf_dup);
        return 0;
    }
    first_newline[0] = 0;
    char* second_line = first_newline + 1;
    char* second_newline = strchr(second_line, '\n');
    if( !second_newline )
    {
        free(buf_dup);
        return 0;
    }
    second_newline[0] = 0;
    char* third_line = second_newline + 1;
    projPJ pj_src = pj_init_plus(first_line);
    if( !pj_src )
    {
        free(buf_dup);
        return 0;
    }
    projPJ pj_dst = pj_init_plus(second_line);
    if( !pj_dst )
    {
        free(buf_dup);
        pj_free(pj_src);
        pj_gc_unloadall(pj_get_default_ctx());
        pj_deallocate_grids();
        return 0;
    }
    double x = 0, y = 0, z = 9;
    bool from_binary = false;
    bool has_z = false;
    if( strncmp(third_line, "BINARY_2D:", strlen("BINARY_2D:")) == 0 &&
        third_line - first_line + strlen("BINARY_2D:") + 2 * sizeof(double) <= len )
    {
        from_binary = true;
        memcpy(&x, third_line + strlen("BINARY_2D:"), sizeof(double));
        memcpy(&y, third_line + strlen("BINARY_2D:") + sizeof(double), sizeof(double));
    }
    else if( strncmp(third_line, "BINARY_3D:", strlen("BINARY_3D:")) == 0 &&
             third_line - first_line + strlen("BINARY_3D:") + 3 * sizeof(double) <= len )
    {
        from_binary = true;
        has_z = true;
        memcpy(&x, third_line + strlen("BINARY_3D:"), sizeof(double));
        memcpy(&y, third_line + strlen("BINARY_3D:") + sizeof(double), sizeof(double));
        memcpy(&z, third_line + strlen("BINARY_3D:") + 2 * sizeof(double), sizeof(double));
    }
    else if( sscanf(third_line, "%lf %lf", &x, &y) != 2 )
    {
        free(buf_dup);
        pj_free(pj_src);
        pj_free(pj_dst);
        pj_gc_unloadall(pj_get_default_ctx());
        pj_deallocate_grids();
        return 0;
    }
#ifdef STANDALONE
    fprintf(stderr, "src=%s\n", first_line);
    fprintf(stderr, "dst=%s\n", second_line);
    if( from_binary )
    {
        if( has_z )
            fprintf(stderr, "coord (from binary)=%.18g %.18g %.18g\n", x, y, z);
        else
            fprintf(stderr, "coord (from binary)=%.18g %.18g\n", x, y);
    }
    else
        fprintf(stderr, "coord=%s\n", third_line);
#endif
    if( has_z )
        pj_transform( pj_src, pj_dst, 1, 0, &x, &y, &z );
    else
        pj_transform( pj_src, pj_dst, 1, 0, &x, &y, NULL );
    free(buf_dup);
    pj_free(pj_src);
    pj_free(pj_dst);
    pj_gc_unloadall(pj_get_default_ctx());
    pj_deallocate_grids();
    return 0;
}
int main( int argc, char **argv )

{
/* -------------------------------------------------------------------- */
/*      Our first pass is to establish the correct answers for all      */
/*      the tests.                                                      */
/* -------------------------------------------------------------------- */
    int i, test_count = sizeof(test_list) / sizeof(TestItem); 

    for( i = 0; i < test_count; i++ )
    {
        TestItem *test = test_list + i;

        projPJ src_pj, dst_pj;

        src_pj = pj_init_plus( test->src_def );
        dst_pj = pj_init_plus( test->dst_def );

        if( src_pj == NULL )
        {
            printf( "Unable to translate:\n%s\n", test->src_def );
            test->skip = 1;
            continue;
        }

        if( dst_pj == NULL )
        {
            printf( "Unable to translate:\n%s\n", test->dst_def );
            test->skip = 1;
            continue;
        }
        
        test->dst_x = test->src_x;
        test->dst_y = test->src_y;
        test->dst_z = test->src_z;

        test->dst_error = pj_transform( src_pj, dst_pj, 1, 0, 
                                        &(test->dst_x), 
                                        &(test->dst_y),
                                        &(test->dst_z) );
     
        pj_free( src_pj );
        pj_free( dst_pj );

        test->skip = 0;
    }

    printf( "%d tests initialized.\n", test_count );

/* -------------------------------------------------------------------- */
/*      Now launch a bunch of threads to repeat the tests.              */
/* -------------------------------------------------------------------- */
    pthread_t ahThread[num_threads];
    pthread_attr_t hThreadAttr;

    pthread_attr_init( &hThreadAttr );
    pthread_attr_setdetachstate( &hThreadAttr, PTHREAD_CREATE_DETACHED );

    for( i = 0; i < num_threads; i++ )
    {
        active_thread_count++;
        
        pthread_create( &(ahThread[i]), &hThreadAttr, 
                        TestThread, NULL );
    }

    printf( "%d test threads launched.\n", num_threads );
            
    while( active_thread_count > 0 )				       
        sleep( 1 );

    printf( "all tests complete.\n" );
    
}
Ejemplo n.º 10
0
GAIAGEO_DECLARE gaiaGeomCollPtr
gaiaTransform (gaiaGeomCollPtr org, char *proj_from, char *proj_to)
{
/* creates a new GEOMETRY reprojecting coordinates from the original one */
    int ib;
    int cnt;
    int i;
    double *xx;
    double *yy;
    double *zz;
    double *mm = NULL;
    double x;
    double y;
    double z = 0.0;
    double m = 0.0;
    int error = 0;
    int from_angle;
    int to_angle;
    gaiaPointPtr pt;
    gaiaLinestringPtr ln;
    gaiaLinestringPtr dst_ln;
    gaiaPolygonPtr pg;
    gaiaPolygonPtr dst_pg;
    gaiaRingPtr rng;
    gaiaRingPtr dst_rng;
    projPJ from_cs = pj_init_plus (proj_from);
    projPJ to_cs = pj_init_plus (proj_to);
    gaiaGeomCollPtr dst;
    if (org->DimensionModel == GAIA_XY_Z)
	dst = gaiaAllocGeomCollXYZ ();
    else if (org->DimensionModel == GAIA_XY_M)
	dst = gaiaAllocGeomCollXYM ();
    else if (org->DimensionModel == GAIA_XY_Z_M)
	dst = gaiaAllocGeomCollXYZM ();
    else
	dst = gaiaAllocGeomColl ();
/* setting up projection parameters */
    from_angle = gaiaIsLongLat (proj_from);
    to_angle = gaiaIsLongLat (proj_to);
    if (!from_cs)
	return dst;
    if (!to_cs)
	return dst;
    cnt = 0;
    pt = org->FirstPoint;
    while (pt)
      {
	  /* counting POINTs */
	  cnt++;
	  pt = pt->Next;
      }
    if (cnt)
      {
	  /* reprojecting POINTs */
	  xx = malloc (sizeof (double) * cnt);
	  yy = malloc (sizeof (double) * cnt);
	  zz = malloc (sizeof (double) * cnt);
	  if (org->DimensionModel == GAIA_XY_M
	      || org->DimensionModel == GAIA_XY_Z_M)
	      mm = malloc (sizeof (double) * cnt);
	  i = 0;
	  pt = org->FirstPoint;
	  while (pt)
	    {
		/* inserting points to be converted in temporary arrays */
		if (from_angle)
		  {
		      xx[i] = gaiaDegsToRads (pt->X);
		      yy[i] = gaiaDegsToRads (pt->Y);
		  }
		else
		  {
		      xx[i] = pt->X;
		      yy[i] = pt->Y;
		  }
		if (org->DimensionModel == GAIA_XY_Z
		    || org->DimensionModel == GAIA_XY_Z_M)
		    zz[i] = pt->Z;
		else
		    zz[i] = 0.0;
		if (org->DimensionModel == GAIA_XY_M
		    || org->DimensionModel == GAIA_XY_Z_M)
		    mm[i] = pt->M;
		i++;
		pt = pt->Next;
	    }
	  /* applying reprojection        */
	  if (pj_transform (from_cs, to_cs, cnt, 0, xx, yy, zz) == 0)
	    {
		/* inserting the reprojected POINTs in the new GEOMETRY */
		for (i = 0; i < cnt; i++)
		  {
		      if (to_angle)
			{
			    x = gaiaRadsToDegs (xx[i]);
			    y = gaiaRadsToDegs (yy[i]);
			}
		      else
			{
			    x = xx[i];
			    y = yy[i];
			}
		      if (org->DimensionModel == GAIA_XY_Z
			  || org->DimensionModel == GAIA_XY_Z_M)
			  z = zz[i];
		      else
			  z = 0.0;
		      if (org->DimensionModel == GAIA_XY_M
			  || org->DimensionModel == GAIA_XY_Z_M)
			  m = mm[i];
		      else
			  m = 0.0;
		      if (dst->DimensionModel == GAIA_XY_Z)
			  gaiaAddPointToGeomCollXYZ (dst, x, y, z);
		      else if (dst->DimensionModel == GAIA_XY_M)
			  gaiaAddPointToGeomCollXYM (dst, x, y, m);
		      else if (dst->DimensionModel == GAIA_XY_Z_M)
			  gaiaAddPointToGeomCollXYZM (dst, x, y, z, m);
		      else
			  gaiaAddPointToGeomColl (dst, x, y);
		  }
	    }
	  else
	      error = 1;
	  free (xx);
	  free (yy);
	  free (zz);
	  if (org->DimensionModel == GAIA_XY_M
	      || org->DimensionModel == GAIA_XY_Z_M)
	      free (mm);
      }
    if (error)
	goto stop;
    ln = org->FirstLinestring;
    while (ln)
      {
	  /* reprojecting LINESTRINGs */
	  cnt = ln->Points;
	  xx = malloc (sizeof (double) * cnt);
	  yy = malloc (sizeof (double) * cnt);
	  zz = malloc (sizeof (double) * cnt);
	  if (ln->DimensionModel == GAIA_XY_M
	      || ln->DimensionModel == GAIA_XY_Z_M)
	      mm = malloc (sizeof (double) * cnt);
	  for (i = 0; i < cnt; i++)
	    {
		/* inserting points to be converted in temporary arrays */
		if (ln->DimensionModel == GAIA_XY_Z)
		  {
		      gaiaGetPointXYZ (ln->Coords, i, &x, &y, &z);
		  }
		else if (ln->DimensionModel == GAIA_XY_M)
		  {
		      gaiaGetPointXYM (ln->Coords, i, &x, &y, &m);
		  }
		else if (ln->DimensionModel == GAIA_XY_Z_M)
		  {
		      gaiaGetPointXYZM (ln->Coords, i, &x, &y, &z, &m);
		  }
		else
		  {
		      gaiaGetPoint (ln->Coords, i, &x, &y);
		  }
		if (from_angle)
		  {
		      xx[i] = gaiaDegsToRads (x);
		      yy[i] = gaiaDegsToRads (y);
		  }
		else
		  {
		      xx[i] = x;
		      yy[i] = y;
		  }
		if (ln->DimensionModel == GAIA_XY_Z
		    || ln->DimensionModel == GAIA_XY_Z_M)
		    zz[i] = z;
		else
		    zz[i] = 0.0;
		if (ln->DimensionModel == GAIA_XY_M
		    || ln->DimensionModel == GAIA_XY_Z_M)
		    mm[i] = m;
	    }
	  /* applying reprojection        */
	  if (pj_transform (from_cs, to_cs, cnt, 0, xx, yy, zz) == 0)
	    {
		/* inserting the reprojected LINESTRING in the new GEOMETRY */
		dst_ln = gaiaAddLinestringToGeomColl (dst, cnt);
		for (i = 0; i < cnt; i++)
		  {
		      /* setting LINESTRING points */
		      if (to_angle)
			{
			    x = gaiaRadsToDegs (xx[i]);
			    y = gaiaRadsToDegs (yy[i]);
			}
		      else
			{
			    x = xx[i];
			    y = yy[i];
			}
		      if (ln->DimensionModel == GAIA_XY_Z
			  || ln->DimensionModel == GAIA_XY_Z_M)
			  z = zz[i];
		      else
			  z = 0.0;
		      if (ln->DimensionModel == GAIA_XY_M
			  || ln->DimensionModel == GAIA_XY_Z_M)
			  m = mm[i];
		      else
			  m = 0.0;
		      if (dst_ln->DimensionModel == GAIA_XY_Z)
			{
			    gaiaSetPointXYZ (dst_ln->Coords, i, x, y, z);
			}
		      else if (dst_ln->DimensionModel == GAIA_XY_M)
			{
			    gaiaSetPointXYM (dst_ln->Coords, i, x, y, m);
			}
		      else if (dst_ln->DimensionModel == GAIA_XY_Z_M)
			{
			    gaiaSetPointXYZM (dst_ln->Coords, i, x, y, z, m);
			}
		      else
			{
			    gaiaSetPoint (dst_ln->Coords, i, x, y);
			}
		  }
	    }
	  else
	      error = 1;
	  free (xx);
	  free (yy);
	  free (zz);
	  if (ln->DimensionModel == GAIA_XY_M
	      || ln->DimensionModel == GAIA_XY_Z_M)
	      free (mm);
	  if (error)
	      goto stop;
	  ln = ln->Next;
      }
    pg = org->FirstPolygon;
    while (pg)
      {
	  /* reprojecting POLYGONs */
	  rng = pg->Exterior;
	  cnt = rng->Points;
	  dst_pg = gaiaAddPolygonToGeomColl (dst, cnt, pg->NumInteriors);
	  xx = malloc (sizeof (double) * cnt);
	  yy = malloc (sizeof (double) * cnt);
	  zz = malloc (sizeof (double) * cnt);
	  if (rng->DimensionModel == GAIA_XY_M
	      || rng->DimensionModel == GAIA_XY_Z_M)
	      mm = malloc (sizeof (double) * cnt);
	  for (i = 0; i < cnt; i++)
	    {
		/* inserting points to be converted in temporary arrays [EXTERIOR RING] */
		if (rng->DimensionModel == GAIA_XY_Z)
		  {
		      gaiaGetPointXYZ (rng->Coords, i, &x, &y, &z);
		  }
		else if (rng->DimensionModel == GAIA_XY_M)
		  {
		      gaiaGetPointXYM (rng->Coords, i, &x, &y, &m);
		  }
		else if (rng->DimensionModel == GAIA_XY_Z_M)
		  {
		      gaiaGetPointXYZM (rng->Coords, i, &x, &y, &z, &m);
		  }
		else
		  {
		      gaiaGetPoint (rng->Coords, i, &x, &y);
		  }
		if (from_angle)
		  {
		      xx[i] = gaiaDegsToRads (x);
		      yy[i] = gaiaDegsToRads (y);
		  }
		else
		  {
		      xx[i] = x;
		      yy[i] = y;
		  }
		if (rng->DimensionModel == GAIA_XY_Z
		    || rng->DimensionModel == GAIA_XY_Z_M)
		    zz[i] = z;
		else
		    zz[i] = 0.0;
		if (rng->DimensionModel == GAIA_XY_M
		    || rng->DimensionModel == GAIA_XY_Z_M)
		    mm[i] = m;
	    }
	  /* applying reprojection        */
	  if (pj_transform (from_cs, to_cs, cnt, 0, xx, yy, zz) == 0)
	    {
		/* inserting the reprojected POLYGON in the new GEOMETRY */
		dst_rng = dst_pg->Exterior;
		for (i = 0; i < cnt; i++)
		  {
		      /* setting EXTERIOR RING points */
		      if (to_angle)
			{
			    x = gaiaRadsToDegs (xx[i]);
			    y = gaiaRadsToDegs (yy[i]);
			}
		      else
			{
			    x = xx[i];
			    y = yy[i];
			}
		      if (rng->DimensionModel == GAIA_XY_Z
			  || rng->DimensionModel == GAIA_XY_Z_M)
			  z = zz[i];
		      else
			  z = 0.0;
		      if (rng->DimensionModel == GAIA_XY_M
			  || rng->DimensionModel == GAIA_XY_Z_M)
			  m = mm[i];
		      else
			  m = 0.0;
		      if (dst_rng->DimensionModel == GAIA_XY_Z)
			{
			    gaiaSetPointXYZ (dst_rng->Coords, i, x, y, z);
			}
		      else if (dst_rng->DimensionModel == GAIA_XY_M)
			{
			    gaiaSetPointXYM (dst_rng->Coords, i, x, y, m);
			}
		      else if (dst_rng->DimensionModel == GAIA_XY_Z_M)
			{
			    gaiaSetPointXYZM (dst_rng->Coords, i, x, y, z, m);
			}
		      else
			{
			    gaiaSetPoint (dst_rng->Coords, i, x, y);
			}
		  }
	    }
	  else
	      error = 1;
	  free (xx);
	  free (yy);
	  free (zz);
	  if (rng->DimensionModel == GAIA_XY_M
	      || rng->DimensionModel == GAIA_XY_Z_M)
	      free (mm);
	  if (error)
	      goto stop;
	  for (ib = 0; ib < pg->NumInteriors; ib++)
	    {
		/* processing INTERIOR RINGS */
		rng = pg->Interiors + ib;
		cnt = rng->Points;
		xx = malloc (sizeof (double) * cnt);
		yy = malloc (sizeof (double) * cnt);
		zz = malloc (sizeof (double) * cnt);
		if (rng->DimensionModel == GAIA_XY_M
		    || rng->DimensionModel == GAIA_XY_Z_M)
		    mm = malloc (sizeof (double) * cnt);
		for (i = 0; i < cnt; i++)
		  {
		      /* inserting points to be converted in temporary arrays [INTERIOR RING] */
		      if (rng->DimensionModel == GAIA_XY_Z)
			{
			    gaiaGetPointXYZ (rng->Coords, i, &x, &y, &z);
			}
		      else if (rng->DimensionModel == GAIA_XY_M)
			{
			    gaiaGetPointXYM (rng->Coords, i, &x, &y, &m);
			}
		      else if (rng->DimensionModel == GAIA_XY_Z_M)
			{
			    gaiaGetPointXYZM (rng->Coords, i, &x, &y, &z, &m);
			}
		      else
			{
			    gaiaGetPoint (rng->Coords, i, &x, &y);
			}
		      if (from_angle)
			{
			    xx[i] = gaiaDegsToRads (x);
			    yy[i] = gaiaDegsToRads (y);
			}
		      else
			{
			    xx[i] = x;
			    yy[i] = y;
			}
		      if (rng->DimensionModel == GAIA_XY_Z
			  || rng->DimensionModel == GAIA_XY_Z_M)
			  zz[i] = z;
		      else
			  zz[i] = 0.0;
		      if (rng->DimensionModel == GAIA_XY_M
			  || rng->DimensionModel == GAIA_XY_Z_M)
			  mm[i] = m;
		  }
		/* applying reprojection        */
		if (pj_transform (from_cs, to_cs, cnt, 0, xx, yy, zz) == 0)
		  {
		      /* inserting the reprojected POLYGON in the new GEOMETRY */
		      dst_rng = gaiaAddInteriorRing (dst_pg, ib, cnt);
		      for (i = 0; i < cnt; i++)
			{
			    /* setting INTERIOR RING points */
			    if (to_angle)
			      {
				  x = gaiaRadsToDegs (xx[i]);
				  y = gaiaRadsToDegs (yy[i]);
			      }
			    else
			      {
				  x = xx[i];
				  y = yy[i];
			      }
			    if (rng->DimensionModel == GAIA_XY_Z
				|| rng->DimensionModel == GAIA_XY_Z_M)
				z = zz[i];
			    else
				z = 0.0;
			    if (rng->DimensionModel == GAIA_XY_M
				|| rng->DimensionModel == GAIA_XY_Z_M)
				m = mm[i];
			    else
				m = 0.0;
			    if (dst_rng->DimensionModel == GAIA_XY_Z)
			      {
				  gaiaSetPointXYZ (dst_rng->Coords, i, x, y, z);
			      }
			    else if (dst_rng->DimensionModel == GAIA_XY_M)
			      {
				  gaiaSetPointXYM (dst_rng->Coords, i, x, y, m);
			      }
			    else if (dst_rng->DimensionModel == GAIA_XY_Z_M)
			      {
				  gaiaSetPointXYZM (dst_rng->Coords, i, x, y, z,
						    m);
			      }
			    else
			      {
				  gaiaSetPoint (dst_rng->Coords, i, x, y);
			      }
			}
		  }
		else
		    error = 1;
		free (xx);
		free (yy);
		free (zz);
		if (rng->DimensionModel == GAIA_XY_M
		    || rng->DimensionModel == GAIA_XY_Z_M)
		    free (mm);
		if (error)
		    goto stop;
	    }
	  pg = pg->Next;
      }
/* destroying the PROJ4 params */
  stop:
    pj_free (from_cs);
    pj_free (to_cs);
    if (error)
      {
	  /* some error occurred */
	  gaiaPointPtr pP;
	  gaiaPointPtr pPn;
	  gaiaLinestringPtr pL;
	  gaiaLinestringPtr pLn;
	  gaiaPolygonPtr pA;
	  gaiaPolygonPtr pAn;
	  pP = dst->FirstPoint;
	  while (pP != NULL)
	    {
		pPn = pP->Next;
		gaiaFreePoint (pP);
		pP = pPn;
	    }
	  pL = dst->FirstLinestring;
	  while (pL != NULL)
	    {
		pLn = pL->Next;
		gaiaFreeLinestring (pL);
		pL = pLn;
	    }
	  pA = dst->FirstPolygon;
	  while (pA != NULL)
	    {
		pAn = pA->Next;
		gaiaFreePolygon (pA);
		pA = pAn;
	    }
	  dst->FirstPoint = NULL;
	  dst->LastPoint = NULL;
	  dst->FirstLinestring = NULL;
	  dst->LastLinestring = NULL;
	  dst->FirstPolygon = NULL;
	  dst->LastPolygon = NULL;
      }
    if (dst)
      {
	  gaiaMbrGeometry (dst);
	  dst->DeclaredType = org->DeclaredType;
      }
    return dst;
}
Ejemplo n.º 11
0
/**
  * Free a proj-based projector.
  *
  * @param p The proj-based projector to free.
  */
void _proj_free(projector *p) {
   pj_free((projPJ *)p->internals);
   free(p);
}
Ejemplo n.º 12
0
Projection::~Projection()
{
    pj_free(this->pj);
}
Ejemplo n.º 13
0
ProjectionPointTransformer::~ProjectionPointTransformer() {
    pj_free(this->from);
    pj_free(this->to);
}
Ejemplo n.º 14
0
//-----------------------------------------------------------------------------------------
Projection_libproj::~Projection_libproj()
{
    if (libProj != nullptr) {
		pj_free(libProj);
	}
}
Ejemplo n.º 15
0
static void TestThread()

{
    int i, test_count = sizeof(test_list) / sizeof(TestItem); 
    int repeat_count = num_iterations;
    int i_iter;

/* -------------------------------------------------------------------- */
/*      Initialize coordinate system definitions.                       */
/* -------------------------------------------------------------------- */
    projPJ *src_pj_list, *dst_pj_list;
    projCtx ctx = pj_ctx_alloc();
//    projCtx ctx = pj_get_default_ctx();
    
    src_pj_list = (projPJ *) calloc(test_count,sizeof(projPJ));
    dst_pj_list = (projPJ *) calloc(test_count,sizeof(projPJ));
                                
#if reinit_every_iteration == 0
    for( i = 0; i < test_count; i++ )
    {
        TestItem *test = test_list + i;

        src_pj_list[i] = pj_init_plus_ctx( ctx, test->src_def );
        dst_pj_list[i] = pj_init_plus_ctx( ctx, test->dst_def );
    }
#endif
    
/* -------------------------------------------------------------------- */
/*      Perform tests - over and over.                                  */
/* -------------------------------------------------------------------- */
    
    for( i_iter = 0; i_iter < repeat_count; i_iter++ )
    {
        for( i = 0; i < test_count; i++ )
        {
            TestItem *test = test_list + i;
            double x, y, z;
            int error;
            int skipTest = test->skip;
            
            x = test->src_x;
            y = test->src_y;
            z = test->src_z;

#if reinit_every_iteration == 1
            src_pj_list[i] = pj_init_plus_ctx( ctx, test->src_def );
            dst_pj_list[i] = pj_init_plus_ctx( ctx, test->dst_def );

            {
                int skipTest = (src_pj_list[i] == NULL || dst_pj_list[i] == NULL);
			
                if ( skipTest != test->skip )
                    fprintf( stderr, "Threaded projection initialization does not match unthreaded initialization\n" );

                if (skipTest)
                {
                    pj_free( src_pj_list[i] );
                    pj_free( dst_pj_list[i] );
                    continue;
                }
            }
#endif

            if ( test->skip )
                continue;

            error = pj_transform( src_pj_list[i], dst_pj_list[i], 1, 0, 
                                  &x, &y, &z );
            

            if( error != test->dst_error )
            {
                fprintf( stderr, "Got error %d, expected %d\n", 
                         error, test->dst_error );
            }

            if( x != test->dst_x || y != test->dst_y || z != test->dst_z )
            {
                fprintf( stderr, 
                         "Got %.15g,%.15g,%.15g\n"
                         "Expected %.15g,%.15g,%.15g\n",
                         x, y, z, 
                         test->dst_x, test->dst_y, test->dst_z );
            }

#if reinit_every_iteration == 1
            pj_free( src_pj_list[i] );
            pj_free( dst_pj_list[i] );
#endif
        }
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
#if reinit_every_iteration == 0
    for( i = 0; i < test_count; i++ )
    {
        pj_free( src_pj_list[i] );
        pj_free( dst_pj_list[i] );
    }
#endif
    
    free( src_pj_list );
    free( dst_pj_list );

    pj_ctx_free( ctx );

    printf( "%d iterations of the %d tests complete in thread X\n", 
            repeat_count, test_count );

    active_thread_count--;
}
Ejemplo n.º 16
0
	void clear() {
		if (pj) pj_free(pj);
		pj = 0;
	}
Ejemplo n.º 17
0
int main( int argc, char **argv )

{
/* -------------------------------------------------------------------- */
/*      Our first pass is to establish the correct answers for all      */
/*      the tests.                                                      */
/* -------------------------------------------------------------------- */
    int i, test_count = sizeof(test_list) / sizeof(TestItem); 

    for( i = 0; i < test_count; i++ )
    {
        TestItem *test = test_list + i;

        projPJ src_pj, dst_pj;

        src_pj = pj_init_plus( test->src_def );
        dst_pj = pj_init_plus( test->dst_def );

        if( src_pj == NULL )
        {
            printf( "Unable to translate:\n%s\n", test->src_def );
            test->skip = 1;
            continue;
        }

        if( dst_pj == NULL )
        {
            printf( "Unable to translate:\n%s\n", test->dst_def );
            test->skip = 1;
            continue;
        }
        
        test->dst_x = test->src_x;
        test->dst_y = test->src_y;
        test->dst_z = test->src_z;

        test->dst_error = pj_transform( src_pj, dst_pj, 1, 0, 
                                        &(test->dst_x), 
                                        &(test->dst_y),
                                        &(test->dst_z) );
     
        pj_free( src_pj );
        pj_free( dst_pj );

        test->skip = 0;

#ifdef notdef
        printf( "Test %d - output %.14g,%.14g,%g\n", i, test->dst_x, test->dst_y, test->dst_z );
#endif
    }

    printf( "%d tests initialized.\n", test_count );

/* -------------------------------------------------------------------- */
/*      Now launch a bunch of threads to repeat the tests.              */
/* -------------------------------------------------------------------- */
#ifdef _WIN32

	{ //Scoped to workaround lack of c99 support in VS
		HANDLE ahThread[num_threads];

		for( i = 0; i < num_threads; i++ )
		{
			active_thread_count++;

			ahThread[i] = CreateThread(NULL, 0, WinTestThread, NULL, 0, NULL);
			
			if (ahThread[i] == 0)
			{
				printf( "Thread creation failed.");
				return 1;
			}
		}

		printf( "%d test threads launched.\n", num_threads );

		WaitForMultipleObjects(num_threads, ahThread, TRUE, INFINITE);
	}

#else
    {
	pthread_t ahThread[num_threads];
	pthread_attr_t hThreadAttr;

	pthread_attr_init( &hThreadAttr );
	pthread_attr_setdetachstate( &hThreadAttr, PTHREAD_CREATE_DETACHED );

	for( i = 0; i < num_threads; i++ )
	{
		active_thread_count++;

		pthread_create( &(ahThread[i]), &hThreadAttr, 
			PosixTestThread, NULL );
	}

	printf( "%d test threads launched.\n", num_threads );

	while( active_thread_count > 0 )				       
		sleep( 1 );
    }
#endif

    printf( "all tests complete.\n" );

    return 0;
}
Ejemplo n.º 18
0
// XXX This whole function is full of multiple return statements!!!
// And probably shouldn't be a void
void QgsCoordinateTransform::initialise()
{
  // XXX Warning - multiple return paths in this block!!
  if ( !mSourceCRS.isValid() )
  {
    //mSourceCRS = defaultWkt;
    // Pass through with no projection since we have no idea what the layer
    // coordinates are and projecting them may not be appropriate
    mShortCircuit = true;
    QgsDebugMsg( "SourceCRS seemed invalid!" );
    return;
  }

  if ( !mDestCRS.isValid() )
  {
    //No destination projection is set so we set the default output projection to
    //be the same as input proj.
    mDestCRS = QgsCRSCache::instance()->crsByAuthId( mSourceCRS.authid() );
  }

  bool useDefaultDatumTransform = ( mSourceDatumTransform == - 1 && mDestinationDatumTransform == -1 );

  // init the projections (destination and source)

  pj_free( mSourceProjection );
  QString sourceProjString = mSourceCRS.toProj4();
  if ( !useDefaultDatumTransform )
  {
    sourceProjString = stripDatumTransform( sourceProjString );
  }
  if ( mSourceDatumTransform != -1 )
  {
    sourceProjString += ( " " + datumTransformString( mSourceDatumTransform ) );
  }
  mSourceProjection = pj_init_plus( sourceProjString.toUtf8() );

  pj_free( mDestinationProjection );
  QString destProjString = mDestCRS.toProj4();
  if ( !useDefaultDatumTransform )
  {
    destProjString = stripDatumTransform( destProjString );
  }
  if ( mDestinationDatumTransform != -1 )
  {
    destProjString += ( " " +  datumTransformString( mDestinationDatumTransform ) );
  }

  if ( !useDefaultDatumTransform )
  {
    addNullGridShifts( sourceProjString, destProjString );
  }

  mDestinationProjection = pj_init_plus( destProjString.toUtf8() );

#ifdef COORDINATE_TRANSFORM_VERBOSE
  QgsDebugMsg( "From proj : " + mSourceCRS.toProj4() );
  QgsDebugMsg( "To proj   : " + mDestCRS.toProj4() );
#endif

  mInitialisedFlag = true;
  if ( !mDestinationProjection )
  {
    mInitialisedFlag = false;
  }
  if ( !mSourceProjection )
  {
    mInitialisedFlag = false;
  }
#ifdef COORDINATE_TRANSFORM_VERBOSE
  if ( mInitialisedFlag )
  {
    QgsDebugMsg( "------------------------------------------------------------" );
    QgsDebugMsg( "The OGR Coordinate transformation for this layer was set to" );
    QgsLogger::debug<QgsCoordinateReferenceSystem>( "Input", mSourceCRS, __FILE__, __FUNCTION__, __LINE__ );
    QgsLogger::debug<QgsCoordinateReferenceSystem>( "Output", mDestCRS, __FILE__, __FUNCTION__, __LINE__ );
    QgsDebugMsg( "------------------------------------------------------------" );
  }
  else
  {
    QgsDebugMsg( "------------------------------------------------------------" );
    QgsDebugMsg( "The OGR Coordinate transformation FAILED TO INITIALISE!" );
    QgsDebugMsg( "------------------------------------------------------------" );
  }
#else
  if ( !mInitialisedFlag )
  {
    QgsDebugMsg( "Coordinate transformation failed to initialize!" );
  }
#endif

  //XXX todo overload == operator for QgsCoordinateReferenceSystem
  //at the moment srs.parameters contains the whole proj def...soon it wont...
  //if (mSourceCRS->toProj4() == mDestCRS->toProj4())
  if ( mSourceCRS == mDestCRS )
  {
    // If the source and destination projection are the same, set the short
    // circuit flag (no transform takes place)
    mShortCircuit = true;
    QgsDebugMsgLevel( "Source/Dest CRS equal, shortcircuit is set.", 3 );
  }
  else
  {
    // Transform must take place
    mShortCircuit = false;
    QgsDebugMsgLevel( "Source/Dest CRS UNequal, shortcircuit is NOt set.", 3 );
  }

}
Ejemplo n.º 19
0
static int raster_add_map(struct gpsnav *nav, struct gps_map *map,
			  struct gps_key_value *kv, int kv_count,
			  const char *base_path)
{
	struct raster_map *raster_map;
	struct raster_map_type *type;
	struct raster_data *data = map->prov->data;
	const char *bitmap_type, *tag;
	const char *datum_str, *proj_str;
	char *bitmap_filename;
	const struct gps_datum *datum;
	PJ *pj;
	int lon0, false_easting;
	int i, r;

	bitmap_filename = NULL;
	bitmap_type = tag = datum_str = proj_str = NULL;
	lon0 = false_easting = 0;
	for (i = 0; i < kv_count; i++, kv++) {
		if (strcmp(kv->key, "bitmap-filename") == 0)
			bitmap_filename = kv->value;
		else if (strcmp(kv->key, "bitmap-type") == 0)
			bitmap_type = kv->value;
		else if (strcmp(kv->key, "tag") == 0)
			tag = kv->value;
		else if (strcmp(kv->key, "datum") == 0)
			datum_str = kv->value;
		else if (strcmp(kv->key, "projection") == 0)
			proj_str = kv->value;
		else if (strcmp(kv->key, "central-meridian") == 0) {
			if (sscanf(kv->value, "%d", &lon0) != 1 ||
			    lon0 < -180 || lon0 > 180) {
				gps_error("Invalid central meridian value");
				return -1;
			}
		} else if (strcmp(kv->key, "false-easting") == 0) {
			if (sscanf(kv->value, "%d", &false_easting) != 1) {
				gps_error("Invalid false easting value");
				return -1;
			}
		}
	}

	if (bitmap_filename == NULL) {
		gps_error("Did not get bitmap filename");
		return -1;
	}

	bitmap_filename = gpsnav_get_full_path(bitmap_filename, base_path);
	if (bitmap_filename == NULL)
		return -1;

	r = -1;

	if (raster_check_for_dupe(nav, bitmap_filename) < 0) {
		r = -EEXIST;
		goto fail;
	}
	if (bitmap_type == NULL) {
		gps_error("Did not get bitmap type");
		goto fail;
	}

	if (tag == NULL || (type = raster_find_type(data, tag)) == NULL) {
		const struct gps_ellipsoid *ell;
		char buf[5][40], *projc[5];
		int c, i;

		if (datum_str == NULL) {
			gps_error("Datum not specified");
			goto fail;
		}
		datum = gpsnav_find_datum(nav, datum_str);
		if (datum == NULL) {
			gps_error("Unknown datum '%s'", datum_str);
			goto fail;
		}
		if (proj_str == NULL) {
			gps_error("Map projection not specified");
			goto fail;
		}
		ell = datum->ellipsoid;
		c = 0;
		sprintf(buf[c++], "proj=%s", proj_str);
		sprintf(buf[c++], "a=%f", ell->a);
		sprintf(buf[c++], "rf=%f", ell->invf);
		if (lon0)
			sprintf(buf[c++], "lon_0=%d", lon0);
		if (false_easting)
			sprintf(buf[c++], "x_0=%d", false_easting);
		for (i = 0; i < c; i++)
			projc[i] = buf[i];
		pj = pj_init(c, projc);
		if (pj == NULL) {
			gps_error("Invalid projection variables");
			goto fail;
		}
		type = malloc(sizeof(*type));
		if (type == NULL) {
			pj_free(pj);
			r = -ENOMEM;
			goto fail;
		}
		if (tag != NULL) {
			type->tag = strdup(tag);
			if (type->tag == NULL) {
				pj_free(pj);
				free(type);
				r = -ENOMEM;
				goto fail;
			}
		} else
			type->tag = NULL;
		type->proj_name = strdup(proj_str);
		if (type->proj_name == NULL) {
			pj_free(pj);
			free(type->tag);
			free(type);
			r = -ENOMEM;
			goto fail;
		}
		type->datum = datum;
		type->proj = pj;
		type->lon0 = lon0;
		type->false_easting = false_easting;
		raster_add_type(data, type);
	}

	raster_map = malloc(sizeof(*raster_map));
	if (raster_map == NULL) {
		r = -ENOMEM;
		goto fail;
	}
	if (strcmp(bitmap_type, raster_png_decoder.name) == 0)
		raster_map->dec = &raster_png_decoder;
	else if (strcmp(bitmap_type, raster_jpeg_decoder.name) == 0)
		raster_map->dec = &raster_jpeg_decoder;
	else if (strcmp(bitmap_type, raster_gif_decoder.name) == 0)
		raster_map->dec = &raster_gif_decoder;
	else {
		gps_error("Invalid raster bitmap type '%s'", bitmap_type);
		free(raster_map);
		goto fail;
	}

	raster_map->type = type;
	raster_map->bitmap_filename = bitmap_filename;

	map->datum = type->datum;
	map->proj = type->proj;
	map->data = raster_map;

	if (raster_map->dec->read_header(map) < 0) {
		raster_free_map(map);
		map->data = NULL;
		goto fail;
	}
	return 0;
fail:
	free(bitmap_filename);
	return r;
}
Ejemplo n.º 20
0
Archivo: map.c Proyecto: Exteris/Gerris
static void gfs_map_projection_destroy (GtsObject * object)
{
  if (GFS_MAP_PROJECTION (object)->pj)
    pj_free (GFS_MAP_PROJECTION (object)->pj);
  (* GTS_OBJECT_CLASS (gfs_map_projection_class ())->parent_class->destroy) (object);
}
Ejemplo n.º 21
0
Errcode pj_flic_play_until(char *path, FlicPlayOptions *requested_options,
						   UserEventFunc *event_detect, void *udata)
/*****************************************************************************
 * play a flic until the user-specified event routine returns FALSE to stop.
 *
 * Returns:
 *	Success if ended due to user's event detect routine.
 *	   1	if ended due to a keyhit and options.keyhit_stops_playback==TRUE.
 *	 (neg)	if ended due to error.
 ****************************************************************************/
{
	Errcode 		err;
	Boolean 		we_initialized_clock = FALSE;
	ULONG			clock;
	ULONG			num_frames;
	FlicRaster		virt_raster;
	FlicRaster		*root_raster = NULL;
	FlicRaster		*playback_raster = NULL;
	Fli_frame		*ff = NULL;
	Flic			theflic = {0};
	Flifile 		*flif;
	Fli_head		*flihdr;
	FliLibCtl		*libctl;

	UserEventData	event_data;
	FlicPlayOptions options;

	/*------------------------------------------------------------------------
	 * validate parms, init options, etc.
	 *----------------------------------------------------------------------*/

	if (NULL == path || NULL == event_detect)
		return pj_error_internal(Err_internal_pointer, modulename, __LINE__);

	if (NULL == requested_options) {
		pj_playoptions_init(&options);
	} else {
		options = *requested_options;
	}

	/*------------------------------------------------------------------------
	 * open the flic.
	 *----------------------------------------------------------------------*/

	err = pj_flic_open(path, &theflic);
	if (Success > err)
		goto ERROR_EXIT;

	flif   = theflic.flifile;
	flihdr = &flif->hdr;
	libctl = theflic.libctl;

	/*------------------------------------------------------------------------
	 * open the video raster, or use the caller-provided raster.
	 *----------------------------------------------------------------------*/

	if (NULL != options.playback_raster) {
		root_raster = (FlicRaster *)options.playback_raster;
	} else {
		root_raster = (FlicRaster *)GetPicScreen();
	}

	/*------------------------------------------------------------------------
	 * setup placement of the playback raster based on the caller-provided
	 * options, or the default option of centering the flic on the raster.
	 *----------------------------------------------------------------------*/

	if (0 == options.x && 0 == options.y) {
		playback_raster = pj_raster_center_virtual(root_raster, &virt_raster,
												 flihdr->width, flihdr->height);
	} else {
		playback_raster = pj_raster_clip_virtual(root_raster, &virt_raster,
							options.x, options.y, flihdr->width, flihdr->height);
		if (NULL == playback_raster) {
			err = Err_clipped;
			goto ERROR_EXIT;	/* totally clipped, just punt */
		}
	}

	pj_raster_clear(playback_raster);

	/*------------------------------------------------------------------------
	 * do some misc setup before starting the actual playback...
	 *----------------------------------------------------------------------*/

	if(Success > (err = pj_fli_alloc_cbuf(&ff,flihdr->width,flihdr->height,COLORS))) {
		goto ERROR_EXIT;
	}

	num_frames				= flihdr->frame_count;
	theflic.userdata		= udata;
	event_data.userdata 	= udata;
	event_data.flic 		= &theflic;
	event_data.cur_loop 	= 0;
	event_data.cur_frame	= 0;
	event_data.num_frames	= num_frames;

	if (options.speed < 0)
		options.speed = flihdr->speed;

	we_initialized_clock = !pj_clock_init();

	/*------------------------------------------------------------------------
	 * do the playback...
	 *----------------------------------------------------------------------*/

	for (;;) {

		/*--------------------------------------------------------------------
		 * the first time through, and if the event detector has called
		 * pj_flic_rewind(), libctl->cur_frame is zero, and we have to seek
		 * back to frame 1 (the brun frame).
		 *------------------------------------------------------------------*/

		if (0 == libctl->cur_frame)
			pj_seek(flif->fd, flihdr->frame1_oset, JSEEK_START);

		/*--------------------------------------------------------------------
		 * if the frame we're about to display is the ring frame, we increment
		 * the cur_loop counter, and set the cur_frame to zero.  that's
		 * because displaying the ring frame is really a fast way to display
		 * frame zero without un-brun'ing it again.
		 *------------------------------------------------------------------*/

		if (num_frames == libctl->cur_frame) {
			event_data.cur_frame = 0;
			++event_data.cur_loop;
		} else {
			event_data.cur_frame = libctl->cur_frame;
		}

		/*--------------------------------------------------------------------
		 * get the current clock now, so that the delta time between frames
		 * included the time it takes to render the frame.
		 * render the frame.
		 *------------------------------------------------------------------*/

		clock = options.speed + pj_clock_1000();
		if(Success > (err = pj_fli_read_uncomp(path,flif,(Rcel *)playback_raster,ff,TRUE)))
			goto ERROR_EXIT;

		/*--------------------------------------------------------------------
		 * call the event detector repeatedly, until it requests a stop, or
		 * it's time to display the next frame.  also check the keyboard
		 * after each event_detect() call, if the caller has asked for that.
		 *------------------------------------------------------------------*/

		do	{
			if (FALSE == event_detect(&event_data)) {
				err = Success;
				goto ERROR_EXIT;
			}
			if (options.keyhit_stops_playback) {
				if (pj_key_is()) {
					pj_key_in();
					err = 1;
					goto ERROR_EXIT;
				}
			}
		} while (clock >= pj_clock_1000());

		/*--------------------------------------------------------------------
		 * increment the frame counter; if it becomes greater than the frame
		 * count, that means we just displayed the ring frame and have to
		 * seek back to the second frame (not the first (brun'd) frame!).
		 *------------------------------------------------------------------*/

		if (++libctl->cur_frame > num_frames) {
			pj_seek(flif->fd, flihdr->frame2_oset, JSEEK_START);
			libctl->cur_frame = 1;
		}
	}

ERROR_EXIT:

	pj_flic_close(&theflic);

	if (NULL != ff)
		pj_free(ff);

	if (we_initialized_clock)
		pj_clock_cleanup();

	return err;
}