<commit_before>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sys/stat.h>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include <gdal_priv.h>
#include <cpl_conv.h>
#include <ogr_spatialref.h>
using namespace std;
//to compile:  c++ raster_math.cpp -o raster_math -lgdal
// ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt

int main(int argc, char* argv[])
{
//passing arguments
if (argc != 2){cout << "Use <program name> <tile_id>" << endl; return 1;}

string tile_id = argv[1];

// carbon pools
string bgc_name = tile_id + "_bgc.tif";
string agc_name = tile_id + "_carbon.tif";
string deadc_name = tile_id + "_deadwood.tif";
string soilc_name = tile_id + "_soil.tif";
string litterc_name = tile_id + "_litter.tif";

// aux data
string lossyear_name = tile_id + "_loss.tif";
string lossclass_name = tile_id + "_res_forest_model.tif";
string peatdran_name = tile_id + "_res_peatdrainage.tif";
string hist_name = tile_id + "_res_hwsd_histosoles.tif";
string climate_name = tile_id + "_res_climate_zone.tif";
string ecozone_name = tile_id + "_res_fao_ecozones_bor_tem_tro.tif";

// set output file name
string out_wildfire_name = tile_id + "_wildfire.tif";
string out_forestry_name = tile_id + "_forestry.tif";
string out_conversion_name = tile_id + "_conversion.tif";
//setting variables
int x, y;
int xsize, ysize;
double GeoTransform[6]; double ulx, uly; double pixelsize;

//initialize GDAL for reading
GDALAllRegister();
GDALDataset  *INGDAL; GDALRasterBand  *INBAND;
GDALDataset  *INGDAL2; GDALRasterBand  *INBAND2;
GDALDataset  *INGDAL3; GDALRasterBand  *INBAND3;
GDALDataset  *INGDAL4; GDALRasterBand  *INBAND4;
GDALDataset  *INGDAL5; GDALRasterBand  *INBAND5;
GDALDataset  *INGDAL6; GDALRasterBand  *INBAND6; //loss
GDALDataset  *INGDAL7; GDALRasterBand  *INBAND7; //  lossclass
GDALDataset  *INGDAL8; GDALRasterBand  *INBAND8; // peatdran
GDALDataset  *INGDAL9; GDALRasterBand  *INBAND9; // histosoles
GDALDataset  *INGDAL10; GDALRasterBand  *INBAND10; // climate
GDALDataset  *INGDAL11; GDALRasterBand  *INBAND11; // eco zone

//open file and get extent and projection
INGDAL = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly );
INBAND = INGDAL->GetRasterBand(1);
xsize=INBAND->GetXSize();
ysize=INBAND->GetYSize();
INGDAL->GetGeoTransform(GeoTransform);
ulx=GeoTransform[0];
uly=GeoTransform[3];
pixelsize=GeoTransform[1];
cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl;

INGDAL2 = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly );
INBAND2 = INGDAL2->GetRasterBand(1);

INGDAL3 = (GDALDataset *) GDALOpen(deadc_name.c_str(), GA_ReadOnly );
INBAND3 = INGDAL3->GetRasterBand(1);

INGDAL4 = (GDALDataset *) GDALOpen(litterc_name.c_str(), GA_ReadOnly );
INBAND4 = INGDAL4->GetRasterBand(1);

INGDAL5 = (GDALDataset *) GDALOpen(soilc_name.c_str(), GA_ReadOnly );
INBAND5 = INGDAL5->GetRasterBand(1);

INGDAL6 = (GDALDataset *) GDALOpen(lossyear_name.c_str(), GA_ReadOnly );
INBAND6 = INGDAL6->GetRasterBand(1);

INGDAL7 = (GDALDataset *) GDALOpen(lossclass_name.c_str(), GA_ReadOnly );
INBAND7 = INGDAL7->GetRasterBand(1);

INGDAL8 = (GDALDataset *) GDALOpen(peatdran_name.c_str(), GA_ReadOnly );
INBAND8 = INGDAL8->GetRasterBand(1);

INGDAL9 = (GDALDataset *) GDALOpen(hist_name.c_str(), GA_ReadOnly );
INBAND9 = INGDAL9->GetRasterBand(1);

INGDAL10 = (GDALDataset *) GDALOpen(climate_name.c_str(), GA_ReadOnly );
INBAND10 = INGDAL10->GetRasterBand(1);

INGDAL11 = (GDALDataset *) GDALOpen(ecozone_name.c_str(), GA_ReadOnly );
INBAND11 = INGDAL11->GetRasterBand(1);

//initialize GDAL for writing
GDALDriver *OUTDRIVER;
GDALDataset *OUTGDAL;
GDALDataset *OUTGDAL2;
GDALDataset *OUTGDAL3;

GDALRasterBand *OUTBAND1;
GDALRasterBand *OUTBAND2;
GDALRasterBand *OUTBAND3;

OGRSpatialReference oSRS;
char *OUTPRJ = NULL;
char **papszOptions = NULL;
papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" );
OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF");
if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );};
oSRS.SetWellKnownGeogCS( "WGS84" );
oSRS.exportToWkt( &OUTPRJ );
double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize };

OUTGDAL = OUTDRIVER->Create( out_wildfire_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions );
OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ);
OUTBAND1 = OUTGDAL->GetRasterBand(1);
OUTBAND1->SetNoDataValue(-9999);

OUTGDAL2 = OUTDRIVER->Create( out_forestry_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions );
OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL2->SetProjection(OUTPRJ);
OUTBAND2 = OUTGDAL2->GetRasterBand(1);
OUTBAND2->SetNoDataValue(-9999);

OUTGDAL3 = OUTDRIVER->Create( out_conversion_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions );
OUTGDAL3->SetGeoTransform(adfGeoTransform); OUTGDAL3->SetProjection(OUTPRJ);
OUTBAND3 = OUTGDAL3->GetRasterBand(1);
OUTBAND3->SetNoDataValue(-9999);

//read/write data
float bgc_data[xsize];
float agc_data[xsize];
float deadc_data[xsize];
float litterc_data[xsize];
float soilc_data[xsize];
float loss_data[xsize];
float lossclass_data[xsize];
float peatdran_data[xsize];
float hist_data[xsize];
float climate_data[xsize];
float ecozone_data[xsize];

float out_wildfire_data[xsize];
float out_forestry_data[xsize];
float out_conversion_data[xsize];

for(y=0; y<4; y++)
{
INBAND->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, deadc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, litterc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, soilc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND6->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0);
INBAND7->RasterIO(GF_Read, 0, y, xsize, 1, lossclass_data, xsize, 1, GDT_Float32, 0, 0);
INBAND8->RasterIO(GF_Read, 0, y, xsize, 1, peatdran_data, xsize, 1, GDT_Float32, 0, 0);
INBAND9->RasterIO(GF_Read, 0, y, xsize, 1, hist_data, xsize, 1, GDT_Float32, 0, 0);
INBAND10->RasterIO(GF_Read, 0, y, xsize, 1, climate_data, xsize, 1, GDT_Float32, 0, 0);
INBAND11->RasterIO(GF_Read, 0, y, xsize, 1, ecozone_data, xsize, 1, GDT_Float32, 0, 0);

for(x=0; x<xsize; x++)
{
	if (loss_data[x] > 0)
	{
		if (lossclass_data[x] = 1) // forestry
		{
			if (peatdran_data[x] != 0) // on peat
			{
				if (peatdran_data[x] != 0) // change to burned areas once I get the data
				{
					cout << "on peat drainage: ";
					out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peatdran_data[x]) + 917; // qc'd this with 10N_100E - passed
					cout << out_forestry_data[x] << "\n";
				}
				else
				{
					out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peatdran_data[x]);
				}

			}
			else
			{
				if (hist_data[x] != 0) // on histosoles
				{
					if (ecozone_data[x] = 1) // tropics
					{
						out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 55);
					}
					if (ecozone_data[x] = 2) // boreal
					{
						out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 2.16);
					}
					if (ecozone_data[x] = 3) // temperate
					{
						out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 6.27);
					}

				}

				else // not on peat, not on histosoles
				{
					out_forestry_data[x] = -9999;

				}
			}
		}
		if (lossclass_data[x] = 2) // conversion
		{
			if (peatdran_data[x] != 0) // on peat
			{
				if (peatdran_data[x] != 0) // change to burned areas once I get the data
				{
					out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (15 - loss_data[x] * peatdran_data[x]) + 917;
				}
				else // not on burned areas
				{
					out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (15 - loss_data[x] * peatdran_data[x]);
				}
			}
			else // not on peat
			{
				if (hist_data[x] != 0) // on histosoles
				{
					if ((ecozone_data[x] = 2) || (ecozone_data[x] = 3)) // boreal or temperate
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + 29;
					}
					if (ecozone_data[x] = 1) // tropics
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + 55;
					}
				}
				else // not on histosoles
				{
					if ((climate_data[x] = 2) || (climate_data[x] = 4) || (climate_data[x] = 8)) // warm/cool temperate/boreal dry
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.8)) * 3.67;
					}
					if ((climate_data[x] = 1) || (climate_data[x] = 3) || (climate_data[x] = 7)) // warm/cool temperate/boreal moist
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.69)) * 3.67;
					}
					if (climate_data[x] = 12) // tropical dry
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.58)) * 3.67;
					}
					if ((climate_data[x] = 10) || (climate_data[x] = 11)) // tropical moist/wet
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.48)) * 3.67;
					}
					if (climate_data[x] = 9) // tropical montane
					{
						out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.64)) * 3.67;
					}
				}
			}
		}
	}
	else
	{
	out_forestry_data[x] = -9999;
	}

//closes for x loop
}
OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_forestry_data, xsize, 1, GDT_Float32, 0, 0 );
OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_wildfire_data, xsize, 1, GDT_Float32, 0, 0 );
OUTBAND3->RasterIO( GF_Write, 0, y, xsize, 1, out_conversion_data, xsize, 1, GDT_Float32, 0, 0 );

//closes for y loop
}

//close GDAL
GDALClose(INGDAL);
GDALClose((GDALDatasetH)OUTGDAL);

return 0;
}
<commit_msg>success in testing if forest class = 1 but with some dummy data for peat<commit_after>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sys/stat.h>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include <gdal/gdal_priv.h>
#include <gdal/cpl_conv.h>
#include <gdal/ogr_spatialref.h>
using namespace std;
//to compile:  c++ raster_math.cpp -o raster_math -lgdal
// ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt

int main(int argc, char* argv[])
{
//passing arguments
if (argc != 2){cout << "Use <program name> <tile id>" << endl; return 1;}
string agb_name=argv[1];

string tile_id = argv[1];
string forestmodel_name = tile_id + "_res_forest_model.tif";
string bgc_name = tile_id + "_bgc.tif";
string agc_name = tile_id + "_carbon.tif";
string loss_name = tile_id + "_loss.tif";
string peat_name = tile_id + "_res_peatdrainage.tif";

//either parse this var from inputs or send it in
string out_name1="test1.tif";
string out_name2 = "test2.tif";

//setting variables
int x, y;
int xsize, ysize;
double GeoTransform[6]; double ulx, uly; double pixelsize;

//initialize GDAL for reading
GDALAllRegister();
GDALDataset  *INGDAL; GDALRasterBand  *INBAND;
GDALDataset  *INGDAL2; GDALRasterBand  *INBAND2;
GDALDataset  *INGDAL3; GDALRasterBand  *INBAND3;
GDALDataset  *INGDAL4; GDALRasterBand  *INBAND4;
GDALDataset  *INGDAL5; GDALRasterBand  *INBAND5;

//open file and get extent and projection
INGDAL = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly );
INBAND = INGDAL->GetRasterBand(1);

INGDAL2 = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly );
INBAND2 = INGDAL2->GetRasterBand(1);

INGDAL3 = (GDALDataset *) GDALOpen(forestmodel_name.c_str(), GA_ReadOnly );
INBAND3 = INGDAL3->GetRasterBand(1);

INGDAL4 = (GDALDataset *) GDALOpen(loss_name.c_str(), GA_ReadOnly );
INBAND4 = INGDAL4->GetRasterBand(1);

INGDAL5 = (GDALDataset *) GDALOpen(peat_name.c_str(), GA_ReadOnly );
INBAND5 = INGDAL5->GetRasterBand(1);

xsize=INBAND->GetXSize();
ysize=INBAND->GetYSize();
INGDAL->GetGeoTransform(GeoTransform);

ulx=GeoTransform[0];
uly=GeoTransform[3];
pixelsize=GeoTransform[1];
cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl;

//initialize GDAL for writing
GDALDriver *OUTDRIVER;
GDALDataset *OUTGDAL;
GDALDataset *OUTGDAL2;
GDALRasterBand *OUTBAND1;
GDALRasterBand *OUTBAND2;
OGRSpatialReference oSRS;
char *OUTPRJ = NULL;
char **papszOptions = NULL;
papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" );
OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF");
if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );};
oSRS.SetWellKnownGeogCS( "WGS84" );
oSRS.exportToWkt( &OUTPRJ );
double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize };

OUTGDAL = OUTDRIVER->Create( out_name1.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions );
OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ);
OUTBAND1 = OUTGDAL->GetRasterBand(1);
OUTBAND1->SetNoDataValue(-9999);

OUTGDAL2 = OUTDRIVER->Create( out_name2.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions );
OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL2->SetProjection(OUTPRJ);
OUTBAND2 = OUTGDAL2->GetRasterBand(1);
OUTBAND2->SetNoDataValue(-9999);

//read/write data
float agb_data[xsize];
float agc_data[xsize];
float bgc_data[xsize];
float loss_data[xsize];
float peat_data[xsize];
float forestmodel_data[xsize];

float out_data1[xsize];
float out_data2[xsize];

for(y=37943; y<37946; y++) {
INBAND->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0);
INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, forestmodel_data, xsize, 1, GDT_Float32, 0, 0);
INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0);
INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, peat_data, xsize, 1, GDT_Float32, 0, 0);

for(x=0; x<xsize; x++)
{
   if (forestmodel_data[x] == 1)   // forestry
	{
		cout << "forest model data is 1: " << forestmodel_data[x] << "\n";
		if (agc_data[x] == -9999)
			{
				cout << "abc data is -9999: " << agc_data[x] << "\n";
				out_data1[x] = -9999;
			}

		else
			{
				if (peat_data[x] = -9999)
					{
					cout << "peat data is -9999: " << peat_data[x] << "\n";
					peat_data[x] = 0;
					}

				out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peat_data[x]);
				cout << "agc: " << agc_data[x] << "\n";
				cout << "bgc: " << bgc_data[x] << "\n";
				cout << "loss: " << loss_data[x] << "\n";
				cout << "peat: " << peat_data[x] << "\n";
				cout << "out data: " << out_data1[x] << "\n";
			}
    }

   else if (forestmodel_data[x] == 2)
   {
		cout << "forest model data is 2: " << forestmodel_data[x] << "\n";

		out_data2[x] = 2;
   }

   else
   {
    cout << "forest model data is not 1 or 2: " << forestmodel_data[x] << "\n";

    out_data2[x] = -9999;
   }

}
OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_data1, xsize, 1, GDT_Float32, 0, 0 );
OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_data2, xsize, 1, GDT_Float32, 0, 0 );

//closes for y loop
}

//close GDAL
GDALClose(INGDAL);
GDALClose((GDALDatasetH)OUTGDAL);
GDALClose((GDALDatasetH)OUTGDAL2);

return 0;
}
<|endoftext|>


<commit_before>// bdlqq_recursivemuteximpl_pthread.cpp                               -*-C++-*-
#include <bdlqq_recursivemuteximpl_pthread.h>

#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlqq_recursivemuteximpl_pthread_cpp,"$Id$ $CSID$")

#ifdef BDLQQ_PLATFORM_POSIX_THREADS

namespace BloombergLP {

              // ------------------------------------------------
              // class RecursiveMutexImpl<Platform::PosixThreads>
              // ------------------------------------------------

// CREATORS
bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::RecursiveMutexImpl()
: d_spin(bsls::SpinLock::s_unlocked)
{
    pthread_mutexattr_t attribute;
    pthread_mutexattr_init(&attribute);
#ifdef PTHREAD_MUTEX_RECURSIVE
    pthread_mutexattr_settype(&attribute,PTHREAD_MUTEX_RECURSIVE);
#else
    d_lockCount = 0;
#endif
    pthread_mutex_init(&d_lock, &attribute);
    pthread_mutexattr_destroy(&attribute);
}

// MANIPULATORS
void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::lock()
{
#ifdef PTHREAD_MUTEX_RECURSIVE
    pthread_mutex_lock(&d_lock);
#else
    if (pthread_mutex_trylock(&d_lock)) {
        d_spin.lock();
        if (d_lockCount && pthread_equal(d_owner,pthread_self())) {
            ++d_lockCount;
            d_spin.unlock();
            return;                                                   // RETURN
        }
        d_spin.unlock();
        pthread_mutex_lock(&d_lock);
    }
    d_spin.lock();
    d_owner = pthread_self();
    d_lockCount = 1;
    d_spin.unlock();
#endif
}

int bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::tryLock()
{
#ifdef PTHREAD_MUTEX_RECURSIVE
    return pthread_mutex_trylock(&d_lock);                            // RETURN
#else
    if (pthread_mutex_trylock(&d_lock)) {
        d_spin.lock();
        if (d_lockCount && pthread_equal(d_owner,pthread_self())) {
            ++d_lockCount;
            d_spin.unlock();
            return 0;                                                 // RETURN
        }
        else {
            d_spin.unlock();
            return 1;                                                 // RETURN
        }
    }
    else {
        d_spin.lock();
        d_owner = pthread_self();
        d_lockCount = 1;
        d_spin.unlock();
        return 0;                                                     // RETURN
    }
#endif
}

void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::unlock()
{
#ifdef PTHREAD_MUTEX_RECURSIVE
    pthread_mutex_unlock(&d_lock);
#else
    d_spin.lock();
    if (!--d_lockCount) {
        d_spin.unlock();
        pthread_mutex_unlock(&d_lock);
        return;                                                       // RETURN
    }
    d_spin.unlock();
#endif
}

}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>bdlqq_recursivemuteximpl_pthread: complining on aix<commit_after>// bdlqq_recursivemuteximpl_pthread.cpp                               -*-C++-*-
#include <bdlqq_recursivemuteximpl_pthread.h>

#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlqq_recursivemuteximpl_pthread_cpp,"$Id$ $CSID$")

#ifdef BDLQQ_PLATFORM_POSIX_THREADS

namespace BloombergLP {

              // ------------------------------------------------
              // class RecursiveMutexImpl<Platform::PosixThreads>
              // ------------------------------------------------

// CREATORS
bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::RecursiveMutexImpl()
#ifndef PTHREAD_MUTEX_RECURSIVE
: d_spin(bsls::SpinLock::s_unlocked)
#endif
{
    pthread_mutexattr_t attribute;
    pthread_mutexattr_init(&attribute);
#ifdef PTHREAD_MUTEX_RECURSIVE
    pthread_mutexattr_settype(&attribute,PTHREAD_MUTEX_RECURSIVE);
#else
    d_lockCount = 0;
#endif
    pthread_mutex_init(&d_lock, &attribute);
    pthread_mutexattr_destroy(&attribute);
}

// MANIPULATORS
void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::lock()
{
#ifdef PTHREAD_MUTEX_RECURSIVE
    pthread_mutex_lock(&d_lock);
#else
    if (pthread_mutex_trylock(&d_lock)) {
        d_spin.lock();
        if (d_lockCount && pthread_equal(d_owner,pthread_self())) {
            ++d_lockCount;
            d_spin.unlock();
            return;                                                   // RETURN
        }
        d_spin.unlock();
        pthread_mutex_lock(&d_lock);
    }
    d_spin.lock();
    d_owner = pthread_self();
    d_lockCount = 1;
    d_spin.unlock();
#endif
}

int bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::tryLock()
{
#ifdef PTHREAD_MUTEX_RECURSIVE
    return pthread_mutex_trylock(&d_lock);                            // RETURN
#else
    if (pthread_mutex_trylock(&d_lock)) {
        d_spin.lock();
        if (d_lockCount && pthread_equal(d_owner,pthread_self())) {
            ++d_lockCount;
            d_spin.unlock();
            return 0;                                                 // RETURN
        }
        else {
            d_spin.unlock();
            return 1;                                                 // RETURN
        }
    }
    else {
        d_spin.lock();
        d_owner = pthread_self();
        d_lockCount = 1;
        d_spin.unlock();
        return 0;                                                     // RETURN
    }
#endif
}

void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::unlock()
{
#ifdef PTHREAD_MUTEX_RECURSIVE
    pthread_mutex_unlock(&d_lock);
#else
    d_spin.lock();
    if (!--d_lockCount) {
        d_spin.unlock();
        pthread_mutex_unlock(&d_lock);
        return;                                                       // RETURN
    }
    d_spin.unlock();
#endif
}

}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>


<commit_before>#pragma once

#include "feature_info.hpp"

#include "../graphics/color.hpp"
#include "../graphics/screen.hpp"

#include "../std/list.hpp"
#include "../std/string.hpp"
#include "../std/shared_ptr.hpp"
#include "../std/map.hpp"

class ScreenBase;

namespace drule
{
  class BaseRule;
}

namespace graphics
{
  namespace gl
  {
    class FrameBuffer;
    class BaseTexture;
  }

  class ResourceManager;
}

class Drawer
{
  double m_visualScale;
  int m_level;

  scoped_ptr<graphics::Screen> m_pScreen;

  static void ClearResourceCache(size_t threadSlot, uint8_t pipelineID);

protected:

  void drawSymbol(m2::PointD const & pt,
                  graphics::EPosition pos,
                  di::DrawRule const & rule,
                  di::FeatureInfo::FeatureID const & id);

  void drawCircle(m2::PointD const & pt,
                  graphics::EPosition pos,
                  di::DrawRule const & rule,
                  di::FeatureInfo::FeatureID const & id);

  void drawPath(di::PathInfo const & path,
                di::DrawRule const * rules,
                size_t count);

  void drawArea(di::AreaInfo const & area,
                di::DrawRule const & rule);

  void drawText(m2::PointD const & pt,
                graphics::EPosition pos,
                di::FeatureStyler const & fs,
                di::DrawRule const & rule,
                di::FeatureInfo::FeatureID const & id);

  void drawPathText(di::PathInfo const & info,
                    di::FeatureStyler const & fs,
                    di::DrawRule const & rule);

  void drawPathNumber(di::PathInfo const & path,
                      di::FeatureStyler const & fs);

  typedef shared_ptr<graphics::gl::BaseTexture> texture_t;
  typedef shared_ptr<graphics::gl::FrameBuffer> frame_buffer_t;

public:

  struct Params : graphics::Screen::Params
  {
    double m_visualScale;
    Params();
  };

  Drawer(Params const & params = Params());

  double VisualScale() const;
  void SetScale(int level);

  int ThreadSlot() const;

  void clear(graphics::Color const & c = graphics::Color(187, 187, 187, 255), bool clearRT = true, float depth = 1.0f, bool clearDepth = true);

  graphics::Screen * screen() const;

  void drawSymbol(m2::PointD const & pt,
                  string const & symbolName,
                  graphics::EPosition pos,
                  double depth);

  void beginFrame();
  void endFrame();

  void clear(graphics::Color const & c = graphics::Color(187, 187, 187, 255),
             bool clearRT = true,
             float depth = -1.0f,
             bool clearDepth = true);

  void onSize(int w, int h);

};
<commit_msg>Minor fixes after merge.<commit_after>#pragma once

#include "feature_info.hpp"

#include "../graphics/color.hpp"
#include "../graphics/screen.hpp"

#include "../std/list.hpp"
#include "../std/string.hpp"
#include "../std/shared_ptr.hpp"
#include "../std/map.hpp"

class ScreenBase;

namespace drule
{
  class BaseRule;
}

namespace graphics
{
  namespace gl
  {
    class FrameBuffer;
    class BaseTexture;
  }

  class ResourceManager;
}

class Drawer
{
  double m_visualScale;
  int m_level;

  scoped_ptr<graphics::Screen> m_pScreen;

  static void ClearResourceCache(size_t threadSlot, uint8_t pipelineID);

protected:

  void drawSymbol(m2::PointD const & pt,
                  graphics::EPosition pos,
                  di::DrawRule const & rule,
                  di::FeatureInfo::FeatureID const & id);

  void drawCircle(m2::PointD const & pt,
                  graphics::EPosition pos,
                  di::DrawRule const & rule,
                  di::FeatureInfo::FeatureID const & id);

  void drawPath(di::PathInfo const & path,
                di::DrawRule const * rules,
                size_t count);

  void drawArea(di::AreaInfo const & area,
                di::DrawRule const & rule);

  void drawText(m2::PointD const & pt,
                graphics::EPosition pos,
                di::FeatureStyler const & fs,
                di::DrawRule const & rule,
                di::FeatureInfo::FeatureID const & id);

  void drawPathText(di::PathInfo const & info,
                    di::FeatureStyler const & fs,
                    di::DrawRule const & rule);

  void drawPathNumber(di::PathInfo const & path,
                      di::FeatureStyler const & fs);

  typedef shared_ptr<graphics::gl::BaseTexture> texture_t;
  typedef shared_ptr<graphics::gl::FrameBuffer> frame_buffer_t;

public:

  struct Params : graphics::Screen::Params
  {
    double m_visualScale;
    Params();
  };

  Drawer(Params const & params = Params());

  double VisualScale() const;
  void SetScale(int level);

  int ThreadSlot() const;

  graphics::Screen * screen() const;

  void drawSymbol(m2::PointD const & pt,
                  string const & symbolName,
                  graphics::EPosition pos,
                  double depth);

  void beginFrame();
  void endFrame();

  void clear(graphics::Color const & c = graphics::Color(187, 187, 187, 255),
             bool clearRT = true,
             float depth = 1.0f,
             bool clearDepth = true);

  void onSize(int w, int h);

  void Draw(di::FeatureInfo const & fi);
};
<|endoftext|>


<commit_before>#include "Patterns.h"

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>

void PatchStreams( char* streams, uint32_t count )
{
	const size_t SCRATCH_PAD_SIZE = 32767;
	const size_t MAX_ENTRY_SIZE = 24;

	char* buf = new char[ SCRATCH_PAD_SIZE ];
	GetPrivateProfileSectionA( "Samples", buf, SCRATCH_PAD_SIZE, "audio/audio-samples.ini" );

	uint32_t entriesRead = 0;
	for( char* raw = buf; *raw != '\0'; ++raw )
	{
		char* stream = streams;
		for ( size_t i = 0; i < MAX_ENTRY_SIZE; ++i )
		{
			*stream++ = *raw++;
			if ( *raw == '\0' ) break;
		}
		*stream = '\0';
		streams += MAX_ENTRY_SIZE+1;
		if ( ++entriesRead >= count ) break;
	}

	delete[] buf;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved)
{
	if ( reason == DLL_PROCESS_ATTACH)
	{
		using namespace hook;

		char* streamNames = *get_pattern<char*>( "8D 0C 49 01 C1 8D 44 24 04 81 C1", 11 );
		uint32_t* streamsCountVC = get_pattern<uint32_t>( "0F 84 D5 00 00 00 81 FD ? ? ? ? 0F 83 C9 00 00 00", 8 );
		uint8_t* streamsCountIII = get_pattern<uint8_t>( "0F 84 2E 03 00 00 80 BC 24 1C 01 00 00 ?", 13 );

		uint32_t numStreams;
		if ( streamsCountIII != nullptr )
			numStreams = *streamsCountIII;
		else if ( streamsCountVC != nullptr )
			numStreams = *streamsCountVC;
		else
			return FALSE; // Not III nor VC?

		PatchStreams( streamNames, numStreams );
	}
	return TRUE;
}<commit_msg>Reject too long strings (>24 characters)<commit_after>#include "Patterns.h"

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>

void PatchStreams( char* streams, uint32_t count )
{
	const size_t SCRATCH_PAD_SIZE = 32767;
	const size_t MAX_ENTRY_SIZE = 24;

	char* buf = new char[ SCRATCH_PAD_SIZE ];
	GetPrivateProfileSectionA( "Samples", buf, SCRATCH_PAD_SIZE, "audio/audio-samples.ini" );

	uint32_t entriesRead = 0;
	for( char* raw = buf; *raw != '\0'; ++raw )
	{
		char thisStream[MAX_ENTRY_SIZE+1];
		char* stream = thisStream;
		for ( size_t i = 0; i < MAX_ENTRY_SIZE; ++i )
		{
			*stream++ = *raw++;
			if ( *raw == '\0' ) break;
		}
		*stream = '\0';

		bool rejectEntry = false;
		if ( *raw != '\0' )
		{
			rejectEntry = true;
			while ( *++raw != '\0' );
		}
		if ( !rejectEntry )
		{
			strcpy_s( streams, MAX_ENTRY_SIZE+1, thisStream );
		}
		streams += MAX_ENTRY_SIZE+1;
		if ( ++entriesRead >= count ) break;
	}

	delete[] buf;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved)
{
	if ( reason == DLL_PROCESS_ATTACH)
	{
		using namespace hook;

		char* streamNames = *get_pattern<char*>( "8D 0C 49 01 C1 8D 44 24 04 81 C1", 11 );
		uint32_t* streamsCountVC = get_pattern<uint32_t>( "0F 84 D5 00 00 00 81 FD ? ? ? ? 0F 83 C9 00 00 00", 8 );
		uint8_t* streamsCountIII = get_pattern<uint8_t>( "0F 84 2E 03 00 00 80 BC 24 1C 01 00 00 ?", 13 );

		uint32_t numStreams;
		if ( streamsCountIII != nullptr )
			numStreams = *streamsCountIII;
		else if ( streamsCountVC != nullptr )
			numStreams = *streamsCountVC;
		else
			return FALSE; // Not III nor VC?

		PatchStreams( streamNames, numStreams );
	}
	return TRUE;
}<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_set_fsi_gp_shadow.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p10_set_fsi_gp_shadow.C
/// @brief Setup initial values for RC and RC_copy registers
//------------------------------------------------------------------------------
// *HWP HW Maintainer   : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer   : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by     : FSP
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p10_set_fsi_gp_shadow.H>
#include "p10_scom_perv_0.H"
#include "p10_scom_perv_1.H"
#include "p10_scom_perv_2.H"
#include "p10_scom_perv_3.H"
#include "p10_scom_perv_4.H"
#include "p10_scom_perv_5.H"
#include "p10_scom_perv_6.H"
#include "p10_scom_perv_8.H"
#include "p10_scom_perv_9.H"
#include "p10_scom_perv_c.H"
#include "p10_scom_perv_d.H"
#include "p10_scom_perv_e.H"

using namespace scomt;
using namespace scomt::perv;

struct
{
    uint32_t reg_addr, reg_copy_addr, value;
} P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES[] =
{

    { FSXCOMP_FSXLOG_ROOT_CTRL0_FSI, FSXCOMP_FSXLOG_ROOT_CTRL0_COPY_FSI, 0x80FF6007},
    { FSXCOMP_FSXLOG_ROOT_CTRL1_FSI, FSXCOMP_FSXLOG_ROOT_CTRL1_COPY_FSI, 0x00180020},
    { FSXCOMP_FSXLOG_ROOT_CTRL2_FSI, FSXCOMP_FSXLOG_ROOT_CTRL2_COPY_FSI, 0x04000000},
    { FSXCOMP_FSXLOG_ROOT_CTRL3_FSI, FSXCOMP_FSXLOG_ROOT_CTRL3_COPY_FSI, 0xEFEEEEFF},
    { FSXCOMP_FSXLOG_ROOT_CTRL8_FSI, FSXCOMP_FSXLOG_ROOT_CTRL8_COPY_FSI, 0x00000000},
    { FSXCOMP_FSXLOG_PERV_CTRL0_FSI, FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI, 0x7C022020},
    { FSXCOMP_FSXLOG_PERV_CTRL1_FSI, FSXCOMP_FSXLOG_PERV_CTRL1_COPY_FSI, 0x60000000}
};

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

fapi2::ReturnCode
p10_set_fsi_gp_shadow(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{

    FAPI_INF("p10_set_fsi_gp_shadow: Entering");

    for (auto rc : P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES)
    {
        fapi2::buffer<uint32_t> l_data = rc.value;
        FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_addr, l_data));
        FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_copy_addr, l_data));
    }

    FAPI_INF("p10_set_fsi_gp_shadow: Exiting");

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Don't Set CFAM Protection Bit In Root Ctrl<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_set_fsi_gp_shadow.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p10_set_fsi_gp_shadow.C
/// @brief Setup initial values for RC and RC_copy registers
//------------------------------------------------------------------------------
// *HWP HW Maintainer   : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer   : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by     : FSP
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p10_set_fsi_gp_shadow.H>
#include "p10_scom_perv_0.H"
#include "p10_scom_perv_1.H"
#include "p10_scom_perv_2.H"
#include "p10_scom_perv_3.H"
#include "p10_scom_perv_4.H"
#include "p10_scom_perv_5.H"
#include "p10_scom_perv_6.H"
#include "p10_scom_perv_8.H"
#include "p10_scom_perv_9.H"
#include "p10_scom_perv_c.H"
#include "p10_scom_perv_d.H"
#include "p10_scom_perv_e.H"

using namespace scomt;
using namespace scomt::perv;

struct
{
    uint32_t reg_addr, reg_copy_addr, value;
} P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES[] =
{

    { FSXCOMP_FSXLOG_ROOT_CTRL0_FSI, FSXCOMP_FSXLOG_ROOT_CTRL0_COPY_FSI, 0x00FF6007},
    { FSXCOMP_FSXLOG_ROOT_CTRL1_FSI, FSXCOMP_FSXLOG_ROOT_CTRL1_COPY_FSI, 0x00180020},
    { FSXCOMP_FSXLOG_ROOT_CTRL2_FSI, FSXCOMP_FSXLOG_ROOT_CTRL2_COPY_FSI, 0x04000000},
    { FSXCOMP_FSXLOG_ROOT_CTRL3_FSI, FSXCOMP_FSXLOG_ROOT_CTRL3_COPY_FSI, 0xEFEEEEFF},
    { FSXCOMP_FSXLOG_ROOT_CTRL8_FSI, FSXCOMP_FSXLOG_ROOT_CTRL8_COPY_FSI, 0x00000000},
    { FSXCOMP_FSXLOG_PERV_CTRL0_FSI, FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI, 0x7C022020},
    { FSXCOMP_FSXLOG_PERV_CTRL1_FSI, FSXCOMP_FSXLOG_PERV_CTRL1_COPY_FSI, 0x60000000}
};

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

fapi2::ReturnCode
p10_set_fsi_gp_shadow(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{

    FAPI_INF("p10_set_fsi_gp_shadow: Entering");

    for (auto rc : P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES)
    {
        fapi2::buffer<uint32_t> l_data = rc.value;
        FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_addr, l_data));
        FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_copy_addr, l_data));
    }

    FAPI_INF("p10_set_fsi_gp_shadow: Exiting");

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_MEPOO_MEPOO_SEGMENT_INL
#define IOX_POSH_MEPOO_MEPOO_SEGMENT_INL

#include "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_posh/mepoo/memory_info.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_utils/error_handling/error_handling.hpp"
#include "iceoryx_utils/internal/relocatable_pointer/relative_ptr.hpp"

namespace iox
{
namespace mepoo
{
template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline MePooSegment<SharedMemoryObjectType, MemoryManagerType>::MePooSegment(const MePooConfig& f_mempoolConfig,
                                                                             posix::Allocator* f_managementAllocator,
                                                                             const posix::PosixGroup& f_readerGroup,
                                                                             const posix::PosixGroup& f_writerGroup,
                                                                             const iox::mepoo::MemoryInfo& memoryInfo)
    : m_sharedMemoryObject(createSharedMemoryObject(f_mempoolConfig, f_writerGroup))
    , m_readerGroup(f_readerGroup)
    , m_writerGroup(f_writerGroup)
    , m_memoryInfo(memoryInfo)
{
    using namespace posix;
    AccessController f_accessController;
    if (!(f_readerGroup == f_writerGroup))
    {
        f_accessController.addPermissionEntry(
            AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READ, f_readerGroup.getName());
    }
    f_accessController.addPermissionEntry(
        AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, f_writerGroup.getName());
    f_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);
    f_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READWRITE);
    f_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);

    if (!f_accessController.writePermissionsToFile(m_sharedMemoryObject.getFileHandle()))
    {
        errorHandler(Error::kMEPOO__SEGMENT_COULD_NOT_APPLY_POSIX_RIGHTS_TO_SHARED_MEMORY);
    }

    m_memoryManager.configureMemoryManager(f_mempoolConfig, f_managementAllocator, m_sharedMemoryObject.getAllocator());
    m_sharedMemoryObject.finalizeAllocation();
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline SharedMemoryObjectType MePooSegment<SharedMemoryObjectType, MemoryManagerType>::createSharedMemoryObject(
    const MePooConfig& f_mempoolConfig, const posix::PosixGroup& f_writerGroup)
{
    // we let the OS decide where to map the shm segments
    constexpr void* BASE_ADDRESS_HINT{nullptr};

    // on qnx the current working directory will be added to the /dev/shmem path if the leading slash is missing
    auto shmName = "/" + f_writerGroup.getName();

    return std::move(
        SharedMemoryObjectType::create(shmName.c_str(),
                                       MemoryManager::requiredChunkMemorySize(f_mempoolConfig),
                                       posix::AccessMode::readWrite,
                                       posix::OwnerShip::mine,
                                       BASE_ADDRESS_HINT,
                                       S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
            .and_then([this](auto& sharedMemoryObject) {
                setSegmentId(iox::RelativePointer::registerPtr(sharedMemoryObject.getBaseAddress(),
                                                               sharedMemoryObject.getSizeInBytes()));

                LogDebug() << "Roudi registered payload segment "
                           << iox::log::HexFormat(reinterpret_cast<uint64_t>(sharedMemoryObject.getBaseAddress()))
                           << " with size " << sharedMemoryObject.getSizeInBytes() << " to id " << m_segmentId;
            })
            .or_else([](auto&) { errorHandler(Error::kMEPOO__SEGMENT_UNABLE_TO_CREATE_SHARED_MEMORY_OBJECT); })
            .value());
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getWriterGroup() const
{
    return m_writerGroup;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getReaderGroup() const
{
    return m_readerGroup;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline MemoryManagerType& MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getMemoryManager()
{
    return m_memoryManager;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline const SharedMemoryObjectType&
MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSharedMemoryObject() const
{
    return m_sharedMemoryObject;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline uint64_t MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSegmentId() const
{
    return m_segmentId;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline void MePooSegment<SharedMemoryObjectType, MemoryManagerType>::setSegmentId(const uint64_t segmentId)
{
    m_segmentId = segmentId;
}

} // namespace mepoo
} // namespace iox

#endif // IOX_POSH_MEPOO_MEPOO_SEGMENT_INL
<commit_msg>iox-#542 fixed clang conversion warning<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_MEPOO_MEPOO_SEGMENT_INL
#define IOX_POSH_MEPOO_MEPOO_SEGMENT_INL

#include "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_posh/mepoo/memory_info.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_utils/error_handling/error_handling.hpp"
#include "iceoryx_utils/internal/relocatable_pointer/relative_ptr.hpp"

namespace iox
{
namespace mepoo
{
template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline MePooSegment<SharedMemoryObjectType, MemoryManagerType>::MePooSegment(const MePooConfig& f_mempoolConfig,
                                                                             posix::Allocator* f_managementAllocator,
                                                                             const posix::PosixGroup& f_readerGroup,
                                                                             const posix::PosixGroup& f_writerGroup,
                                                                             const iox::mepoo::MemoryInfo& memoryInfo)
    : m_sharedMemoryObject(createSharedMemoryObject(f_mempoolConfig, f_writerGroup))
    , m_readerGroup(f_readerGroup)
    , m_writerGroup(f_writerGroup)
    , m_memoryInfo(memoryInfo)
{
    using namespace posix;
    AccessController f_accessController;
    if (!(f_readerGroup == f_writerGroup))
    {
        f_accessController.addPermissionEntry(
            AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READ, f_readerGroup.getName());
    }
    f_accessController.addPermissionEntry(
        AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, f_writerGroup.getName());
    f_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);
    f_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READWRITE);
    f_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);

    if (!f_accessController.writePermissionsToFile(m_sharedMemoryObject.getFileHandle()))
    {
        errorHandler(Error::kMEPOO__SEGMENT_COULD_NOT_APPLY_POSIX_RIGHTS_TO_SHARED_MEMORY);
    }

    m_memoryManager.configureMemoryManager(f_mempoolConfig, f_managementAllocator, m_sharedMemoryObject.getAllocator());
    m_sharedMemoryObject.finalizeAllocation();
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline SharedMemoryObjectType MePooSegment<SharedMemoryObjectType, MemoryManagerType>::createSharedMemoryObject(
    const MePooConfig& f_mempoolConfig, const posix::PosixGroup& f_writerGroup)
{
    // we let the OS decide where to map the shm segments
    constexpr void* BASE_ADDRESS_HINT{nullptr};

    // on qnx the current working directory will be added to the /dev/shmem path if the leading slash is missing
    auto shmName = "/" + f_writerGroup.getName();

    return std::move(
        SharedMemoryObjectType::create(shmName.c_str(),
                                       MemoryManager::requiredChunkMemorySize(f_mempoolConfig),
                                       posix::AccessMode::readWrite,
                                       posix::OwnerShip::mine,
                                       BASE_ADDRESS_HINT,
                                       static_cast<mode_t>(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP))
            .and_then([this](auto& sharedMemoryObject) {
                setSegmentId(iox::RelativePointer::registerPtr(sharedMemoryObject.getBaseAddress(),
                                                               sharedMemoryObject.getSizeInBytes()));

                LogDebug() << "Roudi registered payload segment "
                           << iox::log::HexFormat(reinterpret_cast<uint64_t>(sharedMemoryObject.getBaseAddress()))
                           << " with size " << sharedMemoryObject.getSizeInBytes() << " to id " << m_segmentId;
            })
            .or_else([](auto&) { errorHandler(Error::kMEPOO__SEGMENT_UNABLE_TO_CREATE_SHARED_MEMORY_OBJECT); })
            .value());
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getWriterGroup() const
{
    return m_writerGroup;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getReaderGroup() const
{
    return m_readerGroup;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline MemoryManagerType& MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getMemoryManager()
{
    return m_memoryManager;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline const SharedMemoryObjectType&
MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSharedMemoryObject() const
{
    return m_sharedMemoryObject;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline uint64_t MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSegmentId() const
{
    return m_segmentId;
}

template <typename SharedMemoryObjectType, typename MemoryManagerType>
inline void MePooSegment<SharedMemoryObjectType, MemoryManagerType>::setSegmentId(const uint64_t segmentId)
{
    m_segmentId = segmentId;
}

} // namespace mepoo
} // namespace iox

#endif // IOX_POSH_MEPOO_MEPOO_SEGMENT_INL
<|endoftext|>


<commit_before>
#include "rts_object_system.h"

#include "cocos2d.h"
#include "CCGLProgramStateCache.h"
#include "cor_system/sources/logger.h"
#include "cor_type/sources/primitive/box.h"
#include "cor_cocos2dx_converter/sources/type_converter.h"

namespace cor
{
    namespace cocos2dx_converter
    {
        struct RtsObjectSystemItnl
        {

        };

        RtsObjectSystem::RtsObjectSystem() : itnl(new RtsObjectSystemItnl())
        {

        }

        RtsObjectSystem::~RtsObjectSystem()
        {

        }

        void RtsObjectSystem::setup_rts_rendering_state()
        {
            cocos2d::Director::getInstance()->setDepthTest(false);
            cocos2d::Director::getInstance()->setAlphaBlending(true);

        }

        cocos2d::GLProgram* rts_object_system_alpha_test_shader = NULL;
        cocos2d::GLProgram* rts_object_system_round_shader = NULL;

#define STRINGIFY(A)  #A

        void rts_object_system_load_shader()
        {
            {
                static const char* my_frag_shader = STRINGIFY(

                    \n#ifdef GL_ES\n
                    precision lowp float;
                    \n#endif\n

                        varying vec4 v_fragmentColor;
                    varying vec2 v_texCoord;
                    /*uniform float cc_alpha_value;*/

                    void main()
                    {
                        vec4 texColor = texture2D(CC_Texture0, v_texCoord);
                        float cc_alpha_value = 0.5;
                        if(texColor.a <= cc_alpha_value)
                            discard;

                        texColor.a = 1.0;
                        gl_FragColor = texColor * v_fragmentColor;
                    }
                );

                if(rts_object_system_alpha_test_shader)
                {
                    rts_object_system_alpha_test_shader->release();
                }

                auto ss = cocos2d::GLProgram::createWithByteArrays(cocos2d::ccPositionTextureColor_noMVP_vert, my_frag_shader);
                rts_object_system_alpha_test_shader = ss;
                ss->retain();

            }

            {
                const char* my_vert_shader = STRINGIFY(
                    attribute vec4 a_position;
                    attribute vec2 a_texCoord;
                    attribute vec4 a_color;

                    \n#ifdef GL_ES\n
                        varying lowp vec4 v_fragmentColor;
                    varying mediump vec2 v_texCoord;
                    \n#else\n
                        varying vec4 v_fragmentColor;
                    varying vec2 v_texCoord;
                    \n#endif\n

                        void main()
                    {
                        gl_Position = CC_PMatrix * a_position;
                        gl_Position.x *= 400.0;
                        gl_Position.y *= 240.0;
                        gl_Position.xy = floor(gl_Position.xy + vec2(0.5, 0.5));
                        gl_Position.x /= 400.0;
                        gl_Position.y /= 240.0;
                        v_fragmentColor = a_color;
                        v_texCoord = a_texCoord;
                    }
                );

                if(rts_object_system_round_shader)
                {
                    rts_object_system_round_shader->release();
                }

                auto ss = cocos2d::GLProgram::createWithByteArrays(my_vert_shader, cocos2d::ccPositionTextureColor_noMVP_frag);
                rts_object_system_round_shader = ss;
                ss->retain();

            }

        }

        void RtsObjectSystem::setup_sprite_alphatest(cocos2d::Sprite* sprite)
        {
            static cocos2d::GLProgramState* s = NULL;
            if(!s)
            {
                rts_object_system_load_shader();
                s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(rts_object_system_alpha_test_shader);
                s->retain();
            }
            sprite->setGLProgramState(s);
        }

        void RtsObjectSystem::setup_sprite_round(cocos2d::Sprite* sprite)
        {
            static cocos2d::GLProgramState* s = NULL;
            static RBool need_reset = rfalse;
            auto p_need_reset = &need_reset;
            auto ps = &s;
            if(!s)
            {
                auto shader = &rts_object_system_round_shader;
                rts_object_system_load_shader();
                log_debug("shader ", (*shader)->getProgram());
                s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader);
                s->retain();
                auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {
                    *p_need_reset = rtrue;

                });
                cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -2);
                {
                    // todo: comfirm on android
                    auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {

                        auto scn = cocos2d::Director::getInstance()->getRunningScene();
                        scn->enumerateChildren("//[[:alnum:]]+", [&](cocos2d::Node* n){
                            if(n->getGLProgramState() == s)
                            {
                                n->setGLProgramState(
                                    cocos2d::GLProgramState::getOrCreateWithGLProgramName(
                                    cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
                            }
                            return false;
                        });

                    });

                    cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3);
                }
            }
            sprite->setGLProgramState(s);
            {
                //auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {
                //    sprite->setGLProgramState(
                //        cocos2d::GLProgramState::getOrCreateWithGLProgramName(
                //            cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
                //});

                //// Memory leak.
                //sprite->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3);
            }
            {
                auto shader = &rts_object_system_round_shader;
                auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {

                    RtsObjectSystem::delay_call(sprite, 0.01f, [=](){

                        if(*p_need_reset)
                        {
                            auto s = *ps;
                            s->release();
                            cocos2d::GLProgramStateCache::getInstance()->removeUnusedGLProgramState();
                            rts_object_system_load_shader();
                            s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader);
                            s->retain();
                            *ps = s;

                            *p_need_reset = rfalse;
                        }

                        sprite->setGLProgramState(*ps);
                    });
                });
                sprite->getEventDispatcher()->addEventListenerWithSceneGraphPriority(backToForegroundlistener, sprite);

            }
        }

        void RtsObjectSystem::setup_avoid_blur_texture(cocos2d::Texture2D* texture)
        {
            cocos2d::Texture2D::TexParams p;
            p.minFilter = GL_NEAREST;
            p.magFilter = GL_LINEAR;
            p.wrapS = GL_CLAMP_TO_EDGE;
            p.wrapT = GL_CLAMP_TO_EDGE;
            texture->setTexParameters(p);
        }

        cocos2d::Rect RtsObjectSystem::node_rect(cocos2d::Node* node)
        {
            auto bb = node->getBoundingBox();
            type::Matrix4x4F mat;
            convert(node->getNodeToWorldTransform(), mat);
            auto imat = mat.affine_inverse();
            type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
            type::Box2F ab;

            type::Box2F tb;
            if(bb.size.width > 0)
            {
                //tb.set_rect(imat, b);
                ab = b;
            }

            node->enumerateChildren("//.*", [&](cocos2d::Node* n){
                type::Matrix4x4F m;
                convert(n->getParent()->getNodeToWorldTransform(), m);

                type::Matrix4x4F tm;
                tm = imat * m;

                auto bb = n->getBoundingBox();
                type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
                type::Box2F tb;
                tb.set_rect(tm, b);
                ab.add_rect(tb);

                return false;
            });

            return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y);

        }

        cocos2d::Rect RtsObjectSystem::nodes_rect(cocos2d::Vector<cocos2d::Node*> nodes)
        {
            //depricated
            if(nodes.size() > 0)
            {
                type::Box2F aab;

                for(auto node : nodes)
                {
                    auto bb = node->getBoundingBox();
                    type::Matrix4x4F mat;
                    convert(node->getNodeToWorldTransform(), mat);
                    auto imat = mat.affine_inverse();
                    type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
                    type::Box2F ab;
                    type::Box2F tb;
                    tb.set_rect(imat, b);
                    ab = tb;

                    node->enumerateChildren("//.*", [&](cocos2d::Node* n){
                        type::Matrix4x4F m;
                        convert(n->getParent()->getNodeToWorldTransform(), m);

                        type::Matrix4x4F tm;
                        tm = imat * m;

                        auto bb = n->getBoundingBox();
                        type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
                        type::Box2F tb;
                        tb.set_rect(tm, b);
                        ab.add_rect(tb);

                        return false;
                    });

                    tb.set_rect(mat, b);
                    ab = tb;

                    aab.add_rect(ab);
                }

                auto ab = aab;
                return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y);
            }
            return cocos2d::Rect();

        }

        cocos2d::Action* RtsObjectSystem::delay_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback)
        {
            cocos2d::Vector<cocos2d::FiniteTimeAction*> a;
            a.pushBack(cocos2d::DelayTime::create(interval));
            a.pushBack(cocos2d::CallFunc::create([=](){callback(); }));
            return node->runAction(cocos2d::Sequence::create(
                a
                ));
        }

        cocos2d::Action* RtsObjectSystem::interval_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback)
        {
            cocos2d::Vector<cocos2d::FiniteTimeAction*> a;
            a.pushBack(cocos2d::DelayTime::create(interval));
            a.pushBack(cocos2d::CallFunc::create([=](){callback(); }));
            return node->runAction(
                cocos2d::RepeatForever::create(cocos2d::Sequence::create(
                a
                )));
        }

        void RtsObjectSystem::on_active()
        {
            //log_debug("RtsObjectSystem::on_active");
            //rts_object_system_load_shader();
        }

    }
}
<commit_msg>restore shader on android.<commit_after>
#include "rts_object_system.h"

#include "cocos2d.h"
#include "CCGLProgramStateCache.h"
#include "cor_system/sources/logger.h"
#include "cor_type/sources/primitive/box.h"
#include "cor_cocos2dx_converter/sources/type_converter.h"

namespace cor
{
    namespace cocos2dx_converter
    {
        struct RtsObjectSystemItnl
        {

        };

        RtsObjectSystem::RtsObjectSystem() : itnl(new RtsObjectSystemItnl())
        {

        }

        RtsObjectSystem::~RtsObjectSystem()
        {

        }

        void RtsObjectSystem::setup_rts_rendering_state()
        {
            cocos2d::Director::getInstance()->setDepthTest(false);
            cocos2d::Director::getInstance()->setAlphaBlending(true);

        }

        cocos2d::GLProgram* rts_object_system_alpha_test_shader = NULL;
        cocos2d::GLProgram* rts_object_system_round_shader = NULL;

#define STRINGIFY(A)  #A

        void rts_object_system_load_shader()
        {
            {
                static const char* my_frag_shader = STRINGIFY(

                    \n#ifdef GL_ES\n
                    precision lowp float;
                    \n#endif\n

                        varying vec4 v_fragmentColor;
                    varying vec2 v_texCoord;
                    /*uniform float cc_alpha_value;*/

                    void main()
                    {
                        vec4 texColor = texture2D(CC_Texture0, v_texCoord);
                        float cc_alpha_value = 0.5;
                        if(texColor.a <= cc_alpha_value)
                            discard;

                        texColor.a = 1.0;
                        gl_FragColor = texColor * v_fragmentColor;
                    }
                );

                if(rts_object_system_alpha_test_shader)
                {
                    rts_object_system_alpha_test_shader->release();
                }

                auto ss = cocos2d::GLProgram::createWithByteArrays(cocos2d::ccPositionTextureColor_noMVP_vert, my_frag_shader);
                rts_object_system_alpha_test_shader = ss;
                ss->retain();

            }

            {
                const char* my_vert_shader = STRINGIFY(
                    attribute vec4 a_position;
                    attribute vec2 a_texCoord;
                    attribute vec4 a_color;

                    \n#ifdef GL_ES\n
                        varying lowp vec4 v_fragmentColor;
                    varying mediump vec2 v_texCoord;
                    \n#else\n
                        varying vec4 v_fragmentColor;
                    varying vec2 v_texCoord;
                    \n#endif\n

                        void main()
                    {
                        gl_Position = CC_PMatrix * a_position;
                        gl_Position.x *= 400.0;
                        gl_Position.y *= 240.0;
                        gl_Position.xy = floor(gl_Position.xy + vec2(0.5, 0.5));
                        gl_Position.x /= 400.0;
                        gl_Position.y /= 240.0;
                        v_fragmentColor = a_color;
                        v_texCoord = a_texCoord;
                    }
                );

                if(rts_object_system_round_shader)
                {
                    rts_object_system_round_shader->release();
                }

                auto ss = cocos2d::GLProgram::createWithByteArrays(my_vert_shader, cocos2d::ccPositionTextureColor_noMVP_frag);
                rts_object_system_round_shader = ss;
                ss->retain();

            }

        }

        void RtsObjectSystem::setup_sprite_alphatest(cocos2d::Sprite* sprite)
        {
            static cocos2d::GLProgramState* s = NULL;
            if(!s)
            {
                rts_object_system_load_shader();
                s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(rts_object_system_alpha_test_shader);
                s->retain();
            }
            sprite->setGLProgramState(s);
        }

        void RtsObjectSystem::setup_sprite_round(cocos2d::Sprite* sprite)
        {
            static cocos2d::GLProgramState* s = NULL;
            static RBool need_reset = rfalse;
            auto p_need_reset = &need_reset;
            auto ps = &s;
            if(!s)
            {
                auto shader = &rts_object_system_round_shader;
                rts_object_system_load_shader();
                log_debug("shader ", (*shader)->getProgram());
                s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader);
                s->retain();
                auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {
                    log_debug("backToForegroundlistener -2");
                    *p_need_reset = rtrue;

                });
                cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -2);
                {
                    // todo: comfirm on android
                    auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {
                        log_debug("backToForegroundlistener -3");
                        auto scn = cocos2d::Director::getInstance()->getRunningScene();
                        log_debug("scn ", scn);
                        scn->enumerateChildren("//.*", [&](cocos2d::Node* n){
                            log_debug("n ", n);
                            if(n->getGLProgramState() == s)
                            {
                                log_debug("eq");
                                n->setGLProgramState(
                                    cocos2d::GLProgramState::getOrCreateWithGLProgramName(
                                    cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
                            }
                            return false;
                        });
                        log_debug("scn ed ", scn);
                    });

                    cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3);
                }
            }
            sprite->setGLProgramState(s);
            {
                //auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {
                //    sprite->setGLProgramState(
                //        cocos2d::GLProgramState::getOrCreateWithGLProgramName(
                //            cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
                //});

                //// Memory leak.
                //sprite->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3);
            }
            {
                auto shader = &rts_object_system_round_shader;
                auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) {

                    RtsObjectSystem::delay_call(sprite, 0.01f, [=](){
                        log_debug("backToForegroundlistener sg");
                        if(*p_need_reset)
                        {
                            auto s = *ps;
                            s->release();
                            cocos2d::GLProgramStateCache::getInstance()->removeUnusedGLProgramState();
                            rts_object_system_load_shader();
                            s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader);
                            s->retain();
                            *ps = s;

                            *p_need_reset = rfalse;
                        }

                        sprite->setGLProgramState(*ps);
                    });
                });
                sprite->getEventDispatcher()->addEventListenerWithSceneGraphPriority(backToForegroundlistener, sprite);

            }
        }

        void RtsObjectSystem::setup_avoid_blur_texture(cocos2d::Texture2D* texture)
        {
            cocos2d::Texture2D::TexParams p;
            p.minFilter = GL_NEAREST;
            p.magFilter = GL_LINEAR;
            p.wrapS = GL_CLAMP_TO_EDGE;
            p.wrapT = GL_CLAMP_TO_EDGE;
            texture->setTexParameters(p);
        }

        cocos2d::Rect RtsObjectSystem::node_rect(cocos2d::Node* node)
        {
            auto bb = node->getBoundingBox();
            type::Matrix4x4F mat;
            convert(node->getNodeToWorldTransform(), mat);
            auto imat = mat.affine_inverse();
            type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
            type::Box2F ab;

            type::Box2F tb;
            if(bb.size.width > 0)
            {
                //tb.set_rect(imat, b);
                ab = b;
            }

            node->enumerateChildren("//.*", [&](cocos2d::Node* n){
                type::Matrix4x4F m;
                convert(n->getParent()->getNodeToWorldTransform(), m);

                type::Matrix4x4F tm;
                tm = imat * m;

                auto bb = n->getBoundingBox();
                type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
                type::Box2F tb;
                tb.set_rect(tm, b);
                ab.add_rect(tb);

                return false;
            });

            return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y);

        }

        cocos2d::Rect RtsObjectSystem::nodes_rect(cocos2d::Vector<cocos2d::Node*> nodes)
        {
            //depricated
            if(nodes.size() > 0)
            {
                type::Box2F aab;

                for(auto node : nodes)
                {
                    auto bb = node->getBoundingBox();
                    type::Matrix4x4F mat;
                    convert(node->getNodeToWorldTransform(), mat);
                    auto imat = mat.affine_inverse();
                    type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
                    type::Box2F ab;
                    type::Box2F tb;
                    tb.set_rect(imat, b);
                    ab = tb;

                    node->enumerateChildren("//.*", [&](cocos2d::Node* n){
                        type::Matrix4x4F m;
                        convert(n->getParent()->getNodeToWorldTransform(), m);

                        type::Matrix4x4F tm;
                        tm = imat * m;

                        auto bb = n->getBoundingBox();
                        type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height));
                        type::Box2F tb;
                        tb.set_rect(tm, b);
                        ab.add_rect(tb);

                        return false;
                    });

                    tb.set_rect(mat, b);
                    ab = tb;

                    aab.add_rect(ab);
                }

                auto ab = aab;
                return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y);
            }
            return cocos2d::Rect();

        }

        cocos2d::Action* RtsObjectSystem::delay_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback)
        {
            cocos2d::Vector<cocos2d::FiniteTimeAction*> a;
            a.pushBack(cocos2d::DelayTime::create(interval));
            a.pushBack(cocos2d::CallFunc::create([=](){callback(); }));
            return node->runAction(cocos2d::Sequence::create(
                a
                ));
        }

        cocos2d::Action* RtsObjectSystem::interval_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback)
        {
            cocos2d::Vector<cocos2d::FiniteTimeAction*> a;
            a.pushBack(cocos2d::DelayTime::create(interval));
            a.pushBack(cocos2d::CallFunc::create([=](){callback(); }));
            return node->runAction(
                cocos2d::RepeatForever::create(cocos2d::Sequence::create(
                a
                )));
        }

        void RtsObjectSystem::on_active()
        {
            //log_debug("RtsObjectSystem::on_active");
            //rts_object_system_load_shader();
        }

    }
}
<|endoftext|>


<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__

#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/constants.hpp>

namespace stan {

  namespace prob {

    // NegBinomial(n|alpha,beta)  [alpha > 0;  beta > 0;  n >= 0]
    template <bool propto,
	      typename T_n,
              typename T_shape, typename T_inv_scale,
              class Policy>
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta,
                     const Policy&) {

      static const char* function = "stan::prob::neg_binomial_log(%1%)";

      using stan::math::check_finite;
      using stan::math::check_nonnegative;
      using stan::math::check_positive;
      using stan::math::value_of;
      using stan::math::check_consistent_sizes;
      using stan::prob::include_summand;

      // check if any vectors are zero length
      if (!(stan::length(n)
	    && stan::length(alpha)
	    && stan::length(beta)))
	return 0.0;

      typename return_type<T_shape, T_inv_scale>::type logp(0.0);
      if (!check_nonnegative(function, n, "Failures variable", &logp, Policy()))
        return logp;
      if (!check_finite(function, alpha, "Shape parameter", &logp, Policy()))
        return logp;
      if (!check_positive(function, alpha, "Shape parameter", &logp, Policy()))
        return logp;
      if (!check_finite(function, beta, "Inverse scale parameter",
                        &logp, Policy()))
        return logp;
      if (!check_positive(function, beta, "Inverse scale parameter",
                          &logp, Policy()))
        return logp;
      if (!(check_consistent_sizes(function,
                                   n,alpha,beta,
				   "Failures variable","Shape parameter","Inverse scale parameter",
                                   &logp, Policy())))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_shape,T_inv_scale>::value)
	return 0.0;

      using stan::math::multiply_log;
      using stan::math::binomial_coefficient_log;

      // set up template expressions wrapping scalars into vector views
      VectorView<const T_n> n_vec(n);
      VectorView<const T_shape> alpha_vec(alpha);
      VectorView<const T_inv_scale> beta_vec(beta);
      size_t size = max_size(n, alpha, beta);

      for (size_t i = 0; i < size; i++) {
	// Special case where negative binomial reduces to Poisson
	if (alpha_vec[i] > 1e10) {
	  if (include_summand<propto>::value)
	    logp -= lgamma(n_vec[i] + 1.0);
	  if (include_summand<propto,T_shape>::value ||
	      include_summand<propto,T_inv_scale>::value) {
	    typename return_type<T_shape, T_inv_scale>::type lambda;
	    lambda = alpha_vec[i] / beta_vec[i];
	    logp += multiply_log(n_vec[i], lambda) - lambda;
	  }
	}
	// More typical cases
	if (include_summand<propto,T_shape>::value)
	  if (n_vec[i] != 0)
	    logp += binomial_coefficient_log<typename scalar_type<T_shape>::type>
	      (n_vec[i] + alpha_vec[i] - 1.0, n_vec[i]);
	if (include_summand<propto,T_shape,T_inv_scale>::value)
	  logp += -n_vec[i] * log1p(beta_vec[i])
	    + alpha_vec[i] * log(beta_vec[i] / (1 + beta_vec[i]));
      }
      return logp;
    }

    template <bool propto,
	      typename T_n,
              typename T_shape, typename T_inv_scale>
    inline
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta) {
      return neg_binomial_log<propto>(n,alpha,beta,
                                      stan::math::default_policy());
    }

    template <typename T_n,
	      typename T_shape, typename T_inv_scale,
              class Policy>
    inline
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta,
                     const Policy&) {
      return neg_binomial_log<false>(n,alpha,beta,Policy());
    }

    template <typename T_n,
	      typename T_shape, typename T_inv_scale>
    inline
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta) {
      return neg_binomial_log<false>(n,alpha,beta,
                                      stan::math::default_policy());
    }

  }
}
#endif
<commit_msg>updating neg_binomial distribution<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__

#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/constants.hpp>

namespace stan {

  namespace prob {

    // NegBinomial(n|alpha,beta)  [alpha > 0;  beta > 0;  n >= 0]
    template <bool propto,
	      typename T_n,
              typename T_shape, typename T_inv_scale,
              class Policy>
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta,
                     const Policy&) {

      static const char* function = "stan::prob::neg_binomial_log(%1%)";

      using stan::math::check_finite;
      using stan::math::check_nonnegative;
      using stan::math::check_positive;
      using stan::math::value_of;
      using stan::math::check_consistent_sizes;
      using stan::prob::include_summand;

      // check if any vectors are zero length
      if (!(stan::length(n)
	    && stan::length(alpha)
	    && stan::length(beta)))
	return 0.0;

      typename return_type<T_shape, T_inv_scale>::type logp(0.0);
      if (!check_nonnegative(function, n, "Failures variable", &logp, Policy()))
        return logp;
      if (!check_finite(function, alpha, "Shape parameter", &logp, Policy()))
        return logp;
      if (!check_positive(function, alpha, "Shape parameter", &logp, Policy()))
        return logp;
      if (!check_finite(function, beta, "Inverse scale parameter",
                        &logp, Policy()))
        return logp;
      if (!check_positive(function, beta, "Inverse scale parameter",
                          &logp, Policy()))
        return logp;
      if (!(check_consistent_sizes(function,
                                   n,alpha,beta,
				   "Failures variable","Shape parameter","Inverse scale parameter",
                                   &logp, Policy())))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_shape,T_inv_scale>::value)
	return 0.0;

      using stan::math::multiply_log;
      using stan::math::binomial_coefficient_log;

      // set up template expressions wrapping scalars into vector views
      VectorView<const T_n> n_vec(n);
      VectorView<const T_shape> alpha_vec(alpha);
      VectorView<const T_inv_scale> beta_vec(beta);
      size_t size = max_size(n, alpha, beta);

      for (size_t i = 0; i < size; i++) {
	// Special case where negative binomial reduces to Poisson
	if (alpha_vec[i] > 1e10) {
	  if (include_summand<propto>::value)
	    logp -= lgamma(n_vec[i] + 1.0);
	  if (include_summand<propto,T_shape>::value ||
	      include_summand<propto,T_inv_scale>::value) {
	    typename return_type<T_shape, T_inv_scale>::type lambda;
	    lambda = alpha_vec[i] / beta_vec[i];
	    logp += multiply_log(n_vec[i], lambda) - lambda;
	  }
	} else {
	// More typical cases
	  if (include_summand<propto,T_shape>::value)
	    if (n_vec[i] != 0)
	      logp += binomial_coefficient_log<typename scalar_type<T_shape>::type>
		(n_vec[i] + alpha_vec[i] - 1.0, n_vec[i]);
	  if (include_summand<propto,T_shape,T_inv_scale>::value)
	    logp += -n_vec[i] * log1p(beta_vec[i])
	      + alpha_vec[i] * log(beta_vec[i] / (1 + beta_vec[i]));
	}
      }
      return logp;
    }

    template <bool propto,
	      typename T_n,
              typename T_shape, typename T_inv_scale>
    inline
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta) {
      return neg_binomial_log<propto>(n,alpha,beta,
                                      stan::math::default_policy());
    }

    template <typename T_n,
	      typename T_shape, typename T_inv_scale,
              class Policy>
    inline
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta,
                     const Policy&) {
      return neg_binomial_log<false>(n,alpha,beta,Policy());
    }

    template <typename T_n,
	      typename T_shape, typename T_inv_scale>
    inline
    typename return_type<T_shape, T_inv_scale>::type
    neg_binomial_log(const T_n& n,
                     const T_shape& alpha,
                     const T_inv_scale& beta) {
      return neg_binomial_log<false>(n,alpha,beta,
                                      stan::math::default_policy());
    }

  }
}
#endif
<|endoftext|>