Exemple #1
0
geos::geom::MultiPolygon *WKBParser::_readMultiPolygon()
{
	int count = _is.readInt();
	std::vector<geos::geom::Geometry *> *geoms = new std::vector<geos::geom::Geometry *>(count);

	try {
		for (int i=0; i<count; i++)
		{
			geos::geom::Geometry *g = _readGeometry();
			if (!dynamic_cast<geos::geom::Polygon *>(g))
			{
				AMIGO_LOG_E(TAG, "::_readMultiPolygon() Invalid geometry type\n");
				_clean(geoms);
				return NULL;
			}
			(*geoms)[i] = g;
		}
	} catch (...) 
	{
		AMIGO_LOG_E(TAG, "::_readMultiPolygon() Read failed.\n");
		_clean(geoms);
		return NULL;
	}
	return _factory.createMultiPolygon(geoms);
}
Exemple #2
0
char* loadFile (const char *fname, int *size)
{
    AMIGO_LOG_I(TAG, "::loadFile() %s\n", fname);
	int fd=open(fname, O_RDONLY);
	if(fd<0)
		return NULL;

	char *buffer=NULL;
	*size=0;
	off_t fsize = lseek(fd, 0, SEEK_END);

    AMIGO_LOG_I(TAG, "::loadFile() fd=%d, size=%d\n", fd, fsize);
	if(fsize>0)
	{
		buffer = new char[ fsize ];
		lseek(fd, 0, SEEK_SET);
		int n = read(fd, buffer, fsize);
		if(n != fsize)
		{
		    AMIGO_LOG_E(TAG, "::loadFile() %d != %d\n", n, fsize);
			delete [] buffer;
			return NULL;
		}
		*size = fsize;
	}
	else
	{
	    AMIGO_LOG_E(TAG, "::loadFile() FAILED\n");
	}
	return buffer;
}
Exemple #3
0
bool loadJSON(const std::string &url, std::string &response, bool useCache, bool neededForOffline)
{
	if(url.size()==0)
	{
        AMIGO_LOG_E(TAG, "::loadJSON(): Failed, URL is empty. \n");
		return false;
	}

	AmigoRest client("core/AmigoCore", useCache);
	client.enableCacheWrite(useCache || neededForOffline);
	RestClient::response resp = client.get(url);
	if(!resp.isBad())
	{
		response = resp.body;
		return true;
	} else if(!useCache && neededForOffline)
	{
		client.enableCacheRead(true);
		resp = client.get(url);
		if(!resp.isBad())
		{
			response = resp.body;
			return true;
		}
	}
	AMIGO_LOG_E(TAG, "::loadJSON(): Failed URL: '%s'\n", url.c_str());
	return false;
}
Exemple #4
0
geos::geom::GeometryCollection *WKBParser::_readGeometryCollection()
{
	int count = _is.readInt();
	std::vector<geos::geom::Geometry *> *geoms = new std::vector<geos::geom::Geometry *>(count);

	try {
		for (int i=0; i<count; i++)
		{
			geos::geom::Geometry *g = _readGeometry();
			if(g)
			{
				(*geoms)[i] = g;
			} else
			{
				AMIGO_LOG_E(TAG, "::_readGeometryCollection() Read failed.\n");
				_clean(geoms);
				return NULL;				
			}
		}
	} catch (...) 
	{
		_clean(geoms);
		return NULL;
	}
	return _factory.createGeometryCollection(geoms);
}
Exemple #5
0
geos::geom::Polygon *WKBParser::_readPolygon()
{
	int count = _is.readInt();

    geos::geom::LinearRing *rind = NULL;
	std::vector<geos::geom::Geometry *> *holes=NULL;
	if ( count > 0 )
	{
		try {
		    if( count > 0 )
		    {
                rind = _readLinearRing();
		    }
			holes = new std::vector<geos::geom::Geometry *>(count-1);
			for (int i=0; i<count-1; i++)
			{
			    geos::geom::Geometry *g = (geos::geom::Geometry *)_readLinearRing();
				(*holes)[i] = g;
            }
		} catch (...) 
		{
		    if(holes)
		    {
				_clean(holes);
			}
            if(rind)
            {
			    delete rind;
            }
			AMIGO_LOG_E(TAG, "::_readPolygon() Read failed.\n");
            return NULL;
		}
	}
	return _factory.createPolygon(rind, holes);
}
Exemple #6
0
int getPixelSpan(int mode)
{
 	int pixelSpan;
	switch(mode)
	{
        case ImageUtils::JPEG:
        case ImageUtils::RGB:
            pixelSpan = 3;
            break;
            
        case ImageUtils::RGBA:
            pixelSpan = 4;
            break;
            
        case ImageUtils::GRAY_8:
            pixelSpan = 1;
            break;
            
        case ImageUtils::GRAY_16:
            pixelSpan = 2;
            break;
            
        default:
            AMIGO_LOG_E(TAG, "::getPixelSpan() Error: mode=%d\n", mode);
            pixelSpan = 4;
            break;
	}
    return pixelSpan;
}
Exemple #7
0
std::shared_ptr<std::string> fCache::get(const std::string &key)
{
	std::stringstream sql;
	DatabaseResult result;
	sql << "SELECT data FROM " << TABLE_NAME << " WHERE id='" << key << "';";
    _db.executeSQL(sql.str().c_str(), result);
    if(result.isOK())
    {
    	///////////////////////////////////////////////////////////////////////////
    	// Update timestamp
    	sql.str("");
    	sql <<  "UPDATE " << TABLE_NAME << " SET timestamp=" << Timestamp::unixTime() << " WHERE id='" << key << "';";
    	_db.executeSQL(sql.str().c_str());
    	///////////////////////////////////////////////////////////////////////////

    	if(result.records.size()==1 && result.records[0].size() == 1)
    	{
            auto readBuffer = std::make_shared<std::string>(std::move(result.records.at(0).at(0)));
            if(!readBuffer->empty())
            {
                return readBuffer;
            }
    	}
    } else
    {
        AMIGO_LOG_E(TAG, "::get() sql failed: '%s'\n", sql.str().c_str());
    }

    return nullptr;
}
Exemple #8
0
geos::geom::Geometry *WKBParser::_readGeometry()
{
	unsigned char byteOrdr = _is.readByte();
    if (byteOrdr == WKB_BIG_ENDIAN)
        _is.doSwap();

	int typeInt = _is.readInt();
	int geomType = typeInt & 0xff;

	bool zPresent = ((typeInt & 0x80000000) != 0);
	if (zPresent) _dimension = 3;
	else _dimension = 2; // TODO: handle M values

	int srid = 0;
	bool sridPresent = ((typeInt & 0x20000000) != 0);
	if (sridPresent) srid = _is.readInt(); 

	if ( _ordinates.size() < _dimension )
		_ordinates.resize(_dimension);

	geos::geom::Geometry *geom=NULL;

	switch (geomType) {
		case Point_Type :
			geom = _readPoint();
		break;
		
		case MultiPoint_Type :
			geom = _readMultiPoint();
		break;
		
		case LineString_Type :
			geom = _readLineString();
		break;
		
		case MultiLineString_Type :
			geom = _readMultiLineString();
		break;
		
		case Polygon_Type :
			geom = _readPolygon();
		break;
		
		case MultiPolygon_Type :
			geom = _readMultiPolygon();
		break;
		
		case GeometryCollection_Type :
			geom = _readGeometryCollection();
		break;
		
		default:
			AMIGO_LOG_E(TAG, "::_readGeometry() Unknown WKB type (%d)\n", geomType);
			return NULL;
	}
	if(geom) geom->setSRID(srid);
	return geom;
}
GLuint BitmapHandler::loadTextureFile(const std::string &fileName, int &width, int &height, int mode, bool useCache)
{
	GLuint texId;
    width = 0;
    height = 0;
	texId = _findTexture(fileName, width, height);
	if(texId != 0 && useCache)
	{
		return texId;
	}

    bool useMipmap;
    switch(mode)
    {
        case TEX_MODE_DEFAULT:
            useMipmap=globeConfig::instance()->isUseMipMapTxt();
            break;
        case TEX_MODE_MIPMAP:
            useMipmap=true;
            break;
        case TEX_MODE_NOMIPMAP:
            useMipmap=false;
            break;
    }

	char *buffer = findBmpFile(fileName, width, height, ImageUtils::RGBA, useCache);

	if ( buffer == NULL )
	{
		AMIGO_LOG_E(TAG, "::loadTextureFile() Error loading (%s) image.\n", fileName.c_str());
		return 0;
	}

	glGenTextures ( 1, &texId );
	glBindTexture ( GL_TEXTURE_2D, texId );

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer );

	addTexture(fileName, texId, width, height);

	delete [] buffer;
	return texId;
}
Exemple #10
0
bool loadJSON(const std::string &url, Document &document, bool useCache, bool neededForOffline)
{
	if(url.size()==0)
	{
        AMIGO_LOG_I(TAG, "::loadJSON(): Failed, URL is empty. \n");
		return false;	
	}
	
	AmigoRest client("core/AmigoCore", useCache);
	client.enableCacheWrite(useCache || neededForOffline);
	RestClient::response resp = client.get(url);
	if(!resp.isBad())
	{
		if (document.Parse<0>(resp.body.c_str()).HasParseError())
		{
			AMIGO_LOG_E(TAG, "::loadJSON(): Failed to parse: URL: '%s', JSON: '%s'\n", url.c_str(), resp.body.c_str());
			return false;
		}
		return true;
	} else if(!useCache && neededForOffline)
	{
		client.enableCacheRead(true);
		resp = client.get(url);
		if(!resp.isBad())
		{
			if (document.Parse<0>(resp.body.c_str()).HasParseError())
			{
				AMIGO_LOG_E(TAG, "::loadJSON(): Failed to parse: URL: '%s', JSON: '%s'\n", url.c_str(), resp.body.c_str());
				return false;
			}
			return true;
		}
	}
	AMIGO_LOG_E(TAG, "::loadJSON(): Failed URL: '%s'\n", url.c_str());
	return false;

}
Exemple #11
0
bool getJSONBool(const Value &v, const std::string &name, bool def)
{
    if(v.HasMember(name.c_str()))
    {
        if(v[name.c_str()].GetType() == kFalseType || v[name.c_str()].GetType() == kTrueType)
        {
            return v[name.c_str()].GetBool();
        }
        else
        {
            AMIGO_LOG_E(TAG, "::getJSONBool(): Failed to parse: '%s'\n", name.c_str());
        }
    }
    return def;
};
Exemple #12
0
double getJSONDouble(const Value &v, const std::string &name, double def)
{
    if(v.HasMember(name.c_str()))
    {
        if(v[name.c_str()].IsDouble())
        {
            return v[name.c_str()].GetDouble();
        }
        else
        {
            AMIGO_LOG_E(TAG, "::getJSONDouble(): Failed to parse: '%s'\n", name.c_str());
        }
    }
    return def;
}
Exemple #13
0
int getJSONInt(const Value &v, const std::string &name, int def)
{
    if(v.HasMember(name.c_str()))
    {
        if(v[name.c_str()].IsInt())
        {
            return v[name.c_str()].GetInt();
        }
        else
        {
            AMIGO_LOG_E(TAG, "::getJSONInt(): Failed to parse: '%s'\n", name.c_str());
        }
    }
    return def;
};
Exemple #14
0
int getJSONInt(const Document &document, const std::string &name, int def)
{
    if(document.HasMember(name.c_str()))
    {
        if(document[name.c_str()].IsInt())
        {
            return document[name.c_str()].GetInt();
        }
        else
        {
            AMIGO_LOG_E(TAG, "::getJSONInt(): Failed to parse: '%s'\n", name.c_str());
        }
    }
    return def;
};
Exemple #15
0
std::string getJSONString(const Value &v, const std::string &name, const std::string &def)
{
     if(v.HasMember(name.c_str())) {
         if(v[name.c_str()].GetType() == kStringType)
         {
             const char * str = v[name.c_str()].GetString();
             if(str!=NULL)
             {
                 if (strnlen(str, 2) > 0) {
                     std::string ret = std::string(str);
                     return ret;
                 }
             } else
             {
                 AMIGO_LOG_E(TAG, "::getJSONString(): Failed to parse: '%s'\n", name.c_str());
             }
         }
    }
    return def;
};
Exemple #16
0
char* load_JPEG_FromURL (const char *url, int *width, int *height, bool useCache )
{

//	AmigoCloud::CurlHandler ch;
//	if( !ch.doRequest(url) )
//	 return 0;

	AmigoRest restClient(imageUtilsUserAgent.c_str(), useCache);
	//restClient.setIgnoreSSLCertificate(true); // because of certficate problems.
	RestClient::response response = restClient.get(url);
    if (response.isBad())
    	return 0;

  /* This struct contains the JPEG decompression parameters and pointers to
   * working space (which is allocated as needed by the JPEG library).
   */
  struct jpeg_decompress_struct cinfo;
  /* We use our private extension JPEG error handler.
   * Note that this struct must live as long as the main JPEG parameter
   * struct, to avoid dangling-pointer problems.
   */
  struct my_error_mgr jerr;
  /* More stuff */
//  FILE * infile;		/* source file */
  JSAMPARRAY buffer;		/* Output row buffer */
  int row_stride;		/* physical row width in output buffer */

  /* In this example we want to open the input file before doing anything else,
   * so that the setjmp() error recovery below can assume the file is open.
   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
   * requires it in order to read binary files.
   */

//  if ((infile = fopen(filename, "rb")) == NULL) {
//    fprintf(stderr, "can't open %s\n", filename);
//    return 0;
//  }

  /* Step 1: allocate and initialize JPEG decompression object */

  /* We set up the normal JPEG error routines, then override error_exit. */
  cinfo.err = jpeg_std_error(&jerr.pub);
  jerr.pub.error_exit = my_error_exit;
  /* Establish the setjmp return context for my_error_exit to use. */
  if (setjmp(jerr.setjmp_buffer)) {
    /* If we get here, the JPEG code has signaled an error.
     * We need to clean up the JPEG object, close the input file, and return.
     */
    jpeg_destroy_decompress(&cinfo);
//    fclose(infile);
    return NULL;
  }
  /* Now we can initialize the JPEG decompression object. */
  jpeg_create_decompress(&cinfo);

  /* Step 2: specify data source (eg, a file) */

  FILE * infile = fmemopen((void*)response.body.c_str(), response.body.size(), "rb");
  if (infile == NULL)
  {
      AMIGO_LOG_E(TAG, "Calling fmemopen() has failed.\n");
//      exit(1);
      return NULL;
  }

  jpeg_stdio_src(&cinfo, infile);

  /* Step 3: read file parameters with jpeg_read_header() */

  (void) jpeg_read_header(&cinfo, TRUE);
  /* We can ignore the return value from jpeg_read_header since
   *   (a) suspension is not possible with the stdio data source, and
   *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
   * See libjpeg.doc for more info.
   */

  /* Step 4: set parameters for decompression */

  /* In this example, we don't need to change any of the defaults set by
   * jpeg_read_header(), so we do nothing here.
   */

  /* Step 5: Start decompressor */

  (void) jpeg_start_decompress(&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* We may need to do some setup of our own at this point before reading
   * the data.  After jpeg_start_decompress() we have the correct scaled
   * output image dimensions available, as well as the output colormap
   * if we asked for color quantization.
   * In this example, we need to make an output work buffer of the right size.
   */

   *width = cinfo.output_width;
   *height = cinfo.output_height;
   int numcomp = 4;//cinfo.num_components;

   row_stride = cinfo.output_width * numcomp;//cinfo.output_components;

   char *buff = new char[ *width * *height * numcomp ];

//   printf("load_JPEG_FromURL() %dx%d, %d, buff=%p\n", *width, *height, numcomp, buff);

  /* JSAMPLEs per row in output buffer */

//  char *buffS = new char[ row_stride ];

  /* Step 6: while (scan lines remain to be read) */
  /*           jpeg_read_scanlines(...); */

  /* Here we use the library's state variable cinfo.output_scanline as the
   * loop counter, so that we don't have to keep track ourselves.
   */

  /* Make a one-row-high sample array that will go away when done with image */
  buffer = (*cinfo.mem->alloc_sarray)
				((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);

  while (cinfo.output_scanline < cinfo.output_height) {
	  /* jpeg_read_scanlines expects an array of pointers to scanlines.
	   * Here the array is only one element long, but you could ask for
	   * more than one scanline at a time if that's more convenient.
	   */
	  (void) jpeg_read_scanlines(&cinfo, buffer, 1);
	  /* Assume put_scanline_someplace wants a pointer and sample count. */

	  int index = (cinfo.output_scanline-1) * row_stride;
	  // Convert RGB to RGBA
	  int cb=0;
	  char *bb = (char*)buffer[0];
	  for(int i=0; i<row_stride; i+=4 )
	  {

		  buff[index + i]   = bb[cb]; cb++;
		  buff[index + i+1] = bb[cb]; cb++;
		  buff[index + i+2] = bb[cb]; cb++;
		  buff[index + i+3] = 255;
	  }
//	  memcpy((void*)&buff[(cinfo.output_scanline-1) * row_stride], buffS, row_stride);
  }

//  delete [] buffS;
  /* Step 7: Finish decompression */

  (void) jpeg_finish_decompress(&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* Step 8: Release JPEG decompression object */

  /* This is an important step since it will release a good deal of memory. */
  jpeg_destroy_decompress(&cinfo);

  /* After finish_decompress, we can close the input file.
   * Here we postpone it until after no more JPEG errors are possible,
   * so as to simplify the setjmp error logic above.  (Actually, I don't
   * think that jpeg_destroy can do an error exit, but why assume anything...)
   */
  fclose(infile);

  /* At this point you may want to check to see whether any corrupt-data
   * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
   */
//  printf("load_JPEG_FromURL() done.\n");

  /* And we're done! */
  return buff;
}
Exemple #17
0
iiMath::vec4f StyleData::_parseColor(const std::string &hex, bool &valid)
{
    iiMath::vec4f v;
    if(hex.size()<1)
    {
        AMIGO_LOG_I(TAG, "::_parse_color() Error: color is not valid\n");
        valid = false;
        return v;
    }
    
    int value = 0;
    int a = 0;
    int b = hex.length() - 1;
    int index=0;
    for (; b > 0; a++, b--)
    {
        if (hex[b] >= '0' && hex[b] <= '9')
        {
            value += (hex[b] - '0') * (1 << (a * 4));
        }
        else
        {
            switch (hex[b])
            {
                case 'A':
                case 'a':
                    value += 10 * (1 << (a * 4));
                    break;
                    
                case 'B':
                case 'b':
                    value += 11 * (1 << (a * 4));
                    break;
                    
                case 'C':
                case 'c':
                    value += 12 * (1 << (a * 4));
                    break;
                    
                case 'D':
                case 'd':
                    value += 13 * (1 << (a * 4));
                    break;
                    
                case 'E':
                case 'e':
                    value += 14 * (1 << (a * 4));
                    break;
                    
                case 'F':
                case 'f':
                    value += 15 * (1 << (a * 4));
                    break;
                    
                default:
                    AMIGO_LOG_E(TAG, "::_parseColor() '%s' Error, invalid charactare '%d' in hex number\n", hex.c_str(), hex[a]);
                    return v;
            }
        }
    }
    valid = true;
    int vv= value;
    v.v[0] = (0x000000ff&(vv>>16)) / 255.0;
    vv= value;
    v.v[1] = (0x000000ff&(vv>>8)) / 255.0;
    vv= value;
    v.v[2] = (0x000000ff&(vv)) / 255.0;
    v.v[3] = 1;
    return v;
}
void VectorLayerEditor::_init()
{
    if(_inited)
        return;

    // Load geometry
    AmigoApplicationData &appData = AmigoApplication::instance().getData();
    if(auto project = appData.getUser().projects.findProject(_editorParams.projectId))
    {
        std::vector<std::string> wkbOut;
        std::shared_ptr<APIv1::Dataset> ds = std::dynamic_pointer_cast<APIv1::Dataset>(project->datasets.findDataset(_editorParams.datasetId));
        if(ds)
        {
            if(_editorParams.savedWkb.empty())
            {
                project->db.geoQueryWKB(ds->table_name, _editorParams.jsonRecord, wkbOut, ds->online_only);
                AMIGO_LOG_I(TAG, "::_init() wkbOut.size()=%d\n", wkbOut.size());
            }
            else
            {
                AMIGO_LOG_I(TAG, "::_init() restore '%s'\n", _editorParams.savedWkb.c_str());
                _geometry = GeometryHandler::parseWKBHex(_editorParams.savedWkb);
            }

            if(_geometry == NULL)
            {
                if(wkbOut.size()==1 && wkbOut[0].size()>0)
                {
                    AMIGO_LOG_I(TAG, "::_init() '%s'\n", wkbOut[0].c_str());
                    _geometry = GeometryHandler::parseWKBHex(wkbOut[0]);
                } else {
                    // There is no geometry
                    _createEmptyGeometry();
                }
            }

            if(_geometry!=NULL)
            {
                GeometryTypeId gtype = _geometry->getGeometryTypeId();
                int type;
                switch (gtype) {
                case GEOS_POINT:
                    type = ShapeEditor::T_POINT;
                    break;

                case GEOS_LINESTRING:
                    type = ShapeEditor::T_LINE;
                    break;

                case GEOS_LINEARRING:
                    type = ShapeEditor::T_LINE;
                    break;

                case GEOS_POLYGON:
                    type = ShapeEditor::T_POLYGON;
                    break;

                case GEOS_MULTIPOINT:
                    type = ShapeEditor::T_POINTS;
                    break;

                case GEOS_MULTILINESTRING:
                    type = ShapeEditor::T_LINES;
                    break;

                case GEOS_MULTIPOLYGON:
                    type = ShapeEditor::T_POLYGONS;
                    break;

                case GEOS_GEOMETRYCOLLECTION:
                    type = ShapeEditor::T_POINTS;
                    break;

                default:
                    type = ShapeEditor::T_POINTS;
                    break;
                };
                AMIGO_LOG_I(TAG, "::_init() type=%d, gtype=%d\n", type, gtype);
                _coords.clear();
                for(size_t g = 0; g < _geometry->getNumGeometries(); g++)
                {
                    PointList pList;
                    CoordinateSequence *cs = _geometry->getGeometryN(g)->getCoordinates();
                    // Remove closing point in polygons
                    unsigned size = cs->getSize() - ((type == ShapeEditor::T_POLYGONS || type == ShapeEditor::T_POLYGON)? 1 : 0);
                    for(unsigned i=0; i < size; i++ )
                    {
                        Coordinate c;
                        cs->getAt(i, c);
                        double alt = Globe::instance()->getGlobeSceneHandler()->getElevationAt( c.y, c.x);
                        pList.push_back( iiMath::vec3(c.y, c.x, alt) );
                    }
                    _coords.push_back(pList);
                    delete cs;
                }
                _shapeEditor.load(type, _coords);
            }
        }
        else
        {
            AMIGO_LOG_E(TAG, "::_init() dataset not found: %lu\n", _editorParams.datasetId);
        }
    } else
    {
        AMIGO_LOG_E(TAG, "::_init() project not found: %lu\n", _editorParams.projectId);

    }
    _shapeEditor.setState(GeometryEditorListener::NO_SELECTION);

    _labelStateSet = std::make_shared<LabelVectorStateSet>(false);
    _labelDrawSet = std::make_shared<DrawSetT>();
    _labelDrawSet->setStateSet(_labelStateSet);

    _inited=true;
}