Ejemplo n.º 1
0
void move_spaceship(celestial_object *obj)
{
  obj->position.x += my_round(obj->x_move);
  obj->position.y += my_round(obj->y_move);

  toroidal_space(obj);
}
bool FaceTrackingRenderer3D::ProjectVertex(const PXCPoint3DF32 &v, double &x, double &y, int radius)
{
	x = m_outputImageInfo.width  * (0.5 + 0.001 * v.x);
	y = m_outputImageInfo.height * (0.5 - 0.001 * v.y);

	return ((radius <= my_round(x)) && (my_round(x) < m_outputImageInfo.width-radius) && (radius <= my_round(y)) && (my_round(y) < m_outputImageInfo.height-radius));
}
int __cdecl CHistoricalDataApi::OnRspHistoryQuot(struct STKHISDATA *pHisData)
{
	//BarField* pFields = new BarField[pHisData->nCount];
	BarField* pFields = (BarField*)m_msgQueue->new_block(sizeof(BarField)*pHisData->nCount);

	for (short i = 0; i < pHisData->nCount; i++)
	{
		HISTORYDATA item = pHisData->HisData[i];

		BarField* pF = &pFields[i];
		//memset(pF, 0, sizeof(BarField));
		DateTimeChat2Int(item.time, pF->Date, pF->Time);
		pF->Open = my_round(item.fOpen);
		pF->High = my_round(item.fHigh);
		pF->Low = item.fLow;
		pF->Close = item.fClose;
		pF->Volume = item.fVolume;
		pF->OpenInterest = item.fAmount;
	}

	m_msgQueue->Input_Copy(ResponeType::OnRspQryHistoricalBars, m_msgQueue, m_pClass, true, 0, pFields, sizeof(BarField)*pHisData->nCount, &m_RequestBar, sizeof(HistoricalDataRequestField), nullptr, 0);

	m_msgQueue->delete_block(pFields);

	return 0;
}
Ejemplo n.º 4
0
void move_bullet(list bullet_list)
{
  while (!is_empty(bullet_list))
    {
      bullet_list->object.position.x += my_round(bullet_list->object.x_move * bullet_list->object.speed);
      bullet_list->object.position.y -= my_round(bullet_list->object.y_move * bullet_list->object.speed);

      toroidal_space(&bullet_list->object);
      bullet_list->object.life_span += 1;      
      bullet_list = tail(bullet_list);
    }
}
Ejemplo n.º 5
0
static void ftran(lprec *lp, REAL *pcol)
{
  int  i, j, k, r, *rowp;
  REAL theta, *valuep;

  for(i = 1; i <= lp->eta_size; i++) {
    k = lp->eta_col_end[i] - 1;
    r = lp->eta_row_nr[k];
    theta = pcol[r];
    if(theta != 0) {
      j = lp->eta_col_end[i - 1];
      
      /* CPU intensive loop, let's do pointer arithmetic */
      for(rowp = lp->eta_row_nr + j, valuep = lp->eta_value + j;
	  j < k;
	  j++, rowp++, valuep++)
	pcol[*rowp] += theta * *valuep;
      
      pcol[r] *= lp->eta_value[k];
    }
  }

  /* round small values to zero */
  for(i = 0; i <= lp->rows; i++)
    my_round(pcol[i], lp->epsel);
} /* ftran */
Ejemplo n.º 6
0
double my_round(double x, unsigned int digits) {//Eigene Round fuunktion (math.h fuerhte zu absturz)
    if (digits > 0) {
        return my_round(x*10.0, digits-1)/10.0;
    }
    else {
        return x;
    }
}
Ejemplo n.º 7
0
void move(double theta)
{
    double left_power = 0.0;
    double right_power = 0.0;
    if (theta >= ANGLE_TOL)
    {
        left_power = MOVE_SPEED;
        right_power = cos(theta ) * MOVE_SPEED;
    }
    else if (theta <= -ANGLE_TOL)
    {
        right_power = MOVE_SPEED;
        left_power = cos(theta ) * MOVE_SPEED;
    }
    else
    {
        left_power = MOVE_SPEED;
        right_power = MOVE_SPEED;
    }

    apply_power(my_round(left_power), my_round(right_power));
}
int __cdecl CHistoricalDataApi::OnRspTraceData(struct STKTRACEDATA *pTraceData)
{
	m_timer_1 = 0;

	//TickField* pFields = new TickField[pTraceData->nCount];
	TickField* pFields = (TickField*)m_msgQueue->new_block(sizeof(TickField)*pTraceData->nCount);

	for (size_t i = 0; i < pTraceData->nCount; i++)
	{
		STOCKTRACEDATA item = pTraceData->TraceData[i];

		TickField* pF = &pFields[i];
		//memset(pF, 0, sizeof(TickField));
		DateTimeChat2Int(item.time, pF->Date, pF->Time);
		pF->LastPrice = my_round(item.m_NewPrice);
		pF->Volume = item.m_Volume;
		pF->OpenInterest = item.m_Amount;
		pF->BidPrice1 = my_round(item.m_BuyPrice);
		pF->AskPrice1 = my_round(item.m_SellPrice);
		pF->BidSize1 = (VolumeType)item.m_BuyVol;
		pF->AskSize1 = (VolumeType)item.m_SellVol;
	}

	bool bIsLast = m_RequestTick.CurrentDate >= m_RequestTick.Date2;

	m_msgQueue->Input_Copy(ResponeType::OnRspQryHistoricalTicks, m_msgQueue, m_pClass, bIsLast, 0, pFields, sizeof(TickField)*pTraceData->nCount, &m_RequestTick, sizeof(HistoricalDataRequestField), nullptr, 0);

	m_msgQueue->delete_block(pFields);

	if (!bIsLast)
	{
		m_RequestTick.CurrentDate = GetNextTradingDate(m_RequestTick.CurrentDate);
		m_msgQueue_Query->Input_Copy(RequestType::E_ReqQryHistoricalTicks, m_msgQueue_Query, this, 0, 0,
			&m_RequestTick, sizeof(HistoricalDataRequestField), nullptr, 0, nullptr, 0);
	}

	return 0;
}
Ejemplo n.º 9
0
void write_PPM(char *filename, Image *im)
{
	int i, j, t;
	FILE *fp;

	// write size info

	fp = fopen(filename, "wb");

	fprintf(fp, "P6\n%i %i\n255\n", im->w, im->h);

	// write binary image data

	for (j = 0, t = 0; j < im->h; j++) 
		for (i = 0; i < im->w; i++, t += 4) 
			fprintf(fp, "%c%c%c", 
			(int) my_round(255*im->data[t]), 
			(int) my_round(255*im->data[t+1]), 
			(int) my_round(255*im->data[t+2]));

	// finish up

	fclose(fp);
}
Ejemplo n.º 10
0
void btran(lprec *lp, REAL *row)
{
  int  i, j, k, *rowp;
  REAL f, *valuep;

  for(i = lp->eta_size; i >= 1; i--) {
    f = 0;
    k = lp->eta_col_end[i] - 1;
    j = lp->eta_col_end[i - 1];

    for(rowp = lp->eta_row_nr + j, valuep = lp->eta_value + j;
	j <= k;
	j++, rowp++, valuep++)
      f += row[*rowp] * *valuep;
    
    my_round(f, lp->epsel);
    row[lp->eta_row_nr[k]] = f;
  }
} /* btran */
Ejemplo n.º 11
0
/// \param[in]  periodData
/// \param[in]  wft
/// \param[out] eventData
/// \param[in]  timescale
void getEventData ( 
        CycleData::PeriodData& periodData,
        WaveformTable&         wft,
        EventData&             eventData,
        vector<string>&        pinList,
        double                 timescale)  {

        for(unsigned int i=0; i < periodData.wfcVec.size(); i++) {
            char   wfc     = periodData.wfcVec[i];
            string pinName = pinList[i];

            map<double, State> events;
            wft.getEvents( pinName, wfc, events);

            map<double, State>::iterator iter;
            for(iter = events.begin(); iter != events.end(); iter++) {
                unsigned long long timestamp = 0;
                // Need my_round due to fractional error
                timestamp = (unsigned long long) my_round(iter->first / timescale);
                eventData.data[timestamp].push_back( make_pair(pinName, iter->second)); 
            }
        }

}
Ejemplo n.º 12
0
/**
 * This is the main() method which is called from the command-line.
 * Return code 0 means success. Any other values means some sort of error occurred.
 */
int main(const int argc, const char **argv) {
    // Assume no extra digits (unless overridden later.
    int extraDigits = 0;

    // If XYZ is added to -b, -r or -g, print x, y, z coordinates
    int useXYZ = 0;

    // Provide usage message if no arguments specified.
    const char *appName = argv[0];
    selfCheckEnabled = (strstr(appName, "debug") != 0);
    if (selfCheckEnabled) {
        fprintf(stderr, "(debug mode: self checking enabled)\n");
    }
    if (argc < 2) {
        usage(appName);
        return NORMAL_ERROR;
    }

    // First argument: command.
    const char *cmd = argv[1];
    if ((strcmp(cmd, "-d") == 0) || (strcmp(cmd, "--decode") == 0)) {

        // ------------------------------------------------------------------
        // Decode: [-d | --decode] <default-territory> <mapcode> [<mapcode> ...]
        // ------------------------------------------------------------------
        if (argc < 4) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }

        const char *defaultTerritory = argv[2];
        double lat;
        double lon;

        // Get the territory context.
        enum Territory context = getTerritoryCode(defaultTerritory, TERRITORY_NONE);

        // Decode every Mapcode.
        for (int i = 3; i < argc; ++i) {

            // Decode the Mapcode to a lat/lon.
            const char *mapcode = argv[i];
            int err = decodeMapcodeToLatLonUtf8(&lat, &lon, mapcode, context, NULL);
            if (err != 0) {
                fprintf(stderr, "error: cannot decode '%s %s'\n", defaultTerritory, mapcode);
                return NORMAL_ERROR;
            }

            // Output the decoded lat/lon.
            printf("%.20g %.20g\n", lat, lon);

            // Self-checking code to see if encoder produces this Mapcode for the lat/lon.
            if (selfCheckEnabled) {
                const char *suffix = strstr(mapcode, "-");
                extraDigits = 0;
                if (suffix != 0) {
                    extraDigits = (int) (strlen(suffix) - 1);
                }
                selfCheckLatLonToMapcode(lat, lon, mapcode, extraDigits);
            }
        }
    } else if ((strcmp(cmd, "-e") == 0) || (strcmp(cmd, "-e0") == 0) ||
               (strcmp(cmd, "-e1") == 0) || (strcmp(cmd, "-e2") == 0) ||
               (strcmp(cmd, "-e3") == 0) || (strcmp(cmd, "-e4") == 0) ||
               (strcmp(cmd, "-e5") == 0) || (strcmp(cmd, "-e6") == 0) ||
               (strcmp(cmd, "-e7") == 0) || (strcmp(cmd, "-e8") == 0) ||
               (strcmp(cmd, "--encode") == 0) || (strcmp(cmd, "--encode0") == 0) ||
               (strcmp(cmd, "--encode1") == 0) || (strcmp(cmd, "--encode2") == 0) ||
               (strcmp(cmd, "--encode3") == 0) || (strcmp(cmd, "--encode4") == 0) ||
               (strcmp(cmd, "--encode5") == 0) || (strcmp(cmd, "--encode5") == 0) ||
               (strcmp(cmd, "--encode7") == 0) || (strcmp(cmd, "--encode8") == 0)) {

        // ------------------------------------------------------------------
        // Encode: [-e[0-8] | --encode[0-8]] <lat:-90..90> <lon:-180..180> [territory]>
        // ------------------------------------------------------------------
        if ((argc != 4) && (argc != 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if ((!isdigit(*argv[2]) && (*argv[2] != '-')) || (!isdigit(*argv[3]) && (*argv[3] != '-'))) {
            fprintf(stderr, "error: latitude and longitude must be numeric\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        const double lat = atof(argv[2]);
        const double lon = atof(argv[3]);

        if (strstr(cmd, "-e1") || strstr(cmd, "--encode1")) {
            extraDigits = 1;
        } else if (strstr(cmd, "-e2") || strstr(cmd, "--encode2")) {
            extraDigits = 2;
        } else if (strstr(cmd, "-e3") || strstr(cmd, "--encode3")) {
            extraDigits = 3;
        } else if (strstr(cmd, "-e4") || strstr(cmd, "--encode4")) {
            extraDigits = 4;
        } else if (strstr(cmd, "-e5") || strstr(cmd, "--encode5")) {
            extraDigits = 5;
        } else if (strstr(cmd, "-e6") || strstr(cmd, "--encode6")) {
            extraDigits = 6;
        } else if (strstr(cmd, "-e7") || strstr(cmd, "--encode7")) {
            extraDigits = 7;
        } else if (strstr(cmd, "-e8") || strstr(cmd, "--encode8")) {
            extraDigits = 8;
        } else {
            extraDigits = 0;
        }

        // Get territory context.
        enum Territory context = TERRITORY_NONE;
        const char *defaultTerritory = "AAA";
        if (argc == 5) {
            context = getTerritoryCode(argv[4], TERRITORY_NONE);
            defaultTerritory = argv[4];
        }

        // Encode the lat/lon to a set of Mapcodes.
        Mapcodes mapcodes;
        const int nrResults = encodeLatLonToMapcodes(&mapcodes, lat, lon, context, extraDigits);
        if (nrResults <= 0) {
            fprintf(stderr, "error: cannot encode lat=%.20g, lon=%.20g (default territory=%s)\n",
                    lat, lon, defaultTerritory);
            return NORMAL_ERROR;
        }

        // Output the Mapcode.
        for (int i = 0; i < nrResults; ++i) {
            const char *foundMapcode = mapcodes.mapcode[i];
            printf("%s\n", foundMapcode);

            // Self-checking code to see if decoder produces the lat/lon for all of these Mapcodes.
            if (selfCheckEnabled) {
                selfCheckMapcodeToLatLon(foundMapcode, lat, lon);
            }
        }
    } else if ((strcmp(cmd, "-t") == 0) ||
               (strcmp(cmd, "--territories") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode territories
        // ------------------------------------------------------------------
        if ((argc < 2) || (argc > 2)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        printf("ccode,territorycodes(pipe-separated),alphabets(pipe-seperated),names(pipe-separated)\n");
        for (int i = _TERRITORY_MIN + 1; i < _TERRITORY_MAX; ++i) {
            const enum Territory ccode = (enum Territory) i;
            char territoryName[MAX_MAPCODE_RESULT_LEN];
            printf("%d,", INDEX_OF_TERRITORY(i));

            // Use internal knowledge of ALPHA_SEARCH to show aliases of territoryName.
            printf("%s", getTerritoryIsoName(territoryName, ccode, 0));
            for (int a = 0; a < NR_TERRITORY_RECS; a++) {
                if (ALPHA_SEARCH[a].territory == ccode) {
                    char fullcode[16];
                    strcpy(fullcode, ALPHA_SEARCH[a].alphaCode);
                    if (fullcode[0] >= '0' && fullcode[0] <= '9') {
                        static const char *parents2 = "US,IN,CA,AU,MX,BR,RU,CN,";
                        int p = (fullcode[0] - '0');
                        memcpy(fullcode, &parents2[p * 3 - 3], 2);
                        fullcode[2] = '-';
                        strcpy(fullcode + 3, ALPHA_SEARCH[a].alphaCode + 1);
                    }
                    if (strcmp(fullcode, territoryName) != 0) {
                        printf("|%s", fullcode);
                    }
                }
            }
            printf(",");

            // Print alphabets.
            const TerritoryAlphabets *territoryAlphabets = getAlphabetsForTerritory(ccode);
            for (int j = 0; j < territoryAlphabets->count; j++) {
                if (j > 0) {
                    printf("|");
                }
                printf("%d", territoryAlphabets->alphabet[j]);
            }
            printf(",");

            // Use internal knowledge of TERRITORY_FULL_NAME to show aliases of full territory name.
            char *names = strdup(TERRITORY_FULL_NAME[INDEX_OF_TERRITORY(ccode)]);
            char *s = names;
            while (s) {
                if (s != names) {
                    printf("|");
                }
                char *e = strstr(s, " (");
                if (e) {
                    *e = 0;
                    if (e[-1] == ')') {
                        e[-1] = 0;
                    }
                    printf("%s", s);
                    s = e + 2;
                } else {
                    e = s + strlen(s);
                    if (e[-1] == ')') {
                        e[-1] = 0;
                    }
                    printf("%s", s);
                    s = NULL;
                }
            }
            printf("\n");
        }
    } else if ((strcmp(cmd, "-a") == 0) ||
               (strcmp(cmd, "--alphabets") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode territories
        // ------------------------------------------------------------------
        static const char *mapcodeForCSV[] = {
                // all characters
                "89.EU",
                "00.0A",
                "BCDF.GHJK",
                "LMNP.QRST",
                "VWXY.Z123",
                "4567.890B",
                // all forms
                "pq.xy",
                "pq.xyz",
                "pqx.yz",
                "pq.rxyz",
                "pqr.xyz",
                "pqrx.yz",
                "pqr.sxyz",
                "pqrs.xyz",
                "pqrs.txyz",
                "pqrst.vxyz",
                // all adjad forms
                "p1.xy",
                "pq.2y",
                "3q.x4",
                "5q.6y",
                "pq.1yz",
                "pq1.yz",
                "p2.x3z",
                "p2x.3z",
                "pq.1xy2",
                "pq1.xy2",
                "pq1x.y2",
                "p3.rx4z",
                "p3r.x4z",
                "p3rx.4z",
                "5q.r6y7",
                "5qr.6y7",
                "5qr6.y7",
                "pq1.sx2z",
                "pq1s.x2z",
                "p3r.s4yz",
                "p3rs.4yz",
                "5qr.6xy7",
                "5qr6.xy7",
                "8q9.sx0z",
                "8q9s.x0z",
                "1qr2.tx3z",
                "p4rs.5xy6",
                "p7r8.t9y0",
                "pq1st.2xy3",
                "p4rs5.vx6z",
                "7qr8t.v9yz",
                "p1r2t.3x4z",
                "5q6s7.v8y9",
                // non-mapcode
                "^0123456789!@#$^&*()/:;[]{}<>?|~%",
                "abcdefghijklmnopqrstuvwxyz",
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                // special case for digit-like characters
                "OI.xx",
                "oi.xx",
                "oi.xx-oooooooo",
                "oi.xx-iiiiiiii",
                "PQ.RS-01234567",
                "PQ.RS-890",
                NULL
        };
        if ((argc < 2) || (argc > 2)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }

        printf("alphabetNr,MapcodeInRoman,MapcodeInAlphabet\n");
        for (enum Alphabet alphabet = ALPHABET_ROMAN;
             alphabet < _ALPHABET_MAX; alphabet = (enum Alphabet) (alphabet + 1)) {
            int variant;
            for (variant = 0; variant <= 2; variant++) {
                int m;
                for (m = 0; mapcodeForCSV[m] != NULL; m++) {
                    int i;
                    char asciiString[128];
                    // build a mapcode variant
                    char mapcode[128];
                    strcpy(mapcode, mapcodeForCSV[m]);
                    strcat(mapcode, (variant == 1) ? "-bc" : (variant == 2) ? "-DFGHJKLM" : "");
                    for (i = 0; mapcode[i]; ++i) {
                        mapcode[i] = (char) toupper((int) mapcode[i]);
                    }
                    // convert to alphabet, and back to roman
                    convertMapcodeToAlphabetUtf8(asciiString, mapcode, alphabet);
                    // output a line of csv (in utf8 format)
                    printf("%d,%s,%s\n", alphabet, mapcode, asciiString);
                }
            }
        }
    } else if ((strcmp(cmd, "-b") == 0) || (strcmp(cmd, "-bXYZ") == 0) ||
               (strcmp(cmd, "--boundaries") == 0) || (strcmp(cmd, "--boundariesXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode boundaries.
        // ------------------------------------------------------------------
        if ((argc < 2) || (argc > 3)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc == 3) {
            extraDigits = atoi(argv[2]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        resetStatistics(MAPCODE_BOUNDARY_MAX);
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double minLon;
            double maxLon;
            double minLat;
            double maxLat;
            double lat;
            double lon;

            const TerritoryBoundary *mm = TERRITORY_BOUNDARY(i);
            minLon = ((double) mm->minx) / 1.0E6;
            maxLon = ((double) mm->maxx) / 1.0E6;
            minLat = ((double) mm->miny) / 1.0E6;
            maxLat = ((double) mm->maxy) / 1.0E6;

            // Try center.
            lat = (maxLat - minLat) / 2.0;
            lon = (maxLon - minLon) / 2.0;
            generateAndOutputMapcodes(lat, lon, 0, extraDigits, useXYZ);

            // Try corners.
            generateAndOutputMapcodes(minLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat, maxLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, maxLon, 0, extraDigits, useXYZ);

            // Try JUST inside.
            const double d = 0.000001;
            generateAndOutputMapcodes(minLat + d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat + d, maxLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, maxLon - d, 0, extraDigits, useXYZ);

            // Try JUST outside.
            generateAndOutputMapcodes(minLat - d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat - d, maxLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, maxLon + d, 0, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    } else if ((strcmp(cmd, "-g") == 0) || (strcmp(cmd, "-gXYZ") == 0) ||
               (strcmp(cmd, "--grid") == 0) || (strcmp(cmd, "--gridXYZ") == 0) ||
               (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "-rXYZ") == 0) ||
               (strcmp(cmd, "--random") == 0) || (strcmp(cmd, "--randomXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate grid test set:    [-g | --grid]   <nrOfPoints> [<extradigits>]
        // Generate uniform test set: [-r | --random] <nrOfPoints> [<seed>]
        // ------------------------------------------------------------------
        if ((argc < 3) || (argc > 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        int nrOfPoints = atoi(argv[2]);
        if (nrOfPoints < 1) {
            fprintf(stderr, "error: total number of points to generate must be >= 1\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc >= 4) {
            extraDigits = atoi(argv[3]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        int random = (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "--random") == 0);
        if (random) {
            if (argc == 5) {
                const int seed = atoi(argv[4]);
                srand((unsigned int) seed);
            } else {
                srand((unsigned int) time(0));
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        // Statistics.
        resetStatistics(nrOfPoints);

        int gridX = 0;
        int gridY = 0;
        int line = my_round(sqrt((double) totalNrOfPoints));
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double lat;
            double lon;
            double unit1;
            double unit2;

            if (random) {
                unit1 = ((double) rand()) / RAND_MAX;
                unit2 = ((double) rand()) / RAND_MAX;
            } else {
                unit1 = ((double) gridX) / line;
                unit2 = ((double) gridY) / line;

                if (gridX < line) {
                    ++gridX;
                } else {
                    gridX = 0;
                    ++gridY;
                }
            }

            unitToLatLonDeg(unit1, unit2, &lat, &lon);
            generateAndOutputMapcodes(lat, lon, 1, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    } else {

        // ------------------------------------------------------------------
        // Usage.
        // ------------------------------------------------------------------
        usage(appName);
        return NORMAL_ERROR;
    }
    return 0;
}
Ejemplo n.º 13
0
void Transform::expand(    CycleData& cyData, EventData& evData,
        map< string, WaveformTable>& wftMap,
        vector<string> pinList, double timescale) {

    assert( timescale >= 0.0);
    assert( timescale <= 1.0);

    if(timescale == 0.0) {
        //
        // Calculate timescale
        //
        vector<double> res;
        map<string, WaveformTable>::iterator iter;
        for(iter = wftMap.begin(); iter != wftMap.end(); iter++) {
            res.push_back( iter->second.getEventResolution());
        }
        double minRes = *(min_element( res.begin(), res.end()));
        double exponent = ceil( log10(1/minRes));
        timescale = pow( 10.0, -exponent);

        //applog.debug << "Calculating timescale : " << timescale << endl;
        //applog.debug << "minRes = " << minRes << " exponent = " << exponent << endl;

        assert( timescale >= 0.0);
        assert( timescale <= 1.0);
    }

    //if(debug)
        //cyData.print( applog.debug);

    SignalHeader signalHeader = cyData.getSignalHeader();

    vector<string> pinNames;
    for(unsigned int i=0; i < signalHeader.size(); i++) {
        pinNames.push_back( signalHeader[i].name);
    }

    evData.setSignalHeader( signalHeader);

    unsigned long numVectors = cyData.getNumVectors();

    unsigned long long periodBeginTimestamp = 0;
    unsigned long loopSum = 0;
    for(unsigned long vecNum=0; vecNum < numVectors; vecNum++) {
        CycleData::PeriodData periodData;
        cyData.getPeriodData( periodData, vecNum);


//        periodData.print( applog.debug);

        WaveformTable wft = wftMap[periodData.wftRef];
        double period = wft.period.value;

        // Need my_round due to fractional error
        unsigned long long periodTimestamp = (unsigned long long) my_round(period/timescale);

        EventData periodEventData;

        getEventData( periodData, wft, periodEventData, pinNames, timescale);

//        periodEventData.print( applog.debug);
        
        for(unsigned int i=0; i <= periodData.loopCount; i++) {
            // append event data
            //applog.debug << "Adding events at timestamp " << periodBeginTimestamp << endl;
            evData.add( periodEventData, periodBeginTimestamp);
//            periodBeginTimestamp = (unsigned long long) (((vecNum + 1 + loopSum + i)*period)/timescale);
            periodBeginTimestamp = (unsigned long long) ((vecNum + 1 + loopSum + i)*periodTimestamp);
        }
        loopSum += periodData.loopCount;
    }

    evData.setTimescale( timescale);
}
Ejemplo n.º 14
0
void merge_regions(/* Input */
                   int     *nn,   /* Number of bordering voxels per pair of regions. */
                   double  *pp,   /* Sum of phase differences along border between regions of pair. */
                   int     nc,    /* Length of list of region pairs. */
                   int     *rs,   /* Size (voxels) per region. */
                   int     nr,    /* Number of regions. */
                   /* Output */
                   int     *rw)   /* Multiple of 2pi wrap for each region. */
{
   double     k=0.0;                     /* Average multiple of 2pi phase difference between regions. */  
   double     *cc=NULL;                  /* Array of "mis-wrap-costs" for each connection. */
   double     maxcc = -FLT_MAX;          /* Current maximum cost. */
   int        l=0;                       /* Wrap when merging olbl with nlbl. */
   int        i=0, j=0, mi=0;            /* Some indicies. */
   int        ci=0, ci2=0;               /* Indexes into ii, jj, nn, pp and cc. */
   int        sign1=1, sign2=1;          /* Used to keep track of sign changes when wrapping. */
   int        cnc=0;                     /* Current remaining no of connections. */ 
   int        ocnc=0;                    /* Remaining no. of connections at start of current iteration. */
   int        row=0, col=0;              /* Row and column (two region labels) for current pair to merge. */
   int        olbl=0;                    /* Label numbers for current pair to */
   int        nlbl=0;                    /* merge such that nlbl+olbl->nlbl.  */
   int        olbli_n=0;                 /* Number of instances of olbl in row-list. */
   int        olblj_n=0;                 /* Number of instances of olbl in column-list. */
   int        *olbli=NULL;               /* List of indexes into ii such that ii[olbli[0:olbli_n-1]]==olbl */
   int        *olblj=NULL;               /* List of indexes into jj such that jj[olblj[0:olblj_n-1]]==olbl */
   int        *mlbli_n=NULL;             /* Number of instances of nlbl in row-list. */
   int        *mlblj_n=NULL;             /* Number of instances of nlbl in column-list. */
   int        **mlbli=NULL;              /* List of indexes into ii such that ii[nlbli[0:nlbli_n-1]]==nlbl */
   int        **mlblj=NULL;              /* List of indexes into jj such that jj[nlblj[0:nlblj_n-1]]==nlbl */
   int        *ii_ia=NULL, *jj_ia=NULL;  /* Index arrays for ii and jj. */
   int        *eqlist=NULL;              /* Equivalence list, indicating the region */
                                         /* i+1 is equivalent to eqlist[i]          */

   /*
   Allocate, initialise and sort index-arrays for 
   ii (row-array) and jj (column array) such that
   ii[ii_ia[:]] is sorted in ascending order as
   is jj[jj_ia[:]].
   */
   ii_ia = (int *) mxCalloc(nc,sizeof(int));
   jj_ia = (int *) mxCalloc(nc,sizeof(int));
   for (i=0; i<nc; i++) {ii_ia[i]=i; jj_ia[i]=i;}
   qsort(ii_ia,nc,sizeof(int),ii_cmp);
   qsort(jj_ia,nc,sizeof(int),jj_cmp);

   /*
   Initialise region-wrap and equivalence lists.
   */
   eqlist = (int *) mxCalloc(nr,sizeof(int));
   for (i=0; i<nr; i++) {rw[i] = 0; eqlist[i] = i+1;}

   /*
   Allocate memory for lists of pointers to stretches
   into ii_ia and jj_ia.
   */
   mlbli_n = (int *) mxCalloc(nc,sizeof(int));   
   mlblj_n = (int *) mxCalloc(nc,sizeof(int));   
   mlbli = (int **) mxCalloc(nc,sizeof(mlbli[0]));   
   mlblj = (int **) mxCalloc(nc,sizeof(mlblj[0]));   

   /*
   Make cc array that is used to determine
   what region pair to merge.
   */
   cc = (double *) mxCalloc(nc,sizeof(double));
   for (i=0; i<nc; i++)
   {
      k = -pp[i]/(2.0*PI*nn[i]);
      cc[i] = nn[i]*(0.5-fabs(k-floor(k+0.5)));
   }
 
   /*
   Go through loop as many times as there are regions, each
   time selecting one pair of regions to merge, and updating
   all statistics regarding connections to remaining regions.
   */
   cnc = nc;
   for (i=0; i<nr; i++)
   {
      ocnc = cnc;  /* Current no. of connections at start of loop. */

      /*
      Find index of next pair to merge.
      */
      for (j=0, mi=0, maxcc=0.0; j<nc; j++)
      {
         if (cc[j] > maxcc) {maxcc=cc[j]; mi=j;}
      }

      /*
      Find row and column of next pair to merge.
      */
      row = ii[mi]; 
      col = jj[mi];

      /*
      Determine which label to give the merged region
      and update region size stats.
      */
      nlbl = (rs[row-1] > rs[col-1]) ? row : col;
      olbl = (nlbl == row) ? col : row;
      rs[nlbl-1] = rs[row-1] + rs[col-1];
      rs[olbl-1] = 0;

      /*
      Determine if region should be wrapped before merging.
      */
      l = my_round(-pp[mi]/(2.0*PI*nn[mi]));

      /*
      Set wrapping for region olbl (and equivalent) in list, 
      and update equivalence list.
      */
      if (nlbl == row) {sign1 = -1;}
      else {sign1 = 1;}
      for (j=0; j<nr; j++)
      {
    if (eqlist[j] == olbl) 
        {
           rw[j] += sign1*l;
           eqlist[j] = nlbl;
        }
      }

      /*
      Find pointers to start of stretches of all pairs 
      that contain the old region as one party.
      */
      olbli = binsearch(ii,ii_ia,cnc,olbl,&olbli_n);
      olblj = binsearch(jj,jj_ia,cnc,olbl,&olblj_n);

      /*
      Find pointers to starts of stretches of all pairs
      that contain members that are somewhere paired
      with the "old" region. We have to do that here while
      ii_ia and jj_ia are still sorted.
      This would appear more complicated than searching
      for stretches containing nlbl, but hopefully it will
      mean that we do linear searches (in the loop below)
      in short lists, allowing us to do binary searches
      here (in the long list).
      */
      for (j=0; j<olbli_n; j++)
      {
     ci = olbli[j];
     if (jj[ci] < nlbl) /* Search in row-list. */
     {
        mlbli[j] = binsearch(ii,ii_ia,cnc,jj[ci],&(mlbli_n[j]));
         }
         else if (jj[ci] > nlbl) /* Search in column list. */
     {
        mlbli[j] = binsearch(jj,jj_ia,cnc,jj[ci],&(mlbli_n[j]));
         }
         else /* Paired with nlbl, skip it. */
     {
        mlbli[j] = NULL;
        mlbli_n[j] = 0;
         }
      }
      for (j=0; j<olblj_n; j++)
      {
     ci = olblj[j];
     if (ii[ci] < nlbl) /* Search in row-list. */
     {
        mlblj[j] = binsearch(ii,ii_ia,cnc,ii[ci],&(mlblj_n[j]));
         }
         else if (ii[ci] > nlbl) /* Search in column list. */
     {
        mlblj[j] = binsearch(jj,jj_ia,cnc,ii[ci],&(mlblj_n[j]));
         }
         else /* Paired with nlbl, skip it. */
     {
        mlblj[j] = NULL;
        mlblj_n[j] = 0;
         }
      }

      /*
      For each of these pairs we can consider three possible cases
      1. It is paired with the new label, and should be deleted.
      2. It is paired with a label that is also in a pair with
         the new label. In this case the stats for the pair
         'new label'-label should be updated and 'old label'-label
         be deleted.
      3. It is paired with a label that is NOT in a pair with
         the new label. In this case the stats for 'old label'-label
         should be transferred to a 'new label'-label pair and the 
         'old label'-label should be deleted.
      */
      /*
      First go through all instances where olbl is row index.
      */
      if (olbli)
      {
     sign2 = 1;
         for (j=0; j<olbli_n; j++)
         {
            ci = olbli[j];
        if (jj[ci] == nlbl)
            {
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            /* 
            Check if the label is currently paired up with nlbl.
            Remember that row index (ii) is always smaller than
            column index->we know where to look.
            */
            else if ((jj[ci] < nlbl) && mlbli[j] && ((ci2=linsearch(jj,mlbli[j],mlbli_n[j],nlbl))>-1))
            /*
            We found the label jj[ci] in the row-list matched with nlbl in the column list.
            Since olbl was in the row-list, this means we should sign-reverse sum of
            differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] -= pp[ci]; /* Third sign reversal. */
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else if ((jj[ci] > nlbl) && mlbli[j] && ((ci2=linsearch(ii,mlbli[j],mlbli_n[j],nlbl))>-1))
            /*
            We found label jj[ci] in the column-list matched with nlbl in the row list.
            Since olbl was also in the row-list, this means we should just add to sum of
            differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] += pp[ci];
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else
            /* 
            So, this label has not been mixed up with nlbl before. Well, it is now.
            */
            {
               if (jj[ci] < nlbl)
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  ii[ci] = jj[ci];
                  jj[ci] = nlbl;
                  pp[ci] *= -1.0;
               }
               else
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  ii[ci] = nlbl;
               }
            }
         }
      }
      /*
      Now go through list where olbl is column index.
      */
      if (olblj)
      {
     sign2 = -1;
         for (j=0; j<olblj_n; j++)
         {
            ci = olblj[j];
        if (ii[ci] == nlbl)
            {
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            /* 
            Check if the label is currently paired up with nlbl.
            Remember that row index (ii) is always smaller than
            column index->we know where to look.
            */
            else if ((ii[ci] < nlbl) && mlblj[j] && ((ci2=linsearch(jj,mlblj[j],mlblj_n[j],nlbl))>-1))
            /*
            We found the label ii[ci] in the row-list matched with nlbl in the column list.
            Since olbl was in the column-list, this means we should just add sum of
            differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] += pp[ci]; 
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else if ((ii[ci] > nlbl) && mlblj[j] && ((ci2=linsearch(ii,mlblj[j],mlblj_n[j],nlbl))>-1))
            /*
            We found label ii[ci] in the column-list matched with nlbl in the row list.
            Since olbl was also in the column-list, this means we should sign-reverse when
            adding to sum of differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] -= pp[ci]; /* Third sign reversal. */
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else
            /* 
            So, this label has not been mixed up with nlbl before. Well, it is now.
            */
            {
               if (ii[ci] < nlbl)
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  jj[ci] = nlbl;
               }
               else
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  jj[ci] = ii[ci];
                  ii[ci] = nlbl;
                  pp[ci] *= -1.0;
               }
            }
         }
      }
      if (!cnc) {break;} /* No more connections, we're done. */
      /*
      Resort index arrays ii_ia and jj_ia. Connections that are
      no longer valid have been given ii and jj values of INT_MAX,
      which means they will be out at the end of the ii_ia and jj_ia
      arrays, and will not be considered in subsequent iterations.
      */
      if ((ocnc-cnc) == 1)
      /*
      A large proportion of mergings involve merging of regions
      that have connections only with the current nlbl. Clearly
      we can do much better than a full quicksort for those cases.
      */
      {
     sillysort(ii_ia,jj_ia,ocnc);
      }
      else
      {
         qsort(ii_ia,ocnc,sizeof(int),ii_cmp);
         qsort(jj_ia,ocnc,sizeof(int),jj_cmp);
      }

      /*      return; */
   }

   mxFree(cc);
   mxFree(ii_ia);
   mxFree(jj_ia);   
   mxFree(mlbli_n);
   mxFree(mlblj_n);
   mxFree(mlbli);
   mxFree(mlblj);
   return;
}
void FaceTrackingRenderer3D::DrawLandmark(PXCFaceData::Face* trackedFace)
{
	const PXCFaceData::LandmarksData *landmarkData = trackedFace->QueryLandmarks();

	if (!landmarkData)
		return;

	HWND panelWindow = GetDlgItem(m_window, IDC_PANEL);
	HDC dc1 = GetDC(panelWindow);
	HDC dc2 = CreateCompatibleDC(dc1);

	if (!dc2) 
	{
		ReleaseDC(panelWindow, dc1);
		return;
	}

	HFONT hFont = CreateFont(16, 8, 0, 0, FW_BOLD, 0, 0, 0, 0, 0, 0, 2, 0, L"MONOSPACE");

	if (!hFont)
	{
		DeleteDC(dc2);
		ReleaseDC(panelWindow, dc1);
		return;
	}

	SetBkMode(dc2, TRANSPARENT);

	SelectObject(dc2, m_bitmap);
	SelectObject(dc2, hFont);

	BITMAP bitmap;
	GetObject(m_bitmap, sizeof(bitmap), &bitmap);

	pxcI32 numPoints = landmarkData->QueryNumPoints();
	if (numPoints != m_numLandmarks)
	{
		DeleteObject(hFont);
		DeleteDC(dc2);
		ReleaseDC(panelWindow, dc1);
		return;
	}

	PXCFaceData::LandmarkPoint* points = new PXCFaceData::LandmarkPoint[numPoints];

	for (int l = 0; l < numPoints; l++) //initialize Array
	{
		points[l].world.x = 0.0;
		points[l].world.y = 0.0;
		points[l].world.z = 0.0;
	}

	landmarkData->QueryPoints(points); //data set for all landmarks in frame

	//convert depth data is to millimeters
	for (int l = 0; l < numPoints; l++)
	{
		points[l].world.x *= 1000.0f;
		points[l].world.y *= 1000.0f;
		points[l].world.z *= 1000.0f;
	}

	for (int j = 0; j < numPoints; j++)
	{
		double ix = 0, iy = 0;

		if(ProjectVertex(points[j].world, ix, iy, 1))
		{
			if (points[j].confidenceWorld > 0)
			{
				DrawPoint(dc2, RGB(255, 255, 0), my_round(ix), my_round(iy), 3);
			}
			else
			{
				DrawPoint(dc2, RGB(255, 0, 0), my_round(ix), my_round(iy), 3);
			}
		}
	}
		
	if (points) delete[] points;

	DeleteObject(hFont);
	DeleteDC(dc2);
	ReleaseDC(panelWindow, dc1);
}
void FaceTrackingRenderer3D::DrawPose(PXCFaceData::Face* trackedFace)
{
	HWND panelWindow = GetDlgItem(m_window, IDC_PANEL);
	HDC dc1 = GetDC(panelWindow);
	HDC dc2 = CreateCompatibleDC(dc1);

	if (!dc2) 
	{
		ReleaseDC(panelWindow, dc1);
		return;
	}

	HFONT hFont = CreateFont(28, 18, 0, 0, FW_BOLD, 0, 0, 0, 0, 0, 0, 2, 0, L"MONOSPACE");

	if (!hFont)
	{
		DeleteDC(dc2);
		ReleaseDC(panelWindow, dc1);
		return;
	}

	SetBkMode(dc2, TRANSPARENT);

	SelectObject(dc2, m_bitmap);
	SelectObject(dc2, hFont);

	BITMAP bitmap;
	GetObject(m_bitmap, sizeof(bitmap), &bitmap);

	const PXCFaceData::PoseData *poseData = trackedFace->QueryPose();

	if(poseData == NULL)
	{
		DeleteObject(hFont);
		DeleteDC(dc2);
		ReleaseDC(panelWindow, dc1);
		return;
	}
	PXCFaceData::HeadPosition outFaceCenterPoint;
	poseData->QueryHeadPosition(&outFaceCenterPoint);
	if (outFaceCenterPoint.confidence == 0)
	{
		DeleteObject(hFont);
		DeleteDC(dc2);
		ReleaseDC(panelWindow, dc1);
		return;
	}

	double headCenter_x = 0, headCenter_y = 0;	
	if(ProjectVertex(outFaceCenterPoint.headCenter, headCenter_x, headCenter_y, 2))
	{
		if(poseData->QueryConfidence() > 0 && outFaceCenterPoint.confidence > 0)
		{
			DrawPoint(dc2, RGB(0, 0, 255), my_round(headCenter_x), my_round(headCenter_y), 8);
		}
	
		const PXCFaceData::LandmarksData *landmarkData = trackedFace->QueryLandmarks();

		if (!landmarkData)
		{
			DeleteObject(hFont);
			DeleteDC(dc2);
			ReleaseDC(panelWindow, dc1);
			return;
		}

		PXCFaceData::LandmarkPoint* points = new PXCFaceData::LandmarkPoint[landmarkData->QueryNumPoints()];
		landmarkData->QueryPoints(points); //data set for all landmarks in frame

		points[29].world.x *= 1000.0f;
		points[29].world.y *= 1000.0f;
		points[29].world.z *= 1000.0f;

		double noseTip_x = 0, noseTip_y = 0;

		if(ProjectVertex(points[29].world, noseTip_x, noseTip_y, 1))
		{
			PXCPoint3DF32 direction;
			direction.x = (float)(noseTip_x - headCenter_x);
			direction.y = (float)(noseTip_y - headCenter_y);
			
			HPEN lineColor;
			
			if (poseData->QueryConfidence() > 0)
			{
				lineColor = CreatePen(PS_SOLID, 3, RGB(0 ,255 ,255));
			}
			else
			{
				lineColor = CreatePen(PS_SOLID, 3, RGB(255 ,0 , 0));
			}

			if (!lineColor)
			{
				DeleteObject(hFont);
				DeleteDC(dc2);
				ReleaseDC(panelWindow, dc1);
				return;
			}
			SelectObject(dc2, lineColor);

			MoveToEx(dc2, my_round(noseTip_x), my_round(noseTip_y), 0);
			LineTo(dc2, my_round(noseTip_x + 1.2 * direction.x), my_round(noseTip_y + 1.2 * direction.y));

			DeleteObject(lineColor);
		}
	}
	
	DeleteObject(hFont);
	DeleteDC(dc2);
	ReleaseDC(panelWindow, dc1);
}
void FaceTrackingRenderer3D::DrawBitmap(PXCCapture::Sample* sample, bool ir)
{
	PXCImage *imageDepth = sample->depth;
	assert(imageDepth);
	PXCImage::ImageInfo imageDepthInfo = imageDepth->QueryInfo();

	m_outputImageInfo.width = 1024;
	m_outputImageInfo.height = 1024;
	m_outputImageInfo.format = PXCImage::PIXEL_FORMAT_RGB32;
	m_outputImageInfo.reserved = 0;

	m_outputImage = m_session->CreateImage(&m_outputImageInfo);
	assert(m_outputImage);

	PXCImage::ImageData imageDepthData;
	if (imageDepth->AcquireAccess(PXCImage::ACCESS_READ, PXCImage::PIXEL_FORMAT_RGB32, &imageDepthData) >= PXC_STATUS_NO_ERROR)
	{
		memset(&m_outputImageData, 0, sizeof(m_outputImageData));
		pxcStatus status = m_outputImage->AcquireAccess(PXCImage::ACCESS_WRITE, PXCImage::PIXEL_FORMAT_RGB32, &m_outputImageData);
		if (status < PXC_STATUS_NO_ERROR) return;

		int stridePixels = m_outputImageData.pitches[0];
		pxcBYTE *pixels = reinterpret_cast<pxcBYTE*> (m_outputImageData.planes[0]);
		memset(pixels, 0, stridePixels * m_outputImageInfo.height);

		// get access to depth data
		PXCPoint3DF32* vertices = new PXCPoint3DF32[imageDepthInfo.width * imageDepthInfo.height];
		PXCProjection* projection(m_senseManager->QueryCaptureManager()->QueryDevice()->CreateProjection());
		if (!projection)
		{
			if (vertices) delete[] vertices;
			return;
		}

		projection->QueryVertices(imageDepth, vertices);
		projection->Release();
		int strideVertices = imageDepthInfo.width;

		// render vertices
		int numVertices = 0;
		for (int y = 0; y < imageDepthInfo.height; y++)
		{
			const PXCPoint3DF32 *verticesRow = vertices + y * strideVertices;
			for (int x = 0; x < imageDepthInfo.width; x++)
			{
				const PXCPoint3DF32 &v = verticesRow[x];
				if (v.z <= 0.0f)
				{
					continue;
				}

				double ix = 0, iy = 0;
				if (ProjectVertex(v, ix, iy))
				{
					pxcBYTE *ptr = m_outputImageData.planes[0];
					ptr += my_round(iy) * m_outputImageData.pitches[0];
					ptr += my_round(ix) * 4;
					ptr[0] = pxcBYTE(255.0f * 0.5f);
					ptr[1] = pxcBYTE(255.0f * 0.5f);
					ptr[2] = pxcBYTE(255.0f * 0.5f);
					ptr[3] = pxcBYTE(255.0f);
				}

				numVertices++;
			}
		}
		if (vertices) delete[] vertices;

		if (m_bitmap)
		{
			DeleteObject(m_bitmap);
			m_bitmap = 0;
		}

		HWND hwndPanel = GetDlgItem(m_window, IDC_PANEL);
		HDC dc = GetDC(hwndPanel);
		BITMAPINFO binfo;
		memset(&binfo, 0, sizeof(binfo));
		binfo.bmiHeader.biWidth = m_outputImageData.pitches[0] / 4;
		binfo.bmiHeader.biHeight = -(int)m_outputImageInfo.height;
		binfo.bmiHeader.biBitCount = 32;
		binfo.bmiHeader.biPlanes = 1;
		binfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		binfo.bmiHeader.biCompression = BI_RGB;
		Sleep(1);
		m_bitmap = CreateDIBitmap(dc, &binfo.bmiHeader, CBM_INIT, m_outputImageData.planes[0], &binfo, DIB_RGB_COLORS);

		ReleaseDC(hwndPanel, dc);

		m_outputImage->ReleaseAccess(&m_outputImageData);
		imageDepth->ReleaseAccess(&imageDepthData);
		m_outputImage->Release();
	}
}
Ejemplo n.º 18
0
void CAdaptiveParameterCalculator::onParametersChanged()
{
	CParameterObject::onParametersChanged();
	functionKind = my_round(getParameter("APFunction"));
}
Ejemplo n.º 19
0
/**
 * This is the main() method which is called from the command-line.
 * Return code 0 means success. Any other values means some sort of error occurred.
 */
int main(const int argc, const char **argv) {
    // Assume no extra digits (unless overridden later.
    int extraDigits = 0;

    // If XYZ is added to -b, -r or -g, print x, y, z coordinates
    int useXYZ = 0;

    // Provide usage message if no arguments specified.
    const char *appName = argv[0];
    selfCheckEnabled = (strstr(appName, "debug") != 0);
    if (selfCheckEnabled) {
        fprintf(stderr, "(debug mode: self checking enabled)\n");
    }
    if (argc < 2) {
        usage(appName);
        return NORMAL_ERROR;
    }

    // First argument: command.
    const char *cmd = argv[1];
    if ((strcmp(cmd, "-d") == 0) || (strcmp(cmd, "--decode") == 0)) {

        // ------------------------------------------------------------------
        // Decode: [-d | --decode] <default-territory> <mapcode> [<mapcode> ...]
        // ------------------------------------------------------------------
        if (argc < 4) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }

        const char *defaultTerritory = argv[2];
        double lat;
        double lon;

        // Get the territory context.
        int context = convertTerritoryIsoNameToCode(defaultTerritory, 0);

        // Decode every Mapcode.
        for (int i = 3; i < argc; ++i) {

            // Decode the Mapcode to a lat/lon.
            const char *mapcode = argv[i];
            int err = decodeMapcodeToLatLon(&lat, &lon, mapcode, context);
            if (err != 0) {
                fprintf(stderr, "error: cannot decode '%s %s'\n", defaultTerritory, mapcode);
                return NORMAL_ERROR;
            }

            // Output the decoded lat/lon.
            printf("%.12g %.12g\n", lat, lon);

            // Self-checking code to see if encoder produces this Mapcode for the lat/lon.
            if (selfCheckEnabled) {
                const char *suffix = strstr(mapcode, "-");
                extraDigits = 0;
                if (suffix != 0) {
                    extraDigits = (int) (strlen(suffix) - 1);
                }
                selfCheckLatLonToMapcode(lat, lon, defaultTerritory, mapcode, extraDigits);
            }
        }
    }
    else if ((strcmp(cmd, "-e") == 0) || (strcmp(cmd, "-e0") == 0) ||
             (strcmp(cmd, "-e1") == 0) || (strcmp(cmd, "-e2") == 0) ||
             (strcmp(cmd, "-e3") == 0) || (strcmp(cmd, "-e4") == 0) ||
             (strcmp(cmd, "-e5") == 0) || (strcmp(cmd, "-e6") == 0) ||
             (strcmp(cmd, "-e7") == 0) || (strcmp(cmd, "-e8") == 0) ||
             (strcmp(cmd, "--encode") == 0) || (strcmp(cmd, "--encode0") == 0) ||
             (strcmp(cmd, "--encode1") == 0) || (strcmp(cmd, "--encode2") == 0) ||
             (strcmp(cmd, "--encode3") == 0) || (strcmp(cmd, "--encode4") == 0) ||
             (strcmp(cmd, "--encode5") == 0) || (strcmp(cmd, "--encode5") == 0) ||
             (strcmp(cmd, "--encode7") == 0) || (strcmp(cmd, "--encode8") == 0)) {

        // ------------------------------------------------------------------
        // Encode: [-e[0-8] | --encode[0-8]] <lat:-90..90> <lon:-180..180> [territory]>
        // ------------------------------------------------------------------
        if ((argc != 4) && (argc != 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if ((!isdigit(*argv[2]) && (*argv[2] != '-')) || (!isdigit(*argv[3]) && (*argv[3] != '-'))) {
            fprintf(stderr, "error: latitude and longitude must be numeric\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        const double lat = atof(argv[2]);
        const double lon = atof(argv[3]);

        if (strstr(cmd, "-e1") || strstr(cmd, "--encode1")) {
            extraDigits = 1;
        }
        else if (strstr(cmd, "-e2") || strstr(cmd, "--encode2")) {
            extraDigits = 2;
        }
        else if (strstr(cmd, "-e3") || strstr(cmd, "--encode3")) {
            extraDigits = 3;
        }
        else if (strstr(cmd, "-e4") || strstr(cmd, "--encode4")) {
            extraDigits = 4;
        }
        else if (strstr(cmd, "-e5") || strstr(cmd, "--encode5")) {
            extraDigits = 5;
        }
        else if (strstr(cmd, "-e6") || strstr(cmd, "--encode6")) {
            extraDigits = 6;
        }
        else if (strstr(cmd, "-e7") || strstr(cmd, "--encode7")) {
            extraDigits = 7;
        }
        else if (strstr(cmd, "-e8") || strstr(cmd, "--encode8")) {
            extraDigits = 8;
        }
        else {
            extraDigits = 0;
        }

        // Get territory context.
        int context = 0;
        const char *defaultTerritory = "AAA";
        if (argc == 5) {
            context = convertTerritoryIsoNameToCode(argv[4], 0);
            defaultTerritory = argv[4];
        }

        // Encode the lat/lon to a set of Mapcodes.
        char *results[2 * MAX_NR_OF_MAPCODE_RESULTS];
        const int nrResults = encodeLatLonToMapcodes_Deprecated(results, lat, lon, context, extraDigits);
        if (nrResults <= 0) {
            fprintf(stderr, "error: cannot encode lat=%.12g, lon=%.12g (default territory=%s)\n",
                    lat, lon, defaultTerritory);
            return NORMAL_ERROR;
        }

        // Output the Mapcode.
        for (int i = 0; i < nrResults; ++i) {
            const char *foundMapcode = results[(i * 2)];
            const char *foundTerritory = results[(i * 2) + 1];
            printf("%s %s\n", foundTerritory, foundMapcode);

            // Self-checking code to see if decoder produces the lat/lon for all of these Mapcodes.
            if (selfCheckEnabled) {
                selfCheckMapcodeToLatLon(foundTerritory, foundMapcode, lat, lon);
            }
        }
    }
    else if ((strcmp(cmd, "-b") == 0) || (strcmp(cmd, "-bXYZ") == 0) ||
             (strcmp(cmd, "--boundaries") == 0) || (strcmp(cmd, "--boundariesXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate a test set based on the Mapcode boundaries.
        // ------------------------------------------------------------------
        if ((argc < 2) || (argc > 3)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc == 3) {
            extraDigits = atoi(argv[2]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        resetStatistics(NR_BOUNDARY_RECS);
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double minLon;
            double maxLon;
            double minLat;
            double maxLat;
            double lat;
            double lon;

            const mminforec *mm = boundaries(i);
            minLon = ((double) mm->minx) / 1.0E6;
            maxLon = ((double) mm->maxx) / 1.0E6;
            minLat = ((double) mm->miny) / 1.0E6;
            maxLat = ((double) mm->maxy) / 1.0E6;

            // Try center.
            lat = (maxLat - minLat) / 2.0;
            lon = (maxLon - minLon) / 2.0;
            generateAndOutputMapcodes(lat, lon, 0, extraDigits, useXYZ);

            // Try corners.
            generateAndOutputMapcodes(minLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat, maxLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, minLon, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat, maxLon, 0, extraDigits, useXYZ);

            // Try JUST inside.
            const double d = 0.000001;
            generateAndOutputMapcodes(minLat + d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat + d, maxLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, minLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat - d, maxLon - d, 0, extraDigits, useXYZ);

            // Try JUST outside.
            generateAndOutputMapcodes(minLat - d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(minLat - d, maxLon + d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, minLon - d, 0, extraDigits, useXYZ);
            generateAndOutputMapcodes(maxLat + d, maxLon + d, 0, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    }
    else if ((strcmp(cmd, "-g") == 0) || (strcmp(cmd, "-gXYZ") == 0) ||
             (strcmp(cmd, "--grid") == 0) || (strcmp(cmd, "--gridXYZ") == 0) ||
             (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "-rXYZ") == 0) ||
             (strcmp(cmd, "--random") == 0) || (strcmp(cmd, "--randomXYZ") == 0)) {

        // ------------------------------------------------------------------
        // Generate grid test set:    [-g | --grid]   <nrOfPoints> [<extradigits>]
        // Generate uniform test set: [-r | --random] <nrOfPoints> [<seed>]
        // ------------------------------------------------------------------
        if ((argc < 3) || (argc > 5)) {
            fprintf(stderr, "error: incorrect number of arguments\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        int nrOfPoints = atoi(argv[2]);
        if (nrOfPoints < 1) {
            fprintf(stderr, "error: total number of points to generate must be >= 1\n\n");
            usage(appName);
            return NORMAL_ERROR;
        }
        if (argc >= 4) {
            extraDigits = atoi(argv[3]);
            if ((extraDigits < 0) || (extraDigits > 8)) {
                fprintf(stderr, "error: parameter extraDigits must be in [0..8]\n\n");
                usage(appName);
                return NORMAL_ERROR;
            }
        }
        int random = (strcmp(cmd, "-r") == 0) || (strcmp(cmd, "--random") == 0);
        if (random) {
            if (argc == 5) {
                const int seed = atoi(argv[4]);
                srand((unsigned int) seed);
            }
            else {
                srand((unsigned int) time(0));
            }
        }
        useXYZ = (strstr(cmd, "XYZ") != 0);

        // Statistics.
        resetStatistics(nrOfPoints);

        int gridX = 0;
        int gridY = 0;
        int line = my_round(sqrt((double) totalNrOfPoints));
        for (int i = 0; i < totalNrOfPoints; ++i) {
            double lat;
            double lon;
            double unit1;
            double unit2;

            if (random) {
                unit1 = ((double) rand()) / RAND_MAX;
                unit2 = ((double) rand()) / RAND_MAX;
            }
            else {
                unit1 = ((double) gridX) / line;
                unit2 = ((double) gridY) / line;

                if (gridX < line) {
                    ++gridX;
                }
                else {
                    gridX = 0;
                    ++gridY;
                }
            }

            unitToLatLonDeg(unit1, unit2, &lat, &lon);
            generateAndOutputMapcodes(lat, lon, 1, extraDigits, useXYZ);

            if ((i % SHOW_PROGRESS) == 0) {
                showProgress(i);
            }
        }
        outputStatistics();
    }
    else {

        // ------------------------------------------------------------------
        // Usage.
        // ------------------------------------------------------------------
        usage(appName);
        return NORMAL_ERROR;
    }
    return 0;
}