Пример #1
0
void updateGraphics(void)
{
    int px;

    // update position of label
    labelHapticDeviceModel->setLocalPos(10, displayH - 30, 0.0);

    // update position of label and content
    double posX = 1000 * hapticDevicePosition.x();
    double posY = 1000 * hapticDevicePosition.y();
    double posZ = 1000 * hapticDevicePosition.z();

    labelHapticDevicePosition->setString("position [mm]: " + cStr(posX, 0) + " " +
                                         cStr(posY, 0) + " " +
                                         cStr(posZ, 0));

    labelHapticDevicePosition->setLocalPos(10, displayH - 50, 0.0);

    // update haptic rate label
    labelHapticRate->setString ("haptic rate: "+cStr(frequencyCounter.getFrequency(), 0) + " [Hz]");

    px = (int)(0.5 * (displayW - labelHapticRate->getWidth()));
    labelHapticRate->setLocalPos(px, 15);

    // render world
    camera->renderView(displayW, displayH);

    // swap buffers
    glutSwapBuffers();

    // check for any OpenGL errors
    GLenum err;
    err = glGetError();
    if (err != GL_NO_ERROR) printf("Error:  %s\n", gluErrorString(err));
}
Пример #2
0
String& String::append(const char* cb, size_t n)
{
    KEEPOLD;

    //
    // preconditions
    //

    if(cb == 0)
        strError("String::append", "InvalidArgument");

    //
    // operations
    //

    if(n == NPOS)
        n = strlen(cb);

    if(n > 0)
        doReplace(length(), 0, cb, n);

    //
    // post conditions
    //

    assert((OLD.length() + n) == length());
    assert(memcmp(cStr() + OLD.length(), cb, n) == 0);

    return *this;
}
Пример #3
0
QList<QColor> QgsServerParameterDefinition::toColorList( bool &ok, const char delimiter ) const
{
  ok = true;
  QList<QColor> colors;

  for ( const auto &part : toStringList( delimiter ) )
  {
    QString cStr( part );
    if ( !cStr.isEmpty() )
    {
      // support hexadecimal notation to define colors
      if ( cStr.startsWith( QLatin1String( "0x" ), Qt::CaseInsensitive ) )
      {
        cStr.replace( 0, 2, QStringLiteral( "#" ) );
      }

      const QColor color = QColor( cStr );
      ok = color.isValid();

      if ( !ok )
      {
        return QList<QColor>();
      }

      colors.append( color );
    }
  }

  return colors;
}
Пример #4
0
void nsAbIPCCard::CopyValue(PRBool isUnicode, nsString & attribValue, LPTSTR * result)
{
    *result = NULL;
    if(attribValue.Length() && attribValue.get()) {
        PRInt32 length;
        if(isUnicode) {                                 
            length = attribValue.Length()+1;
            PRUnichar * Str = (PRUnichar *) CoTaskMemAlloc(sizeof(PRUnichar) * length);
            wcsncpy(Str, attribValue.get(), length-1);
            Str[length-1] = '\0';
            *result = Str;
        } 
        else { 
            NS_LossyConvertUTF16toASCII cStr(attribValue);
            // These strings are defined as wide in the idl, so we need to add up to 3
            // bytes of 0 byte padding at the end (if the string is an odd number of 
            // bytes long, we need one null byte to pad out the last char to a wide char
            // and then  two more nulls as a wide null terminator.
            length = cStr.Length()+3;
            char * str = (char *) CoTaskMemAlloc(length);
            strncpy(str, cStr.get(), length-1);
            str[length-1] = '\0';
            *result = (LPTSTR) str;
        } 
    }
}
Пример #5
0
void updateGraphics(void)
{
    int px, py;

    // update haptic rate label
    labelHapticRate->setString ("haptic rate: "+cStr(frequencyCounter.getFrequency(), 0) + " [Hz]");

    px = (int)(0.5 * (displayW - labelHapticRate->getWidth()));
    labelHapticRate->setLocalPos(px, 15);

    // update other widgets
    py = (int)(0.5 * (displayH - level->getHeight()));
    level->setLocalPos(50, py);
    level->setValue(tool->m_lastComputedGlobalForce.length());

    px = displayW - 80;
    py = (int)(0.5 * displayH);
    dial->setLocalPos(px, py);
    dial->setValue1(angVel.length());

    // render world
    camera->renderView(displayW, displayH);

    // swap buffers
    glutSwapBuffers();

    // check for any OpenGL errors
    GLenum err;
    err = glGetError();
    if (err != GL_NO_ERROR) printf("Error:  %s\n", gluErrorString(err));
}
Пример #6
0
String::String(const char* cb, size_t n)
{

    //
    // preconditions
    //

    if(cb == 0)
        strError("String::String", "InvalidArgument");

    //
    // operations
    //

    if(n == NPOS)
        n = strlen(cb);

    if(n == 0) {
        srep = 0;
    }
    else {
        srep = StringRep::getNew(n, 0, cb);
    }

    //
    // post conditions
    //

    assert(n == 0 || srep != 0);
    assert(length() == n);
    assert(memcmp(cStr(), cb, length()) == 0);
}
Пример #7
0
bool CreateShortcut(wxString path, wxString name, wxString dest, wxString args, wxString iconPath)
{
	wxFileName pathFileName(path, name + ".lnk");
	pathFileName.MakeAbsolute();
	path = pathFileName.GetFullPath();
	return SUCCEEDED(CreateLink(cStr(path), dest.wchar_str().data(), args.wchar_str().data()));
}
Пример #8
0
 void
 AppState::maybeStart (lumiera::Subsys& subsys)
 {
   TRACE (common, "maybe startup %s...?", cStr(subsys));
   REQUIRE (subsystems_);
   subsystems_->maybeRun (subsys);
 }
Пример #9
0
Файл: cgi.c Проект: Accio/ribios
SEXP r_cgiParam(SEXP r_param, SEXP ignore_case, SEXP r_default) {
  if(r_param == R_NilValue) return(R_NilValue);

  char* name;
  Stringa value=stringCreate(16);

  char *param=cStr(r_param);
  char *str=NULL;

  SEXP res;
  int (*fPtr)(char*, char*);
  fPtr=cBool(ignore_case) ? &myStrCaseEqual : &myStrEqual;

  cgiGetInit();

  while(name = cgiGetNext(value)) {
    if((*fPtr)(name, param)) {
      str=hlr_strdup(string(value));
      break;
    }
  }
  
  stringDestroy(value);

  if(str) {
    return mkString(str);
  } else {
    return r_default;
  }
}
Пример #10
0
//
// insert
//
String& String::insert(size_t pos, const String& s)
{
    KEEPOLD;

    //
    // preconditions
    //

    if(pos > length())
        strError("String::insert", "OutOfRange");

    //
    // operations
    //

    if(this == &s)
        return insert(pos, String(s));          // insert into itself
    if(s.srep)
        doReplace(pos, 0, s.srep->str, s.srep->getLen());

    //
    // post conditions
    //

    assert(length() == (s.length() + OLD.length()));
    assert(memcmp(cStr() + pos, s.cStr(), s.length()) == 0);

    return *this;
}
Пример #11
0
Файл: cgi.c Проект: Accio/ribios
SEXP r_cgiDecodeWord(SEXP word) {
  static Stringa value;
  stringCreateOnce(value, 16);
  
  stringCpy(value, cStr(word));
  cgiDecodeWord(value);
  return mkString(string(value));
}
Пример #12
0
Файл: cgi.c Проект: Accio/ribios
SEXP r_cgiEncodeWord(SEXP word) {
  static Stringa value;
  stringCreateOnce(value, 16);
  static char *s;
  
  s=cStr(word);
  cgiEncodeWord(s, value);
  return mkString(string(value));
}
Пример #13
0
void InitialGameStateExtractor::extractBuildings(GameState &state, UString bldFileName,
                                                 sp<City> city, bool alienBuilding)
{
	auto &data = this->ufo2p;

	auto fileName = "xcom3/ufodata/" + bldFileName + ".bld";

	auto inFile = fw().data->fs.open(fileName);
	if (!inFile)
	{
		LogError("Failed to open \"%s\"", fileName.cStr());
	}
	auto fileSize = inFile.size();
	auto bldCount = fileSize / sizeof(struct BldFileEntry);

	LogInfo("Loading %lu buildings from %s", (unsigned long)bldCount, fileName.cStr());

	for (unsigned i = 0; i < bldCount; i++)
	{
		struct BldFileEntry entry;
		inFile.read((char *)&entry, sizeof(entry));

		auto b = mksp<Building>();
		if (alienBuilding)
		{
			LogInfo("Alien bld %d func %d", entry.name_idx, entry.function_idx);
			// FIXME: albld.bld seems to have unexpected name_idx and function_idx?
			b->name = data.alien_building_names->get(i);
			b->function = b->name;
		}
		else
		{
			b->name = data.building_names->get(entry.name_idx);
			b->function = data.building_functions->get(entry.function_idx);
		}
		b->owner = {&state, data.getOrgId(entry.owner_idx)};
		// Our rects are exclusive of p2
		// Shift position by 20 tiles
		b->bounds = {entry.x0 + 20, entry.y0 + 20, entry.x1 + 21, entry.y1 + 21};
		auto id = UString::format("%s%s", Building::getPrefix(), canon_string(b->name));

		city->buildings[id] = b;
	}
}
Пример #14
0
int ConfigFile::getInt(UString key)
{
	auto string = this->getString(key);
	if (string == "")
	{
		return 0;
	}
	int value = std::atoi(string.cStr());
	return value;
}
Пример #15
0
void updateGraphics(void)
{
    // update content of position label
    for (int i=0; i<numHapticDevices; i++)
    {
        // read position of device an convert into millimeters
        cVector3d pos;
        hapticDevices[i]->getPosition(pos);
        pos.mul(1000);

        // create a string that concatenates the device number and its position.
        string strID;
        cStr(strID, i);
        string strLabel = "#" + strID + "  x: ";

        cStr(strLabel, pos.x, 2);
        strLabel = strLabel + "   y: ";
        cStr(strLabel, pos.y, 2);
        strLabel = strLabel + "  z: ";
        cStr(strLabel, pos.z, 2);

        labels[i]->m_string = strLabel;
    }

    // render world
    camera->renderView(displayW, displayH);

    // Swap buffers
    glutSwapBuffers();

    // check for any OpenGL errors
    GLenum err;
    err = glGetError();
    if (err != GL_NO_ERROR) printf("Error:  %s\n", gluErrorString(err));

    // inform the GLUT window to call updateGraphics again (next frame)
    if (simulationRunning)
    {
        glutPostRedisplay();
    }
}
Пример #16
0
String& String::insert(size_t pos, const char* cb, size_t n)
{
    KEEPOLD;

#ifndef NDEBUG
    char *pOLD = 0;
    if(cb != 0) {
        if(n == NPOS)
            n = strlen(cb);
        pOLD = new char[n];
        assert(pOLD != 0);
        memcpy(pOLD, cb, n);
    }
#endif

    //
    // preconditions
    //

    if(pos > length())
        strError("String::insert", "OutOfRange");
    if(cb == 0)
        strError("String::insert", "InvalidArgument");

    //
    // operations
    //

    if(n == NPOS)
        n = strlen(cb);

    if(n > 0)
        doReplace(pos, 0, cb, n);

    //
    // post conditions
    //

    assert(length() == (n + OLD.length()));

#ifndef NDEBUG
    //
    // this asertion is so complicated
    // because of hacks like: s.insert(1, s.cStr() + 2)
    //
    assert(memcmp(cStr() + pos, pOLD, n) == 0);
    delete [] pOLD;
#endif

    return *this;
}
Пример #17
0
wxThread::ExitCode PastebinTask::TaskStart()
{
    SetStatus(_("Sending to pastebin..."));

    // Create handle
    CURL *curl = curl_easy_init();
    char errBuffer[CURL_ERROR_SIZE];

    // URL encode
    wxCharBuffer contentBuf = m_content.ToUTF8();
    char *content = curl_easy_escape(curl, contentBuf.data(), strlen(contentBuf));

    wxCharBuffer posterBuf = m_author.ToUTF8();
    char *poster = curl_easy_escape(curl, posterBuf.data(), strlen(posterBuf));

    wxString postFields;
    postFields << "poster=" << poster << "&syntax=text&content=" << content;

    curl_easy_setopt(curl, CURLOPT_URL, "http://paste.ubuntu.com/");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlLambdaCallback);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, cStr(postFields));
    curl_easy_setopt(curl, CURLOPT_HEADER, true);
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &errBuffer);

    wxString outString;
    wxStringOutputStream outStream(&outString);
    CurlLambdaCallbackFunction curlWrite = [&] (void *buffer, size_t size) -> size_t
    {
        outStream.Write(buffer, size);
        return outStream.LastWrite();
    };
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curlWrite);

    int status = curl_easy_perform(curl);

    if (status == 0)
    {
        // Parse the response header for the redirect location.
        m_pasteURL = outString.Mid(outString.Find("Location: ") + 10);
        m_pasteURL = m_pasteURL.Mid(0, m_pasteURL.Find('\n'));
        return (ExitCode)1;
    }
    else
    {
        EmitErrorMessage(wxString::Format("Pastebin failed: %s", errBuffer));
        return (ExitCode)0;
    }
}
Пример #18
0
bool ConfigFile::getBool(UString key)
{
	auto value = this->getString(key);
	for (auto &v : trueValues)
	{
		if (v == value)
			return true;
	}
	for (auto &v : falseValues)
	{
		if (v == value)
			return false;
	}
	LogError("Invalid boolean value of \"%s\" in key \"%s\"", value.cStr(), key.cStr());
	return false;
}
Пример #19
0
void updateGraphics(void)
{
    // update haptic rate label
    labelHapticRate->setString ("haptic rate: "+cStr(frequencyCounter.getFrequency(), 0) + " [Hz]");

    int px = (int)(0.5 * (displayW - labelHapticRate->getWidth()));
    labelHapticRate->setLocalPos(px, 15);

    // render world
    camera->renderView(displayW, displayH);

    // swap buffers
    glutSwapBuffers();

    // check for any OpenGL errors
    GLenum err;
    err = glGetError();
    if (err != GL_NO_ERROR) printf("Error:  %s\n", gluErrorString(err));
}
Пример #20
0
//
// assignment operators
//
String& String::operator=(const String& s)
{
    //
    // operations
    //

    ((String&)s).refInc();    // casting away constness, as we change not
                              // the value of the string
    refDec();
    srep = s.srep;

    //
    // post conditions
    //

    assert(length() == s.length());
    assert(memcmp(cStr(), s.cStr(), length()) == 0);

    return *this;
}
Пример #21
0
String& String::operator+=(const char *cs)
{
    KEEPOLD;
#ifndef NDEBUG
    char *pOLD = 0;
    if(cs != 0) {
        pOLD = new char[strlen(cs) + 1];
        assert(pOLD != 0);
        strcpy(pOLD, cs);
    }
#endif

    //
    // preconditions
    //

    if(cs == 0)
        strError("String::operator+=", "InvalidArgument");

    //
    // operations
    //

    doReplace(length(), 0, cs, strlen(cs));

    //
    // post conditions
    //

#ifndef NDEBUG
    //
    // this asertion is so complicated
    // because of hacks like: s += s.cStr();
    //
    assert((OLD.length() + strlen(pOLD)) == length());
    assert(memcmp(cStr() + OLD.length(), pOLD, strlen(pOLD)) == 0);
    delete [] pOLD;
#endif

    return *this;
}
Пример #22
0
String& String::assign(const char* cb, size_t n)
{
    //
    // preconditions
    //

    if(cb == 0)
        strError("String::assign", "InvalidArgument");

    //
    // operations
    //

    if(n == NPOS)
        n = strlen(cb);

    if(n == 0) {
        refDec();
        srep = 0;
    }
    else {
        if(needClone(n)) {
            String::StringRep* rep = StringRep::getNew(n, 0, cb);
            refDec();
            srep = rep;
        }
        else {
            srep->setLen(n);
            memcpy(srep->str, cb, n);
        }
    }

    //
    // post conditions
    //

    assert(length() == n);
    assert(memcmp(cStr(), cb, length()) == 0);

    return *this;
}
Пример #23
0
 ExitCode
 AppState::abort (lumiera::Error& problem)
 {
   
   ERROR (common, "Aborting Lumiera after unhandled error: %s", cStr(problem.what()));
   
   log_and_clear_unexpected_errorstate();
   
   try
     {
       if (subsystems_)
         {
           subsystems_->triggerEmergency(true);
           subsystems_->shutdownAll();
         }
       return maybeWait ();
     }
   catch (...)
     {
       return abort();
     }
 }
Пример #24
0
static void initLogger()
{
	outFile = NULL;

	// Handle Log calls befoore the settings are read, just output everything to stdout

	if (!ConfigFile::getInstance().loaded())
	{
		stderrLogLevel = LogLevel::Debug;
		fileLogLevel = LogLevel::Nothing;
		backtraceLogLevel = LogLevel::Nothing;
		showDialogOnError = false;
		// Returning withoput setting loggerInited causes this to be called evey Log call until the
		// config is parsed
		return;
	}

	loggerInited = true;

	stderrLogLevel = (LogLevel)stderrLogLevelOption.get();
	fileLogLevel = (LogLevel)fileLogLevelOption.get();
	backtraceLogLevel = (LogLevel)backtraceLogLevelOption.get();
	showDialogOnError = showDialogOnErrorOption.get();

	auto logFilePath = logFileOption.get();
	if (logFilePath.empty())
	{
		// No log file set, disabling logging to file
		fileLogLevel = LogLevel::Nothing;
		return;
	}
	outFile = fopen(logFilePath.cStr(), "w");
	if (!outFile)
	{
		// Failed to open log file, disabling logging to file
		fileLogLevel = LogLevel::Nothing;
		return;
	}
}
Пример #25
0
bool ProviderWithChecksum::readDocument(const UString &path, UString &result)
{
	if (inner->readDocument(path, result))
	{
		auto sha1Sum = calculate_checksum(result.str());
		auto expectedSha1Sum = contents[path.str()];
		if (expectedSha1Sum != "")
		{
			if (sha1Sum != expectedSha1Sum)
			{
				LogWarning("File \"%s\" has incorrect checksum \"%s\", expected \"%s\"",
				           path.cStr(), sha1Sum.cStr(), expectedSha1Sum.c_str());
			}
		}
		else
		{
			LogInfo("Skipping missing checksum for file \"%s\"", path.cStr());
		}
		return true;
	}

	return false;
}
Пример #26
0
//
//  appending operators
//
String& String::operator+=(const String& s)
{
    size_t sLen;
    KEEPOLD;

    //
    // operations
    //

    if(this == &s)              // append to self
        return operator+=(String(s));
    sLen = s.length();
    if(sLen > 0)
        doReplace(length(), 0, s.srep->str, sLen);

    //
    // post conditions
    //

    assert((OLD.length() + s.length()) == length());
    assert(memcmp(cStr() + OLD.length(), s.cStr(), s.length()) == 0);

    return *this;
}
Пример #27
0
void updateGraphics(void)
{
	//-----------------Jake--------------//
    // update content of position label
    // read position of device an convert into millimeters
    cVector3d pos = tool->m_proxyPointForceModel->getProxyGlobalPosition();
  //  pos.mul(1000);

    // create a string that concatenates the device number and its position.
    string strID;
    cStr(strID, 0);
    string strLabel = "#" + strID + "  x: ";

    cStr(strLabel, pos.x, 2);
    strLabel = strLabel + "   y: ";
    cStr(strLabel, pos.y, 2);
    strLabel = strLabel + "  z: ";
    cStr(strLabel, pos.z, 2);

    labels[0]->m_string = strLabel;

	pos = index_finger->m_proxyPointForceModel->getProxyGlobalPosition();

    string strID1;
    cStr(strID1, 1);
    string strLabel1 = "#" + strID1 + "  x: ";

    cStr(strLabel1, pos.x, 2);
    strLabel1 = strLabel1 + "   y: ";
    cStr(strLabel1, pos.y, 2);
    strLabel1 = strLabel1 + "  z: ";
    cStr(strLabel1, pos.z, 2);
	
    labels[1]->m_string = strLabel1;

    string strID2;
    cStr(strID2, 2);
    string strLabel2 = "#" + strID2 + "  x: ";

    cStr(strLabel2, pos.x, 2);
    strLabel2 = strLabel2 + "   y: ";
    cStr(strLabel2, pos.y, 2);
    strLabel2 = strLabel2 + "  z: ";
    cStr(strLabel2, pos.z, 2);
	
    labels[2]->m_string = strLabel2;

    // render world
    camera->renderView(displayW, displayH);

    // Swap buffers
    glutSwapBuffers();

    // check for any OpenGL errors
    GLenum err;
    err = glGetError();
    if (err != GL_NO_ERROR) printf("Error:  %s\n", gluErrorString(err));

    // inform the GLUT window to call updateGraphics again (next frame)
    if (simulationRunning)
    {
        glutPostRedisplay();
    }
}
Пример #28
0
void nsAbIPCCard::JoinAddress(PRBool isUnicode, LPTSTR *ptrAddress, nsString &address1, nsString &address2)
{
  // If the two address lines in a moz card are not empty
  // then join the lines into a single line separated by
  // '\x0A'. This is the format expected by Palm.
  *ptrAddress = NULL;
  PRUint32 strLength= address1.Length() + address2.Length();
  if(!strLength)
    return;

  // Allocate space for 'strLength' plus three for nulls and one for "\x0A".
  // These strings are defined as wide in the idl, so we need to add up to 3
  // bytes of 0 byte padding at the end (if the string is an odd number of 
  // bytes long, we need one null byte to pad out the last char to a wide char
  // and then  two more nulls as a wide null terminator.
  strLength += 4;
  if(isUnicode)
  { 
    PRUnichar * uniStr = (PRUnichar *) CoTaskMemAlloc(sizeof(PRUnichar) * (strLength));
    if(address1.Length())
    {
      wcsncpy(uniStr, address1.get(), strLength-1);
      uniStr[strLength-1] = '\0';
      if(address2.Length())
      {
        wcsncat(uniStr, (const wchar_t *)"\x0A", strLength-1);
        wcsncat(uniStr, address2.get(), strLength-1);
        uniStr[strLength-1] = '\0';
      }
    }
    else
    {
      wcsncpy(uniStr, address2.get(), strLength-1);
      uniStr[strLength-1] = '\0';
    }

    *ptrAddress = uniStr;
  } 
  else
  { 
    char * str = (char *) CoTaskMemAlloc(strLength);
    if(address1.Length())
    {
      NS_LossyConvertUTF16toASCII cStr(address1);
      strncpy(str, cStr.get(), strLength-1);
      str[strLength-1] = '\0';
      if(address2.Length())
      {
        LossyCopyUTF16toASCII(address2, cStr);
        strncat(str, "\x0A", strLength-1);
        strncat(str, cStr.get(), strLength-1);
        str[strLength-1] = '\0';
      }
    }
    else
    {
      NS_LossyConvertUTF16toASCII cStr(address2);
      strncpy(str, cStr.get(), strLength-1);
      str[strLength-1] = '\0';
    }
    *ptrAddress = (LPTSTR) str;
  } 
}
Пример #29
0
int main(int argc, char* argv[])
{
    //-----------------------------------------------------------------------
    // INITIALIZATION
    //-----------------------------------------------------------------------

    printf ("\n");
    printf ("-----------------------------------\n");
    printf ("CHAI 3D\n");
    printf ("Demo: 23-tooth\n");
    printf ("Copyright 2003-2010\n");
    printf ("-----------------------------------\n");
    printf ("\n\n");
    printf ("Instructions:\n\n");
    printf ("- Use haptic device and user switch to rotate \n");
    printf ("  rotate and translate tooth. \n");
    printf ("\n\n");
    printf ("Keyboard Options:\n\n");
    printf ("[1] - Wireframe (ON/OFF)\n");
    printf ("[2] - Normals   (ON/OFF)\n");
    printf ("[+] - Increase Opacity\n");
    printf ("[-] - Reduce Opacity\n");
    printf ("[x] - Exit application\n");
    printf ("\n\n");

    // parse first arg to try and locate resources
    resourceRoot = string(argv[0]).substr(0,string(argv[0]).find_last_of("/\\")+1);

	sp = new Serial("COM6");
	if (sp->IsConnected())
		printf("We're connected");

    //-----------------------------------------------------------------------
    // 3D - SCENEGRAPH
    //-----------------------------------------------------------------------

    // create a new world.
    world = new cWorld();

    // set the background color of the environment
    // the color is defined by its (R,G,B) components.
    world->setBackgroundColor(0.0, 0.0, 0.0);

    // create a camera and insert it into the virtual world
    camera = new cCamera(world);
    world->addChild(camera);

    // position and oriente the camera
    camera->set( cVector3d (3.0, 0.0, 0.3),    // camera position (eye)
                 cVector3d (0.0, 0.0, 0.0),    // lookat position (target)
                 cVector3d (0.0, 0.0, 1.0));   // direction of the "up" vector

    // set the near and far clipping planes of the camera
    // anything in front/behind these clipping planes will not be rendered
    camera->setClippingPlanes(0.01, 10.0);

    // enable high quality rendering when tooth becomes transparent
    camera->enableMultipassTransparency(true);

    // create a light source and attach it to the camera
    light = new cLight(world);
    camera->addChild(light);                   // attach light to camera
    light->setEnabled(true);                   // enable light source
    light->setPos(cVector3d( 2.0, 0.5, 1.0));  // position the light source
    light->setDir(cVector3d(-2.0, 0.5, 1.0));  // define the direction of the light beam
    light->m_ambient.set(0.6, 0.6, 0.6);
    light->m_diffuse.set(0.8, 0.8, 0.8);
    light->m_specular.set(0.8, 0.8, 0.8);

    //-----------------------------------------------------------------------
    // 2D - WIDGETS
    //-----------------------------------------------------------------------

    // create a 2D bitmap logo
    logo = new cBitmap();

    // add logo to the front plane
    camera->m_front_2Dscene.addChild(logo);

    // load a "chai3d" bitmap image file
    bool fileload;
    fileload = logo->m_image.loadFromFile(RESOURCE_PATH("resources/images/chai3d.bmp"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = logo->m_image.loadFromFile("../../../bin/resources/images/chai3d.bmp");
        #endif
    }

    // position the logo at the bottom left of the screen (pixel coordinates)
    logo->setPos(10, 10, 0);

    // scale the logo along its horizontal and vertical axis
    logo->setZoomHV(0.4, 0.4);

    // here we replace all black pixels (0,0,0) of the logo bitmap
    // with transparent black pixels (0, 0, 0, 0). This allows us to make
    // the background of the logo look transparent.
    logo->m_image.replace(
                          cColorb(0, 0, 0),      // original RGB color
                          cColorb(0, 0, 0, 0)    // new RGBA color
                          );

    // enable transparency
    logo->enableTransparency(true);


    //-----------------------------------------------------------------------
    // HAPTIC DEVICES / TOOLS
    //-----------------------------------------------------------------------

    // create a haptic device handler
    handler = new cHapticDeviceHandler();

    // get access to the first available haptic device
    cGenericHapticDevice* hapticDevice;
    handler->getDevice(hapticDevice, 0);

    // retrieve information about the current haptic device
    if (hapticDevice)
    {
        info = hapticDevice->getSpecifications();
    }

    // create a 3D tool and add it to the world
    tool = new cGeneric3dofPointer(world);

	//-----------------Jake--------------//
	index_finger = new cGeneric3dofPointer(world);
	thumb = new cGeneric3dofPointer(world);

    world->addChild(tool);
	world->addChild(index_finger);
	world->addChild(thumb);

    // connect the haptic device to the tool
    tool->setHapticDevice(hapticDevice);

    // initialize tool by connecting to haptic device
    tool->start();

    // map the physical workspace of the haptic device to a larger virtual workspace.
    tool->setWorkspaceRadius(1.0);
	index_finger->setWorkspaceRadius(1.0);
	thumb->setWorkspaceRadius(1.0);

    // define a radius for the tool (graphical display)
    tool->setRadius(0.01);
	index_finger->setRadius(0.01);
	thumb->setRadius(0.01);

    // hide the device sphere. only show proxy.
    tool->m_deviceSphere->setShowEnabled(false);
	index_finger->setShowEnabled(false);
	thumb->setShowEnabled(false);

    // set the physical radius of the proxy to be equal to the radius
    // of the tip of the mesh drill (see drill in the virtual scene section)
    proxyRadius = 0.03;
    tool->m_proxyPointForceModel->setProxyRadius(proxyRadius);
	index_finger->m_proxyPointForceModel->setProxyRadius(proxyRadius);
	thumb->m_proxyPointForceModel->setProxyRadius(proxyRadius);

    // informe the finger-proxy force renderer to only check one side of triangles
    tool->m_proxyPointForceModel->m_collisionSettings.m_checkBothSidesOfTriangles = false;
	index_finger->m_proxyPointForceModel->m_collisionSettings.m_checkBothSidesOfTriangles = false;
	thumb->m_proxyPointForceModel->m_collisionSettings.m_checkBothSidesOfTriangles = false;

    // the environmeny is static, you can set this parameter to "false"
    tool->m_proxyPointForceModel->m_useDynamicProxy = false;
	index_finger->m_proxyPointForceModel->m_useDynamicProxy = false;
	thumb->m_proxyPointForceModel->m_useDynamicProxy = false;

    tool->m_proxyPointForceModel->m_useForceShading = true;
	index_finger->m_proxyPointForceModel->m_useForceShading = true;
	thumb->m_proxyPointForceModel->m_useForceShading = true;

    // read the scale factor between the physical workspace of the haptic
    // device and the virtual workspace defined for the tool
    double workspaceScaleFactor = tool->getWorkspaceScaleFactor();

    // define a maximum stiffness that can be handled by the current
    // haptic device. The value is scaled to take into account the
    // workspace scale factor
    double stiffnessMax = info.m_maxForceStiffness / workspaceScaleFactor;

	rootLabels = new cGenericObject();
    camera->m_front_2Dscene.addChild(rootLabels);

    // create a small label as title
    cLabel* titleLabel = new cLabel();
    rootLabels->addChild(titleLabel);

	//-----Jake------//

    // define its position, color and string message
    titleLabel->setPos(300, 60, 0);
    titleLabel->m_fontColor.set(1.0, 1.0, 1.0);
    titleLabel->m_string = "Haptic Device Pos [mm]:";

	string strID;
    cStr(strID, 0);
    string strDevice = "#" + strID + " - " +info.m_modelName;

	cLabel* newLabel = new cLabel();
	tool->m_proxyMesh->addChild(newLabel);
	newLabel->m_string = strDevice;
	newLabel->setPos(0.00, 0.05, 0.00);
	newLabel->m_fontColor.set(1.0, 1.0, 1.0);

	string strID1;
    cStr(strID1, 1);
    string strDevice1 = "#" + strID1 + " - index finger";

	cLabel* newLabel1 = new cLabel();
	index_finger->m_proxyMesh->addChild(newLabel1);
	newLabel1->m_string = strDevice1;
	newLabel1->setPos(0.00, 0.05, 0.00);
	newLabel1->m_fontColor.set(1.0, 1.0, 1.0);

	string strID2;
    cStr(strID2, 2);
    string strDevice2 = "#" + strID2 + " - thumb";

	cLabel* newLabel2 = new cLabel();
	thumb->m_proxyMesh->addChild(newLabel2);
	newLabel2->m_string = strDevice2;
	newLabel2->setPos(0.00, 0.05, 0.00);
	newLabel2->m_fontColor.set(1.0, 1.0, 1.0);

	// crate a small label to indicate the position of the device
	cLabel* newPosLabel = new cLabel();
	rootLabels->addChild(newPosLabel);
	newPosLabel->setPos(300, 50, 0);
	newPosLabel->m_fontColor.set(0.6, 0.6, 0.6);
	labels[0] = newPosLabel;

	cLabel* newPosLabel1 = new cLabel();
	rootLabels->addChild(newPosLabel1);
	newPosLabel1->setPos(300, 30, 0);
	newPosLabel1->m_fontColor.set(0.6, 0.6, 0.6);
	labels[1] = newPosLabel1;

	cLabel* newPosLabel2 = new cLabel();
	rootLabels->addChild(newPosLabel2);
	newPosLabel2->setPos(300, 10, 0);
	newPosLabel2->m_fontColor.set(0.6, 0.6, 0.6);
	labels[2]= newPosLabel2;

    //-----------------------------------------------------------------------
    // COMPOSE THE VIRTUAL SCENE
    //-----------------------------------------------------------------------

    // create a virtual mesh
    tooth = new cMesh(world);

    // add object to world
    world->addChild(tooth);

    // set the position and orientation of the object at the center of the world
    tooth->setPos(0.0, 0.0, 0.0);
    tooth->rotate(cVector3d(0.0, 0.0, 1.0), cDegToRad(-10));
    tooth->rotate(cVector3d(0.0, 1.0, 0.0), cDegToRad(10));

    // load an object file
    fileload = tooth->loadFromFile(RESOURCE_PATH("resources/models/tooth/tooth.3ds"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = tooth->loadFromFile("../../../bin/resources/models/tooth/tooth.3ds");
        #endif
    }
    if (!fileload)
    {
        printf("Error - 3D Model failed to load correctly.\n");
        close();
        return (-1);
    }

    // make the outside of the tooth rendered in wireframe
    ((cMesh*)(tooth->getChild(1)))->setWireMode(true);

    // make the outside of the tooth rendered in semi-transparent
    ((cMesh*)(tooth->getChild(1)))->setUseTransparency(false);
    ((cMesh*)(tooth->getChild(1)))->setTransparencyLevel(transparencyLevel);

    // compute a boundary box
    tooth->computeBoundaryBox(true);

    // resize tooth to screen
    tooth->scale(0.003);

    // compute collision detection algorithm
    tooth->createAABBCollisionDetector(1.01 * proxyRadius, true, false);

    // define a default stiffness for the object	x
    tooth->setStiffness(0.8 * stiffnessMax, true);

    // create a new mesh.
    drill = new cMesh(world);

    // load a drill like mesh and attach it to the tool
    fileload = drill->loadFromFile(RESOURCE_PATH("resources/models/drill/drill.3ds"));
    if (!fileload)
    {
        #if defined(_MSVC)
        fileload = drill->loadFromFile("../../../bin/resources/models/drill/drill.3ds");
        #endif
    }
    if (!fileload)
    {
        printf("Error - 3D Model failed to load correctly.\n");
        close();
        return (-1);
    }

    // resize tool mesh model
    drill->scale(0.004);

    // remove the collision detector. we do not want to compute any
    // force feedback rendering on the object itself.
    drill->deleteCollisionDetector(true);

    // define a material property for the mesh
    cMaterial mat;
    mat.m_ambient.set(0.5, 0.5, 0.5);
    mat.m_diffuse.set(0.8, 0.8, 0.8);
    mat.m_specular.set(1.0, 1.0, 1.0);
    drill->setMaterial(mat, true);
    drill->computeAllNormals(true);

    // attach drill to tool
    tool->m_proxyMesh->addChild(drill);

    //-----------------------------------------------------------------------
    // OPEN GL - WINDOW DISPLAY
    //-----------------------------------------------------------------------

    // initialize GLUT
    glutInit(&argc, argv);

    // retrieve the resolution of the computer display and estimate the position
    // of the GLUT window so that it is located at the center of the screen
    int screenW = glutGet(GLUT_SCREEN_WIDTH);
    int screenH = glutGet(GLUT_SCREEN_HEIGHT);
    int windowPosX = (screenW - WINDOW_SIZE_W) / 2;
    int windowPosY = (screenH - WINDOW_SIZE_H) / 2;

    // initialize the OpenGL GLUT window
    glutInitWindowPosition(windowPosX, windowPosY);
    glutInitWindowSize(WINDOW_SIZE_W, WINDOW_SIZE_H);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(updateGraphics);
    glutKeyboardFunc(keySelect);
    glutReshapeFunc(resizeWindow);
    glutSetWindowTitle("CHAI 3D");

    // create a mouse menu (right button)
    glutCreateMenu(menuSelect);
    glutAddMenuEntry("full screen", OPTION_FULLSCREEN);
    glutAddMenuEntry("window display", OPTION_WINDOWDISPLAY);
    glutAttachMenu(GLUT_RIGHT_BUTTON);


    //-----------------------------------------------------------------------
    // START SIMULATION
    //-----------------------------------------------------------------------

    // simulation in now running
    simulationRunning = true;

    // create a thread which starts the main haptics rendering loop
    cThread* hapticsThread = new cThread();
    hapticsThread->set(updateHaptics, CHAI_THREAD_PRIORITY_HAPTICS);

    // start the main graphics rendering loop
    glutMainLoop();

    // close everything
    close();

    // exit
    return (0);
}
Пример #30
0
void InitialGameStateExtractor::extractResearch(GameState &state, Difficulty)
{
	auto &data = this->ufo2p;
	for (unsigned i = 0; i < data.research_data->count(); i++)
	{
		auto rdata = data.research_data->get(i);

		auto r = mksp<ResearchTopic>();

		r->name = data.research_names->get(i);
		auto id = ResearchTopic::getPrefix() + canon_string(r->name);
		r->description = data.research_descriptions->get(i);
		r->ufopaedia_entry = "";
		r->man_hours = rdata.skillHours;
		r->man_hours_progress = 0;
		switch (rdata.researchGroup)
		{
			case 0:
				r->type = ResearchTopic::Type::BioChem;
				break;
			case 1:
				r->type = ResearchTopic::Type::Physics;
				break;
			default:
				LogError("Unexpected researchGroup 0x%02x for research item %s",
				         (unsigned)rdata.researchGroup, id.cStr());
		}
		switch (rdata.labSize)
		{
			case 0:
				r->required_lab_size = ResearchTopic::LabSize::Small;
				break;
			case 1:
				r->required_lab_size = ResearchTopic::LabSize::Large;
				break;
			default:
				LogError("Unexpected labSize 0x%02x for research item %s", (unsigned)rdata.labSize,
				         id.cStr());
		}
		// FIXME: this assumed all listed techs are reqired, which is not true for some topics
		// (It's possible that an unknown member in ResearchData marks this, or it's done
		// in-code)
		// This should be fixed up in the patch.

		ResearchDependency dependency;
		dependency.type = ResearchDependency::Type::All;

		for (int pre = 0; pre < 3; pre++)
		{

			if (rdata.prereqTech[pre] != 0xffff)
			{
				auto prereqId = ResearchTopic::getPrefix() +
				                canon_string(data.research_names->get(rdata.prereqTech[pre]));
				dependency.topics.emplace(StateRef<ResearchTopic>{&state, prereqId});
			}
		}

		r->dependencies.research.push_back(dependency);

		r->score = rdata.score;

		if (state.research.topics.find(id) != state.research.topics.end())
		{
			LogError("Multiple research topics with ID \"%s\"", id.cStr());
		}
		state.research.topics[id] = r;
// FIXME: The ufopaedia entries here don't seem to directly map to the IDs we're currently using?
// May also be a many:1 ratio (e.g. the "alien gas" research topic unlocks multiple ufopaedia
// entries) making this more complex
#if 0

		auto ufopaediaEntryID = "PAEDIAENTRY_" + canon_string(r->name);
		auto ufopaediaCatID =
		    "PAEDIACATEGORY_" + canon_string(data.ufopaedia_group->get(rdata.ufopaediaGroup));
		auto paediaCat = state.ufopaedia[ufopaediaCatID];
		if (!paediaCat)
		{
			state.ufopaedia[ufopaediaCatID] = mksp<UfopaediaCategory>();
			paediaCat = state.ufopaedia[ufopaediaCatID];
		}
		auto paediaEntry = paediaCat->entries[ufopaediaEntryID];
		if (!paediaEntry)
		{
			paediaCat->entries[ufopaediaEntryID] = mksp<UfopaediaEntry>();
			paediaEntry = paediaCat->entries[ufopaediaEntryID];
		}
		if (paediaEntry->required_research)
		{
			LogError("Multiple required research for UFOPaedia topic \"%s\" - \"%s\" and \"%s\"",
			         ufopaediaEntryID.cStr(), r->name.cStr(),
			         paediaEntry->required_research->name.cStr());
		}
		paediaEntry->required_research = {&state, id};
#endif
	}
	state.research.updateTopicList();
}