Beispiel #1
0
Transport::Transport()
: only_localhost_allowed_(false)
{
  char *ros_ip_env = NULL, *ros_hostname_env = NULL;
  #ifdef _MSC_VER
    _dupenv_s(&ros_ip_env, NULL, "ROS_IP");
    _dupenv_s(&ros_hostname_env, NULL, "ROS_HOSTNAME");
  #else
    ros_ip_env = getenv("ROS_IP");
    ros_hostname_env = getenv("ROS_HOSTNAME");
  #endif
  if (ros_hostname_env && !strcmp(ros_hostname_env, "localhost"))
    only_localhost_allowed_ = true;
  else if (ros_ip_env && !strncmp(ros_ip_env, "127.", 4))
    only_localhost_allowed_ = true;
  else if (ros_ip_env && !strcmp(ros_ip_env, "::1"))
    only_localhost_allowed_ = true;

  char our_hostname[256] = {0};
  gethostname(our_hostname, sizeof(our_hostname)-1);
  allowed_hosts_.push_back(std::string(our_hostname));
  allowed_hosts_.push_back("localhost");
#if !defined(__ANDROID__) && !defined(_MSC_VER)
  // for ipv4 loopback, we'll explicitly search for 127.* in isHostAllowed()
  // now we need to iterate all local interfaces and add their addresses
  // from the getifaddrs manpage:  (maybe something similar for windows ?) 
  ifaddrs *ifaddr;
  if (-1 == getifaddrs(&ifaddr))
  {
    ROS_ERROR("getifaddr() failed");
    return;
  }
  for (ifaddrs *ifa = ifaddr; ifa; ifa = ifa->ifa_next)
  {
    if(NULL == ifa->ifa_addr)
      continue; // ifa_addr can be NULL
    int family = ifa->ifa_addr->sa_family;
    if (family != AF_INET && family != AF_INET6)
      continue; // we're only looking for IP addresses
    char addr[NI_MAXHOST] = {0};
    if (getnameinfo(ifa->ifa_addr,
                    (family == AF_INET) ? sizeof(sockaddr_in)
                                        : sizeof(sockaddr_in6),
                    addr, NI_MAXHOST,
                    NULL, 0, NI_NUMERICHOST))
    {
      ROS_ERROR("getnameinfo() failed");
      continue;
    }
    allowed_hosts_.push_back(std::string(addr));
  }
  freeifaddrs(ifaddr);
#endif
}
void InitializeEnvironment() {
    char *pValue;
    size_t len;

    errno_t err    = _dupenv_s( &pValue, &len, "JAVA_HOME" );     
    gJavaHome  = pValue;

    char *path_env = (char*)malloc(sizeof(char)*2048);

    _snprintf(path_env, 2048, "PATH=%s\\bin;%s", gJavaHome.c_str(), getenv("PATH"));
    _putenv ( path_env );

    err = _dupenv_s( &pValue, &len, "GEMFIRE" );
    gGemfireHome    = pValue;
}
Beispiel #3
0
void Prefs::open(){

	char *p;//=getenv( "blitzpath" );
	size_t len;
	errno_t err=_dupenv_s( &p,&len,"blitzpath" );
	if( err ){
		AfxMessageBox( "blitzpath environment variable not found!",MB_TOPMOST|MB_SETFOREGROUND|MB_ICONINFORMATION );
		ExitProcess(0);
	}

	homeDir=p;
	free( p );

	AddFontResource( (homeDir+"/cfg/blitz.fon").c_str() );

	setDefault();

	bool prg_windowed;

	ifstream in( (homeDir+"/cfg/blitzide.prefs").c_str() );
	if( !in.good() ) return;

	while( !in.eof() ){
		string t;in>>t;
		if( !t.size() ) continue;
		while( in.peek()=='\t' ) in.ignore();
		if( t=="prg_debug" ) in>>prg_debug;
		else if( t=="prg_lastbuild" ) getline( in,prg_lastbuild );
		else if( t=="prg_windowed" ) in>>prg_windowed;
		else if( t=="win_maximized" ) in>>win_maximized;
Beispiel #4
0
/**
 * Test code to get a environment variable in Windows
 */
int main(int argc, char* argv[]) {
	QCoreApplication app(argc, argv);

	const QString envVar = "path";	// the name of the evnironment variable for which we want the value
	char* pEnvVarVal = NULL;	// the value that will be return from the function

#ifdef _WIN32
		size_t envVarValSize;	// the returned size of the variable 
		errno_t envVarErrorCode = _dupenv_s(&pEnvVarVal, &envVarValSize, envVar.toLatin1());
		if(envVarErrorCode != 0 || envVarValSize == 0) { 
			// Handle error
			// Note: for some reason an unknown variable may return success 
			// with a 0 size value instead of returning an error
			std::cerr << "Unknown system variable " << envVar.toStdString() << std::endl;
		}
		else {
			// Print value of the variable
			std::cout << envVar.toStdString() << ":\t" << pEnvVarVal;
		}
#else	// Linux/Mac code
		pEnvVarVal = getenv(envVar.toLatin1());
#endif

	// Preven memory leak by cleaning up the variable's value after we are finished with it
	delete pEnvVarVal;
	pEnvVarVal = NULL;

	return app.exec(); // this will prevent the application for exiting immediately
}
Beispiel #5
0
int git_init()
{
	char *home;
	char path[MAX_PATH+1];
	char *prefix;
	int ret;
	size_t homesize,size;

	_fmode = _O_BINARY;
	_setmode(_fileno(stdin), _O_BINARY);
	_setmode(_fileno(stdout), _O_BINARY);
	_setmode(_fileno(stderr), _O_BINARY);

	// set HOME if not set already
	getenv_s(&homesize, NULL, 0, "HOME");
	if (!homesize)
	{
		_dupenv_s(&home,&size,"USERPROFILE");
		_putenv_s("HOME",home);
		free(home);
	}
	GetModuleFileName(NULL, path, MAX_PATH);
	convert_slash(path);

	git_extract_argv0_path(path);
	g_prefix = prefix = setup_git_directory();
	ret = git_config(git_default_config, NULL);

	if (!homesize)
	{
		_putenv_s("HOME","");/* clear home evironment to avoid affact third part software*/
	}

	return ret;
}
std::string get_home_folder ()
{
    auto home_dir = std::string{};

    char* appdata_folder{};
    auto buffer_len = 0U;
    errno_t error = _dupenv_s(&appdata_folder, &buffer_len, "LOCALAPPDATA");
    if (error)
    {
        error = _dupenv_s(&appdata_folder, &buffer_len, "APPDATA");
    }
    if (!error)
    {
        home_dir = appdata_folder;
    }
    free(appdata_folder);
    return home_dir;
}
const char *EstEID_getLogFilename() {
#ifdef _WIN32
	if (!filename[0]) {
		char *tempValue;
		size_t length;
		if(_dupenv_s(&tempValue, &length, "TEMP")) {
			tempValue = strdup("");
		}
		sprintf_s(filename, MAX_LOG_FILE_NAME_LEN, "%s\\esteid.log", tempValue);
		free(tempValue);
	}
	return filename;
#else
	return "/tmp/esteid.log";
#endif
}
Beispiel #8
0
std::string Filesystem::getCurrentRobotDirectory(std::string name)
{
	if (name.length() <= 0)
		name = "unnamed";

	char *dir;
	errno_t err = _dupenv_s(&dir, NULL, "APPDATA");

	if (err)
		throw "Failed to get AppData directory!";

	std::string strDir(dir);
	free(dir);

	return strDir + '\\' + ROBOT_APPDATA_DIRECTORY + '\\' + name + '\\';
}
    //---------------------------------------------------------------
    String DocumentExporter::getEnvironmentVariable ( const String & variableName )
    {
        char * buffer;
        size_t numberOfElements;
        errno_t error = _dupenv_s ( &buffer, &numberOfElements, variableName.c_str() );

        if ( error != 0 )
        {
            free ( buffer );
            return String();
        }

        String variableValue ( buffer, numberOfElements-1 );

        free ( buffer );
        return variableValue;
    }
Beispiel #10
0
        Formatter::Formatter() : doColor_(true){
                // Check for the format string environment variable
            char* format_string = NULL;
#ifdef _MSC_VER
                    _dupenv_s(&format_string, NULL, "SMCONSOLE_FORMAT");
#else
                format_string =  getenv("SMCONSOLE_FORMAT");
#endif
                if (!format_string)
                {
                    init("[${severity}] [${time}]: ${message}");
                }
                else
                {
                    init(format_string);
                }
                
            }
Beispiel #11
0
void init(const M_string& remappings)
{
  M_string::const_iterator it = remappings.find("__master");
  if (it != remappings.end())
  {
    g_uri = it->second;
  }

  if (g_uri.empty())
  {
    char *master_uri_env = NULL;
    #ifdef _MSC_VER
      _dupenv_s(&master_uri_env, NULL, "ROS_MASTER_URI");
    #else
      master_uri_env = getenv("ROS_MASTER_URI");
    #endif
    if (!master_uri_env)
    {
      ROS_FATAL( "ROS_MASTER_URI is not defined in the environment. Either " \
                 "type the following or (preferrably) add this to your " \
                 "~/.bashrc file in order set up your " \
                 "local machine as a ROS master:\n\n" \
                 "export ROS_MASTER_URI=http://localhost:11311\n\n" \
                 "then, type 'roscore' in another shell to actually launch " \
                 "the master program.");
      ROS_BREAK();
    }

    g_uri = master_uri_env;

#ifdef _MSC_VER
    // http://msdn.microsoft.com/en-us/library/ms175774(v=vs.80).aspx
    free(master_uri_env);
#endif
  }

  // Split URI into
  if (!network::splitURI(g_uri, g_host, g_port))
  {
    ROS_FATAL( "Couldn't parse the master URI [%s] into a host:port pair.", g_uri.c_str());
    ROS_BREAK();
  }
}
Beispiel #12
0
void searchenv(char *filename, int fnsz, char *envname, char *pathname, int pthsz)
{
   static char pbuf[5000];
   char *p, *np;
   size_t len;
//   char *strpbrk(), *strtok(), *getenv();

   strcpy_s(pathname, pthsz, filename);
   if (_access(pathname, 0) != -1)
      return;

   /* ----------------------------------------------------------------------
         The file doesn't exist in the current directory. If a specific
      path was requested (ie. file contains \ or /) or if the environment
      isn't set, return a NULL, else search for the file on the path.
   ---------------------------------------------------------------------- */
   _dupenv_s(&p, &len, envname);
   if (len==0)
   {
      *pathname = '\0';
      return;
   }

   strncpy_s(pbuf, sizeof(pbuf), p, sizeof(pbuf));
   np = nullptr;
   if (p = strtok_s(pbuf, ";", &np))
   {
      do
      {
		  if (p[strlen(p)-1]=='\\')
	         sprintf_s(pathname, pthsz-1, "%0.90s%s", p, filename);
		  else
	         sprintf_s(pathname, pthsz, "%0.90s\\%s", p, filename);

         if (_access(pathname, 0) >= 0)
            return;
      }
      while(p = strtok_s(NULL, ";", &np));
   }
   *pathname = 0;
}
Beispiel #13
0
/*! Get the value of an environment variable.
 *
 * The returned std::string is the full environment variable string, and thus
 * may actually contain multiple fields in the string with delimiters.
 *
 * \param var_name The name of the variable to search for.
 * \param default_val A default string value to use if the path isn't found.
 * \returns The string value of the environment variable.
 */
static std::string get_env_var(const std::string &var_name,
        const std::string &default_val = "") {

    std::string env_result = default_val;
    char *env_var_str = NULL;

    /* Some versions of MinGW don't expose `_dupenv_s` */
#if defined(UHD_PLATFORM_WIN32) && !defined(__MINGW32__)
    size_t len;
    errno_t err = _dupenv_s(&env_var_str, &len, var_name.c_str());
    if((not err) and (env_var_str != NULL))
        env_result = std::string(env_var_str);
    free(env_var_str);
#else
    env_var_str = std::getenv(var_name.c_str());
    if(env_var_str != NULL)
        env_result = std::string(env_var_str);
#endif

    return env_result;
}
std::vector<unsigned char> CTestCaseData::LoadFile(const std::string filename)
{
  std::vector<unsigned char> vectorBuffer;
  char* pFileSamplesPath;
  size_t len = 0;
  if (_dupenv_s(&pFileSamplesPath, &len, "FileSamplesPath") || !pFileSamplesPath)
  {
	  pFileSamplesPath = TEST_DATA_PATH;
  }
  std::string fileSamplesPath(pFileSamplesPath);
  if (fileSamplesPath.size() && (*fileSamplesPath.rbegin() != '\\'))
  {
	  fileSamplesPath += L'\\';
  }
  auto file = fileSamplesPath + filename;
  if (PathFileExistsA(file.c_str()))
  {
    HANDLE hFile = CreateFileA(file.c_str(), FILE_READ_ACCESS, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    if (hFile != INVALID_HANDLE_VALUE)
    {
      auto fileSize = GetFileSize(hFile, NULL);
      vectorBuffer.resize(fileSize);
      DWORD dwBytesRead = 0;
      ReadFile(hFile, &vectorBuffer[0], fileSize, &dwBytesRead, NULL);
      CloseHandle(hFile);
    }
  }
  else
  {
    vectorBuffer.resize(MAX_PATH);
    GetCurrentDirectoryA(vectorBuffer.size() - 1, (LPSTR)&vectorBuffer[0]);
    std::string filePath((LPSTR)&vectorBuffer[0]);
    filePath += "\\" + file;
    const std::wstring errorMessage(L"File not found: " + CPtoUCS2(filePath, CP_ACP));
    Microsoft::VisualStudio::CppUnitTestFramework::Assert::Fail(errorMessage.c_str(), LINE_INFO());
  }
  return vectorBuffer;
}
Beispiel #15
0
const char *getLogFilename() {
#ifdef _WIN32
	if (!filename[0]) {
		char *tempValue;
		size_t length;
		if(_dupenv_s(&tempValue, &length, "TEMP")) {
			tempValue = strdup("");
		}
		sprintf_s(filename, MAX_LOG_FILE_NAME_LEN, "%s\\esteid-pkcs11.log", tempValue);
		free(tempValue);
	}
	return filename;
#elif __APPLE__
  if (!filename[0]) {
    char *tmp;
    tmp = getenv("TMPDIR");
    sprintf(filename, "%sesteid-pkcs11.log", tmp);
  }
  return filename;
#else
	return "/tmp/esteid-pkcs11.log";
#endif
}
Beispiel #16
0
/* Returns the program's appdata folder. */
std::string getAppDataFolder()
{
#if PLATFORM == PLATFORM_WINDOWS
        /* Create a pointer and a size_t. */
        char *buff;
        size_t size = 0;

        /* Get the address. */
        _dupenv_s(&buff, &size, "APPDATA");

        /* Store the address into a string. */
        std::string addr = buff;
        addr += "\\DarkRedemption\\";

        /* Free the buffer given to us. */
        free(buff);

        /* Return the string. */
        return addr;
#else
        return "";
#endif
}
Beispiel #17
0
void InitializeLogging()
{
	char * loggingFileName = NULL;
	size_t loggingFileNameLength = 0;
	_dupenv_s(& loggingFileName, & loggingFileNameLength, LOGGING_ENV_VAR);
	if (loggingFileName != NULL) 
	{
		// If the environment variable contains the path of a currently existing directory,
		// then use a process-specific name for the log file and put it in that directory.
		// Otherwise, assume that the environment variable specifies the name of the log file.
		DWORD attributes = GetFileAttributesA(loggingFileName);
		if (attributes != INVALID_FILE_ATTRIBUTES && ((attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY))
		{
			char* loggingDirName = loggingFileName;
			size_t bufferSize = loggingFileNameLength + 30; // Need space for PID and tick count
			loggingFileName = new char[bufferSize];
			_snprintf_s(loggingFileName, bufferSize, _TRUNCATE, "%s\\client.%d.%d.log", loggingDirName, GetCurrentProcessId(), GetTickCount());
			delete[] loggingDirName;
		}

		logFile = _fsopen(loggingFileName, "at", _SH_DENYNO);
		delete[] loggingFileName;
	}
}
/**
 * Discover available (pre-allocated) nodes.  Allocate the
 * requested number of nodes/process slots to the job.
 */
static int orte_ras_ccp_allocate(opal_list_t *nodes)
{
    int ret, i;
    size_t len;
    char *cluster_head = NULL;
    HRESULT hr = S_OK;
    ICluster* pCluster = NULL;

    /* CCP is not thread safe. Use the apartment model. */
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    /* Create the Cluster object. */
    hr = CoCreateInstance( __uuidof(Cluster),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof(ICluster),
                           reinterpret_cast<void **> (&pCluster) );

    if (FAILED(hr)) {
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:allocate: failed to create cluster object!"));
        return ORTE_ERROR;
    }
    
    if(NULL == orte_ccp_headnode) {
        /* Get the cluster head nodes name */
        _dupenv_s(&cluster_head, &len, "LOGONSERVER");

        if(cluster_head == NULL) {
            OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                "ras:ccp:allocate: connot find cluster head node!"));
            return ORTE_ERROR;
        }

        /* Get rid of the beginning '//'. */
        for( i = 0; i < len - 2; i++){
            cluster_head[i] = cluster_head[i+2];
            cluster_head[i+2] = '\0';
        }
    } else {
        cluster_head = orte_ccp_headnode;
    }

    /* Connect to the cluster's head node */
    hr = pCluster->Connect(_bstr_t(cluster_head));
    if (FAILED(hr)) {
        ras_get_cluster_message(pCluster);
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:allocate: connection failed!"));
        return ORTE_ERROR;
    }
   
    if (ORTE_SUCCESS != (ret = discover(nodes, pCluster))) {
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:allocate: discover failed!"));
        return ret;
    }
        
    /* in the CCP world, if we didn't find anything, then this
     * is an unrecoverable error - report it
     */
    if (opal_list_is_empty(nodes)) {
        orte_show_help("help-ras-ccp.txt", "no-nodes-found", true);
        return ORTE_ERR_NOT_FOUND;
    }

    /* All finished, release cluster object*/
    pCluster->Release();
    CoUninitialize();

    return ret;
}
static int discover(opal_list_t* nodelist, ICluster* pCluster)
{
    int ret = ORTE_ERROR;
    int32_t nodeid;
    orte_node_t *node;
    opal_list_item_t* item;
    opal_list_t new_nodes;
    struct timeval start, stop;

    HRESULT hr = S_OK;  
    long idle_processors = 0;
    IClusterEnumerable* pNodesCollection = NULL;
    IEnumVARIANT* pNodes = NULL;
    INode* pNode = NULL;
    BSTR node_name = NULL, node_arch = NULL;
    VARIANT var;
    NodeStatus Status;
    size_t len;

    /* check for timing request - get start time if so */
    if (orte_timing) {
        gettimeofday(&start, NULL);
    }
    
    /* Get the collection of nodes. */
    hr = pCluster->get_ComputeNodes(&pNodesCollection);
    if (FAILED(hr)) {
        ras_get_cluster_message(pCluster);
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:pCluster->get_ComputeNodes failed."));
        return ORTE_ERROR;
    }

    /* Get the enumerator used to iterate through the collection. */
    hr = pNodesCollection->GetEnumerator(&pNodes);
    if (FAILED(hr)) {
        ras_get_cluster_message(pCluster);
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:pNodesCollection->GetEnumerator failed."));
        return ORTE_ERROR;
    }

    VariantInit(&var);

    /* Construct new node list. */
    OBJ_CONSTRUCT(&new_nodes, opal_list_t);
    nodeid=0;

    /* Loop through the collection. */
    while (hr = pNodes->Next(1, &var, NULL) == S_OK) {
        var.pdispVal->QueryInterface(IID_INode, reinterpret_cast<void **> (&pNode));

        /* Check wether the node is ready. 
         * There are four states:
         *          NodeStatus_Ready = 0,
         *          NodeStatus_Paused = 1,
         *          NodeStatus_Unreachable = 2, probably not a windows cluster node.
         *          NodeStatus_PendingApproval = 3
         */
        hr = pNode->get_Status(&Status);
        if (FAILED(hr)) {
            OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                "ras:ccp:pNode->get_Status failed."));
            ret = ORTE_ERROR;
            goto cleanup;
        }

        /* Get available number of processors on each node. */
        hr = pNode->get_NumberOfIdleProcessors(&idle_processors);
        if (FAILED(hr)) {
            OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                "ras:ccp:pNode->get_NumberOfIdleProcessors failed."));
            ret = ORTE_ERROR;
            goto cleanup;
        }

        /* Do we have enough processors on the available nodes? 
         * Question: How do we get the required number of processors?
         */
        if ( (Status == NodeStatus_Ready) && (idle_processors > 0) ) {

            /* Get node name. */
            hr = pNode->get_Name(&node_name);
            if (FAILED(hr)) {
                OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                    "ras:ccp:pNode->get_Name failed."));
                ret = ORTE_ERROR;
                goto cleanup;
            }

            /* Get node processor architecture. */
            hr = pNode->get_ProcessorArchitecture(&node_arch);
            if (FAILED(hr)) {
                OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                    "ras:ccp:pNode->get_ProcessorArchitecture failed."));
                ret = ORTE_ERROR;
                goto cleanup;
            }

            /* Prevent duplicated nodes in the list*/
            for (item = opal_list_get_first(&new_nodes);
                 opal_list_get_end(&new_nodes) != item;
                 item = opal_list_get_next(item)) {

                node = (orte_node_t*) item;
                if (0 == strcmp(node->name, (char *)node_name)) {
                    ++node->slots;
                    OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                        "ras:ccp:allocate:discover: found -- bumped slots to %d",
                                        node->slots));
                    break;
                }
            }
            /* Did we find it? */

            if (opal_list_get_end(&new_nodes) == item) {

                /* Nope -- didn't find it, so add a new item to the list */

                OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                                    "ras:ccp:allocate:discover: not found -- added to list"));

                node = OBJ_NEW(orte_node_t);

                /* The function _dupenv_s is much safer than getenv on Windows. */
                _dupenv_s(&node->username, &len, "username");

                node->name = _com_util::ConvertBSTRToString(node_name);
                node->launch_id = nodeid;
                node->slots_inuse = 0;
                node->slots_max = 0;
                node->slots = 1;
                opal_list_append(nodelist, &node->super);
            } 
            /* up the nodeid */
            nodeid++;
        }

        pNode->Release();
        VariantClear(&var);
    }

    pNodes->Release();

    if (nodeid > 0) ret = ORTE_SUCCESS;

    /* All done */
cleanup:

    if (ORTE_SUCCESS == ret) {
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:allocate:discover: success"));
    } else {
        OPAL_OUTPUT_VERBOSE((1, orte_ras_base.ras_output,
                            "ras:ccp:allocate:discover: failed (rc=%d)", ret));
    }

    OBJ_DESTRUCT(&new_nodes);
    SysFreeString(node_name);
    SysFreeString(node_arch);

    /* check for timing request - get stop time and report elapsed time if so */
    if (orte_timing) {
        gettimeofday(&stop, NULL);
        opal_output(0, "ras_ccp: time to allocate is %ld usec",
                    (long int)((stop.tv_sec - start.tv_sec)*1000000 +
                               (stop.tv_usec - start.tv_usec)));
        gettimeofday(&start, NULL);
    }
    
    return ret;
}
Beispiel #20
0
rmw_node_t *
rmw_create_node(const char * name, size_t domain_id)
{
  if (!name) {
    RMW_SET_ERROR_MSG("name is null");
    return nullptr;
  }
  DDS::DomainParticipantFactory_var dp_factory = DDS::DomainParticipantFactory::get_instance();
  if (!dp_factory) {
    RMW_SET_ERROR_MSG("failed to get domain participant factory");
    return nullptr;
  }

  DDS::DomainId_t domain = static_cast<DDS::DomainId_t>(domain_id);
  DDS::DomainParticipant * participant = nullptr;

  // Make sure that the OSPL_URI is set, otherwise node creation will fail.
  char * ospl_uri = nullptr;
  const char * ospl_uri_env = "OSPL_URI";
#ifndef _WIN32
  ospl_uri = getenv(ospl_uri_env);
#else
  size_t ospl_uri_size;
  _dupenv_s(&ospl_uri, &ospl_uri_size, ospl_uri_env);
#endif
  if (!ospl_uri) {
    RMW_SET_ERROR_MSG("OSPL_URI not set");
    return nullptr;
  } else {
#ifdef _WIN32
    free(ospl_uri);
#endif
  }

  // Ensure the ROS_DOMAIN_ID env variable is set, otherwise parsing of the config may fail.
  // Also make sure the it is set to the domain_id passed in, otherwise it will fail.
  // But first backup the current ROS_DOMAIN_ID.
  char * ros_domain_id = nullptr;
  const char * env_var = "ROS_DOMAIN_ID";
#ifndef _WIN32
  ros_domain_id = getenv(env_var);
#else
  size_t ros_domain_id_size;
  _dupenv_s(&ros_domain_id, &ros_domain_id_size, env_var);
#endif

  // On Windows, setting the ROS_DOMAIN_ID does not fix the problem, so error early.
#ifdef _WIN32
  if (!ros_domain_id) {
    RMW_SET_ERROR_MSG("environment variable ROS_DOMAIN_ID is not set");
    fprintf(stderr, "[rmw_opensplice_cpp]: error: %s\n", rmw_get_error_string_safe());
    return nullptr;
  }
#endif

  // Set the ROS_DOMAIN_ID explicitly (if not Windows).
#ifndef _WIN32
  auto domain_id_as_string = std::to_string(domain_id);
  int ret = 0;
  ret = setenv(env_var, domain_id_as_string.c_str(), 1);
  if (0 != ret) {
    RMW_SET_ERROR_MSG("failed to set the ROS_DOMAIN_ID");
    return nullptr;
  }
#endif

  participant = dp_factory->create_participant(
    domain, PARTICIPANT_QOS_DEFAULT, NULL, DDS::STATUS_MASK_NONE);
  if (!participant) {
    RMW_SET_ERROR_MSG("failed to create domain participant");
    return NULL;
  }

  // Restore the ROS_DOMAIN_ID if necessary (and not Windows).
#ifndef _WIN32
  if (ros_domain_id) {
    ret = setenv(env_var, ros_domain_id, 1);
    if (0 != ret) {
      RMW_SET_ERROR_MSG("failed to reset the ROS_DOMAIN_ID");
      return nullptr;
    }
  } else {
    // Otherwise unset it again.
    ret = unsetenv(env_var);
    if (0 != ret) {
      RMW_SET_ERROR_MSG("failed to unset the ROS_DOMAIN_ID");
      return nullptr;
    }
  }
#endif

  rmw_node_t * node = nullptr;
  OpenSpliceStaticNodeInfo * node_info = nullptr;
  CustomPublisherListener * publisher_listener = nullptr;
  CustomSubscriberListener * subscriber_listener = nullptr;
  void * buf = nullptr;

  DDS::DataReader * data_reader = nullptr;
  DDS::PublicationBuiltinTopicDataDataReader * builtin_publication_datareader = nullptr;
  DDS::SubscriptionBuiltinTopicDataDataReader * builtin_subscription_datareader = nullptr;
  DDS::Subscriber * builtin_subscriber = participant->get_builtin_subscriber();
  if (!builtin_subscriber) {
    RMW_SET_ERROR_MSG("builtin subscriber handle is null");
    goto fail;
  }

  // setup publisher listener
  data_reader = builtin_subscriber->lookup_datareader("DCPSPublication");
  builtin_publication_datareader =
    DDS::PublicationBuiltinTopicDataDataReader::_narrow(data_reader);
  if (!builtin_publication_datareader) {
    RMW_SET_ERROR_MSG("builtin publication datareader handle is null");
    goto fail;
  }

  buf = rmw_allocate(sizeof(CustomPublisherListener));
  if (!buf) {
    RMW_SET_ERROR_MSG("failed to allocate memory");
    goto fail;
  }
  RMW_TRY_PLACEMENT_NEW(publisher_listener, buf, goto fail, CustomPublisherListener)
  buf = nullptr;
  builtin_publication_datareader->set_listener(publisher_listener, DDS::DATA_AVAILABLE_STATUS);

  data_reader = builtin_subscriber->lookup_datareader("DCPSSubscription");
  builtin_subscription_datareader =
    DDS::SubscriptionBuiltinTopicDataDataReader::_narrow(data_reader);
  if (!builtin_subscription_datareader) {
    RMW_SET_ERROR_MSG("builtin subscription datareader handle is null");
    goto fail;
  }

  // setup subscriber listener
  buf = rmw_allocate(sizeof(CustomSubscriberListener));
  if (!buf) {
    RMW_SET_ERROR_MSG("failed to allocate memory");
    goto fail;
  }
  RMW_TRY_PLACEMENT_NEW(subscriber_listener, buf, goto fail, CustomSubscriberListener)
  buf = nullptr;
  builtin_subscription_datareader->set_listener(subscriber_listener, DDS::DATA_AVAILABLE_STATUS);

  node = rmw_node_allocate();
  if (!node) {
    RMW_SET_ERROR_MSG("failed to allocate rmw_node_t");
    goto fail;
  }

  node->name = reinterpret_cast<const char *>(rmw_allocate(sizeof(char) * strlen(name) + 1));
  if (!node->name) {
    RMW_SET_ERROR_MSG("failed to allocate memory for node name");
    goto fail;
  }
  memcpy(const_cast<char *>(node->name), name, strlen(name) + 1);

  buf = rmw_allocate(sizeof(OpenSpliceStaticNodeInfo));
  if (!buf) {
    RMW_SET_ERROR_MSG("failed to allocate memory");
    goto fail;
  }
  RMW_TRY_PLACEMENT_NEW(node_info, buf, goto fail, OpenSpliceStaticNodeInfo)
  buf = nullptr;
  node_info->participant = participant;
  node_info->publisher_listener = publisher_listener;
  node_info->subscriber_listener = subscriber_listener;

  node->implementation_identifier = opensplice_cpp_identifier;
  node->data = node_info;

  return node;
fail:
  if (participant) {
    if (dp_factory->delete_participant(participant) != DDS::RETCODE_OK) {
      std::stringstream ss;
      ss << "leaking domain participant while handling failure at: " <<
        __FILE__ << ":" << __LINE__ << '\n';
      (std::cerr << ss.str()).flush();
    }
  }
  if (publisher_listener) {
    RMW_TRY_DESTRUCTOR_FROM_WITHIN_FAILURE(
      publisher_listener->~CustomPublisherListener(), CustomPublisherListener)
    rmw_free(publisher_listener);
  }
  if (subscriber_listener) {
    RMW_TRY_DESTRUCTOR_FROM_WITHIN_FAILURE(
      subscriber_listener->~CustomSubscriberListener(), CustomSubscriberListener)
    rmw_free(subscriber_listener);
  }
  if (node_info) {
    RMW_TRY_DESTRUCTOR_FROM_WITHIN_FAILURE(
      node_info->~OpenSpliceStaticNodeInfo(), OpenSpliceStaticNodeInfo)
    rmw_free(node_info);
  }
  if (buf) {
    rmw_free(buf);
  }
  if (node) {
    if (node->name) {
      rmw_free(const_cast<char *>(node->name));
    }
    rmw_node_free(node);
  }
  return nullptr;
}
static void setup_python(int argc, char **argv) {
  char *pathlist = NULL;
  TCHAR szPath[MAX_PATH];
  std::string module_path;
  if (GetModuleFileName(NULL, szPath, MAX_PATH)) {
    CHAR char_path[MAX_PATH] = {0};
    WideCharToMultiByte(CP_UTF8, 0, szPath, -1, char_path, MAX_PATH, NULL, NULL);
    std::string full_path(char_path);
    size_t path_end = full_path.find_last_of('\\');
    if (path_end != std::string::npos)
      module_path = full_path.substr(0, path_end + 1);
  }

#if 0
  if (_dupenv_s(&pathlist, &bufsize, "PYTHONPATH") == 0 && pathlist)
  {
    int len = strlen("PYTHONPATH")+1+strlen(pathlist)+strlen(";python;scripts")+1;
    char *tmp = (char*)malloc(len);
    sprintf_s(tmp, len, "PYTHONPATH=%s;python;scripts", pathlist);
    _putenv(tmp);
    free(tmp);
  }
  else
#endif

  SetDllDirectoryA((module_path + "..").c_str());

  // This should initialize PYTHONPATH, but for some reason it doesn't work when built in VS2010.
  std::string pythonpath;
  pythonpath.append(module_path).append("modules;");
  pythonpath.append(module_path).append("python;");
  pythonpath.append(module_path).append("python\\Lib;");
  pythonpath.append(module_path).append("python\\libs;");
  pythonpath.append(module_path).append("python\\DLLs;");
  _putenv_s("PYTHONHOME", "python");
  _putenv_s("PYTHONPATH", pythonpath.c_str());
  if (pathlist)
    free(pathlist);

  Py_SetProgramName(argv[0]);

  // Here comes some ugly hack to fix PYTHONPATH init problem.
  // Create dummy site package to avoid error import site message from Py_Initialize();
  FILE *pFile;
  pFile = fopen("site.py", "w");
  if (pFile != NULL)
    fclose(pFile);

  Py_Initialize();

  // Delete dummy site module.
  remove("site.py");
  remove("site.pyc");

  PySys_SetArgv(argc, argv);

  // Now import sys and modify PYTHONPATH.
  PyRun_SimpleString("import sys");
  PyRun_SimpleString("sys.path.append('modules')");
  PyRun_SimpleString("sys.path.append('python')");
  PyRun_SimpleString("sys.path.append('python\\Lib')");
  PyRun_SimpleString("sys.path.append('python\\libs')");
  PyRun_SimpleString("sys.path.append('python\\DLLs')");

  // Reload site module with real module from updated PYTHONPATH.
  PyRun_SimpleString("import site");
  PyRun_SimpleString("reload(site)");
}
Beispiel #22
0
// do all the important initialization stuffz
bool InitializepreVentrilo()
{
	std::ifstream fin(strSettingsFile.c_str());
	std::string line;
	if(!std::getline(fin, line))
	{
		char *pProg;
		size_t len;
		errno_t err = _dupenv_s( &pProg, &len, "PROGRAMFILES" );
		if(!err)
		{
			settings.ventPath = pProg;
			settings.ventPath += "\\Ventrilo\\Ventrilo.exe";
			free( pProg );
		}
		else
			settings.ventPath = "";
	}
	else
		settings.ventPath = line;
	if(!(fin >> settings.pauseType))
		settings.pauseType = (PAUSE_TYPE_OTHERS | PAUSE_TYPE_SELF);
	if(!(fin >> settings.mediaPlayer))
		settings.mediaPlayer = MEDIA_PLAYER_WINAMP;
	if(!(fin >> settings.bAdjustVolume))
		settings.bAdjustVolume = true;
	if(!(fin >> settings.nAdjustedVolume))
		settings.nAdjustedVolume = 29;
	fin.close();
	SaveSettings();


	hinstDLL = LoadLibrary("prevent.dll");
	if(hinstDLL == NULL)
	{
		MessageBox(NULL, "Unable to load prevent.dll", NULL, NULL);
		return false;
	}


	pSetVentHook = (LPSetVentHook)GetProcAddress(hinstDLL, "SetVentHook");
	pKillVentHook = GetProcAddress(hinstDLL, "KillVentHook");
	pSetMediaPlayer = (LPdwhwnd)GetProcAddress(hinstDLL, "SetMediaPlayer");
	pSetMuteType = (LPSetMuteType)GetProcAddress(hinstDLL, "SetMuteType");
	if(pSetVentHook == NULL || pKillVentHook == NULL || pSetMediaPlayer == NULL || pSetMuteType == NULL)
	{
		MessageBox(NULL, "Unable to load DLL functions", NULL, NULL);
		return false;
	}


	hWndVent = FindWindow( NULL, "Ventrilo");
	if(hWndVent == NULL)
	{
		if((int)ShellExecute(NULL, "open", settings.ventPath.c_str(), "", NULL, SW_SHOWNORMAL) <= 32)
		{
			MessageBox(NULL, "Please select the Ventrilo executable.", NULL, NULL);

			OPENFILENAME ofn;
			char szFileName[MAX_PATH] = "";
			ZeroMemory(&ofn, sizeof(ofn));
			ofn.lStructSize = sizeof(ofn);
			ofn.hwndOwner = NULL;
			ofn.lpstrFilter = "Ventrilo.exe\0Ventrilo.exe\0All Files (*.*)\0*.*\0";
			ofn.lpstrFile = szFileName;
			ofn.nMaxFile = MAX_PATH;
			ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
			ofn.lpstrDefExt = "exe";

			if(GetOpenFileName(&ofn))
			{
				settings.ventPath = szFileName;
				ShellExecute(NULL, "open", settings.ventPath.c_str(), "", NULL, SW_SHOWNORMAL);
			}
		}
	}

	hThreadVent = CreateThread(
				NULL,				// default security attributes
				0,					// use default stack size  
				ThreadVentProc,		// thread function 
				NULL,				// argument to thread function 
				0,					// use default creation flags 
				&dwThreadVentId);	// returns the thread identifier
	if(hThreadVent == NULL)
	{
		MessageBox(NULL, "Error.", NULL, NULL);
		return false;
	}

	OnMediaPlayer();

	return true;
}
Beispiel #23
0
/*
 * Perform initialization. This usually happens on the program startup
 * and restarting after glutMainLoop termination...
 */
void FGAPIENTRY glutInit( int* pargc, char** argv )
{
    char* displayName = NULL;
	char* geometry = NULL;
	size_t len;
	errno_t err = 0;

    int i, j, argc = *pargc;

    if( fgState.Initialised )
        fgError( "illegal glutInit() reinitialization attempt" );

    if (pargc && *pargc && argv && *argv && **argv)
    {
        fgState.ProgramName = strdup (*argv);

        if( !fgState.ProgramName )
            fgError ("Could not allocate space for the program's name.");
    }

    fgCreateStructure( );

    fgElapsedTime( );

    /* check if GLUT_FPS env var is set */
#if !TARGET_HOST_WINCE
    {
        char *fps = NULL;
		err = _dupenv_s( &fps, &len, "GLUT_FPS" );
        if( len )
        {
            int interval;
            sscanf_s( fps, "%d", &interval );

            if( interval <= 0 )
                fgState.FPSInterval = 5000;  /* 5000 millisecond default */
            else
                fgState.FPSInterval = interval;
        }
    }

	err = _dupenv_s( &displayName, &len, "DISPLAY" );

    for( i = 1; i < argc; i++ )
    {
        if( strcmp( argv[ i ], "-display" ) == 0 )
        {
            if( ++i >= argc )
                fgError( "-display parameter must be followed by display name" );

            displayName = argv[ i ];

            argv[ i - 1 ] = NULL;
            argv[ i     ] = NULL;
            ( *pargc ) -= 2;
        }
        else if( strcmp( argv[ i ], "-geometry" ) == 0 )
        {
            if( ++i >= argc )
                fgError( "-geometry parameter must be followed by window "
                         "geometry settings" );

            geometry = argv[ i ];

            argv[ i - 1 ] = NULL;
            argv[ i     ] = NULL;
            ( *pargc ) -= 2;
        }
        else if( strcmp( argv[ i ], "-direct" ) == 0)
        {
            if( fgState.DirectContext == GLUT_FORCE_INDIRECT_CONTEXT )
                fgError( "parameters ambiguity, -direct and -indirect "
                    "cannot be both specified" );

            fgState.DirectContext = GLUT_FORCE_DIRECT_CONTEXT;
            argv[ i ] = NULL;
            ( *pargc )--;
        }
        else if( strcmp( argv[ i ], "-indirect" ) == 0 )
        {
            if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
                fgError( "parameters ambiguity, -direct and -indirect "
                    "cannot be both specified" );

            fgState.DirectContext = GLUT_FORCE_INDIRECT_CONTEXT;
            argv[ i ] = NULL;
            (*pargc)--;
        }
        else if( strcmp( argv[ i ], "-iconic" ) == 0 )
        {
            fgState.ForceIconic = GL_TRUE;
            argv[ i ] = NULL;
            ( *pargc )--;
        }
        else if( strcmp( argv[ i ], "-gldebug" ) == 0 )
        {
            fgState.GLDebugSwitch = GL_TRUE;
            argv[ i ] = NULL;
            ( *pargc )--;
        }
        else if( strcmp( argv[ i ], "-sync" ) == 0 )
        {
            fgState.XSyncSwitch = GL_TRUE;
            argv[ i ] = NULL;
            ( *pargc )--;
        }
    }

    /* Compact {argv}. */
    for( i = j = 1; i < *pargc; i++, j++ )
    {
        /* Guaranteed to end because there are "*pargc" arguments left */
        while ( argv[ j ] == NULL )
            j++;
        if ( i != j )
            argv[ i ] = argv[ j ];
    }

#endif /* TARGET_HOST_WINCE */

    /*
     * Have the display created now. If there wasn't a "-display"
     * in the program arguments, we will use the DISPLAY environment
     * variable for opening the X display (see code above):
     */
    fghInitialize( displayName );

    /*
     * Geometry parsing deffered until here because we may need the screen
     * size.
     */

    if (geometry )
    {
        unsigned int parsedWidth, parsedHeight;
        int mask = XParseGeometry( geometry,
                                   &fgState.Position.X, &fgState.Position.Y,
                                   &parsedWidth, &parsedHeight );
        /* TODO: Check for overflow? */
        fgState.Size.X = parsedWidth;
        fgState.Size.Y = parsedHeight;

        if( (mask & (WidthValue|HeightValue)) == (WidthValue|HeightValue) )
            fgState.Size.Use = GL_TRUE;

        if( mask & XNegative )
            fgState.Position.X += fgDisplay.ScreenWidth - fgState.Size.X;

        if( mask & YNegative )
            fgState.Position.Y += fgDisplay.ScreenHeight - fgState.Size.Y;

        if( (mask & (XValue|YValue)) == (XValue|YValue) )
            fgState.Position.Use = GL_TRUE;
    }
}
/**
 * Windows DLL entry point function. This ensures that the environment
 * variable \c TWEEK_BASE_DIR is set as soon as this DLL is attached to the
 * process. If it is not set, then it sets it based on an assumption about the
 * structure of a Tweek installation. More specifically, an assumption is made
 * that this DLL lives in the \c lib subdirectory of the Tweek installation.
 * Therefore, the root of the Tweek installation is the parent of the
 * directory containing this DLL.
 */
BOOL __stdcall DllMain(HINSTANCE module, DWORD reason, LPVOID reserved)
{
   switch (reason)
   {
      case DLL_PROCESS_ATTACH:
         {
            char* env_dir(NULL);
#if defined(_MSC_VER) && _MSC_VER >= 1400
            size_t len;
            _dupenv_s(&env_dir, &len, "TWEEK_BASE_DIR");
#else
            env_dir = std::getenv("TWEEK_BASE_DIR");
#endif

            try
            {
               fs::path base_dir;

               // If TWEEK_BASE_DIR is not set, look up the path to this DLL
               // and use it to provide a default setting for that environment
               // variable.
               if ( NULL == env_dir )
               {
                  char tmppath[1024];
                  std::memset(tmppath, 0, sizeof(tmppath));
                  GetModuleFileName(module, tmppath, sizeof(tmppath));

                  const fs::path dll_path(tmppath, fs::native);
                  base_dir = dll_path.branch_path().branch_path();
#if (defined(JUGGLER_DEBUG) || defined(TWEEK_DEBUG)) && ! defined(_DEBUG)
                  // The debug DLL linked against the release runtime is in
                  // <base_dir>\lib\debug.
                  base_dir = base_dir.branch_path();
#endif

                  const std::string base_dir_str =
                     base_dir.native_directory_string();

#if defined(_MSC_VER) && _MSC_VER >= 1400
                  _putenv_s("TWEEK_BASE_DIR", base_dir_str.c_str());
#else
                  std::ostringstream env_stream;
                  env_stream << "TWEEK_BASE_DIR=" << base_dir_str;
                  putenv(env_stream.str().c_str());
#endif
               }
               else
               {
                  base_dir = fs::path(env_dir, fs::native);
#if defined(_MSC_VER) && _MSC_VER >= 1400
                  std::free(env_dir);
                  env_dir = NULL;
#endif
               }

#if defined(_MSC_VER) && _MSC_VER >= 1400
               _dupenv_s(&env_dir, &len, "TWEEK_DATA_DIR");
#else
               env_dir = std::getenv("TWEEK_DATA_DIR");
#endif

               // If TWEEK_BASE_DIR is not set, set a default relative to
               // base_dir.
               if ( NULL == env_dir )
               {
                  fs::path data_dir(base_dir / "share" / "tweek");
                  const std::string data_dir_str =
                     data_dir.native_directory_string();

#if defined(_MSC_VER) && _MSC_VER >= 1400
                  _putenv_s("TWEEK_DATA_DIR", data_dir_str.c_str());
#else
                  std::ostringstream env_stream;
                  env_stream << "TWEEK_DATA_DIR=" << data_dir_str;
                  putenv(env_stream.str().c_str());
#endif
               }
#if defined(_MSC_VER) && _MSC_VER >= 1400
               else
               {
                  std::free(env_dir);
                  env_dir = NULL;
               }
#endif
            }
            catch (fs::filesystem_error& ex)
            {
               std::cerr << "Automatic assignment of Tweek environment "
                         << "variables failed:\n" << ex.what() << std::endl;

#if defined(_MSC_VER) && _MSC_VER >= 1400
               if ( NULL != env_dir )
               {
                  std::free(env_dir);
               }
#endif
            }
         }
         break;
      default:
         break;
   }

   return TRUE;
}
Beispiel #25
0
void main()
{
	if (!CONFIG::get("saveFile", fileName))
	{
		char *pValue;
		size_t len;
		errno_t err = _dupenv_s(&pValue, &len, "USERPROFILE");
		if (err)
			fileName = string("C:\\savedcoords.txt");
		else
			fileName = string(pValue) + "\\Documents\\Rockstar Games\\GTA V\\savedcoords.txt";
	}

	sendPlayerMessage("GTAV DevHelper by Funtik Initialized");
	sendPlayerMessage("Press F6 to open chat textbox");

	auto loadEntities = []()
	{
		if (!CONFIG::loadList("devhelper/vehicles.txt", vehicles))
			sendPlayerMessage("Can not load devhelper/vehicles.txt", 255, 0, 0);
		else
		{
			maxVehNr = vehicles.size() - 1;
			sendPlayerMessage("Vehicles loaded", 0, 255, 0);
		}

		if (!CONFIG::loadList("devhelper/peds.txt", peds))
			sendPlayerMessage("Can not load devhelper/peds.txt", 255, 0, 0);
		else
		{
			maxPedNr = peds.size() - 1;
			sendPlayerMessage("Peds loaded", 0, 255, 0);
		}

		if (!CONFIG::loadList("devhelper/objects.txt", objects))
			sendPlayerMessage("Can not load devhelper/objects.txt", 255, 0, 0);
		else
		{
			maxObjNr = objects.size() - 1;
			sendPlayerMessage("Objects loaded", 0, 255, 0);
		}
	};
	thread(loadEntities).detach();

	while (true)
	{
		Player player = PLAYER::PLAYER_ID();
		Ped playerPed = PLAYER::PLAYER_PED_ID();
		if (ENTITY::DOES_ENTITY_EXIST(playerPed))
		{
			Hash model = ENTITY::GET_ENTITY_MODEL(playerPed);
			if (ENTITY::IS_ENTITY_DEAD(playerPed) || PLAYER::IS_PLAYER_BEING_ARRESTED(player, TRUE))
			{
				if (model != GAMEPLAY::GET_HASH_KEY("player_zero") &&
					model != GAMEPLAY::GET_HASH_KEY("player_one") &&
					model != GAMEPLAY::GET_HASH_KEY("player_two"))
				{
					model = GAMEPLAY::GET_HASH_KEY("player_zero");
					STREAMING::REQUEST_MODEL(model);
					while (!STREAMING::HAS_MODEL_LOADED(model))
						WAIT(0);
					PLAYER::SET_PLAYER_MODEL(player, model);
					PED::SET_PED_DEFAULT_COMPONENT_VARIATION(playerPed);
					STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(model);
					while (ENTITY::IS_ENTITY_DEAD(PLAYER::PLAYER_PED_ID()) || PLAYER::IS_PLAYER_BEING_ARRESTED(player, TRUE))
						WAIT(0);
				}
			}
		}
		if (modKitId != -1)
		{
			VEHICLE::SET_VEHICLE_MOD_KIT(lastVehId, modKitId);
			sendPlayerMessage("Your car\'s modkit changed", 0, 255, 0);
			modKitId = -1;
		}
		if (vehCreateId != -1)
		{
			stringstream buff;
			DWORD model = (vehCreateId == -2) ? vehHash : GAMEPLAY::GET_HASH_KEY((char *)vehicles[vehCreateId].c_str());
			buff << "Loading vehicle [" << vehCreateId << "] " << ((vehCreateId == -2) ? vehName : vehicles[vehCreateId]) << ", Hash = 0x" << std::hex << model;
			sendPlayerMessage(buff.str());
			if (STREAMING::IS_MODEL_IN_CDIMAGE(model) && STREAMING::IS_MODEL_A_VEHICLE(model))
			{
				STREAMING::REQUEST_MODEL(model);
				while (!STREAMING::HAS_MODEL_LOADED(model)) WAIT(0);
				Vector3 coords = ENTITY::GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS(PLAYER::PLAYER_PED_ID(), 0.0, 5.0, 0.0);
				Vehicle veh = VEHICLE::CREATE_VEHICLE(model, coords.x, coords.y, coords.z, 0.0, 1, 1);
				VEHICLE::SET_VEHICLE_ON_GROUND_PROPERLY(veh);

				ENTITY::SET_ENTITY_HEADING(veh, ENTITY::GET_ENTITY_HEADING(PLAYER::PLAYER_PED_ID()));
				PED::SET_PED_INTO_VEHICLE(PLAYER::PLAYER_PED_ID(), veh, -1);

				WAIT(0);
				STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(model);
				ENTITY::SET_VEHICLE_AS_NO_LONGER_NEEDED(&veh);
				sendPlayerMessage(string("Vehicle ") + ((vehCreateId == -2) ? vehName : vehicles[vehCreateId]) + " created.", 0, 255, 0);
			}
			else
			{
				sendPlayerMessage("Error when creating vehicle", 255, 0, 0);
			}
			vehCreateId = -1;
		}
		if (chatEnabled)
		{
			GRAPHICS::DRAW_RECT(0.0f, 0.0f, 0.9f, 0.645f, 0, 0, 0, 200);
			size_t first = (chatLines.size() > 10) ? (chatLines.size() - 10) : 0;
			for (size_t i = first, c = 0; i < chatLines.size(); ++i, ++c)
			{
				drawText(chatLines[i].text, 0.0f, ((float)c)*(0.03f), chatLines[i].r, chatLines[i].g, chatLines[i].b);
			}
			
		}
		if (chatWrite)
		{
			string chatText(curChatText);
			chatText.insert(chatText.begin() + cursorPos, '_');
			GRAPHICS::DRAW_RECT(0.0f, 0.340f, 0.9f, 0.040f, 125, 125, 125, 255);
			drawText("> " + chatText, 0.0f, 0.330f, 255, 255, 255);
			UI::SET_PAUSE_MENU_ACTIVE(false);
		}
		if (pedId != -1)
		{
			Hash skin = (pedId == -2) ? pedHash : GAMEPLAY::GET_HASH_KEY((char*)peds[pedId].c_str());
			if (STREAMING::IS_MODEL_IN_CDIMAGE(skin) && STREAMING::IS_MODEL_VALID(skin))
			{
				STREAMING::REQUEST_MODEL(skin);
				while (!STREAMING::HAS_MODEL_LOADED(skin))
					WAIT(0);
				PLAYER::SET_PLAYER_MODEL(PLAYER::PLAYER_ID(), skin);
				PED::SET_PED_DEFAULT_COMPONENT_VARIATION(PLAYER::PLAYER_PED_ID());
				STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(skin);
				sendPlayerMessage(string("Your model changed to ") + ((pedId == -2) ? pedName : peds[pedId]), 0, 200, 0);
			}
			else
				sendPlayerMessage("Unknown error!", 255, 0, 0);
			pedId = -1;
		}
		if (objectEditor)
		{
			/*for (unsigned i = 0; i < lil::Object::_data.size(); ++i)
			{
				Vector3 pos = lil::Object::_data[i]->GetPosition();
				GRAPHICS::DRAW_DEBUG_TEXT_2D("Object", pos.x, pos.y, pos.z, 255, 255, 255, 255);
			}*/
			Vector3 pos = playerObject->GetPosition();
			Vector3 rot = playerObject->GetRotation();
			drawText("Object parameters:", 0.1f, 0.8f, 255, 255, 255);
			char buff[256];
			sprintf_s(buff, "Position X: %.4f", pos.x);
			drawText(buff, 0.01f, 0.815f, 255, 255, 255);
			sprintf_s(buff, "Position Y: %.4f", pos.y);
			drawText(buff, 0.01f, 0.83f, 255, 255, 255);
			sprintf_s(buff, "Position Z: %.4f", pos.z);
			drawText(buff, 0.01f, 0.845f, 255, 255, 255);

			sprintf_s(buff, "Rotation X: %.4f", rot.x);
			drawText(buff, 0.01f, 0.86f, 255, 255, 255);
			sprintf_s(buff, "Rotation Y: %.4f", rot.y);
			drawText(buff, 0.01f, 0.875f, 255, 255, 255);
			sprintf_s(buff, "Rotation Z: %.4f", rot.z);
			drawText(buff, 0.01f, 0.89f, 255, 255, 255);
		}
		if (objId != -1)
		{
			Hash object = (objId == -2) ? pedHash : GAMEPLAY::GET_HASH_KEY((char*)objects[objId].c_str());
			if (STREAMING::IS_MODEL_VALID(object))
			{
				STREAMING::REQUEST_MODEL(object);
				while (!STREAMING::HAS_MODEL_LOADED(object))
					WAIT(0);
				if (!objectEditor)
				{
					objectEditor = true;
					GRAPHICS::SET_DEBUG_LINES_AND_SPHERES_DRAWING_ACTIVE(true);
					UI::DISPLAY_HUD(false);
					UI::DISPLAY_RADAR(false);
				}
				lil::Object *curObj = new lil::Object(object, objPos.x, objPos.y, objPos.z);
				playerObject = curObj;

				STREAMING::SET_MODEL_AS_NO_LONGER_NEEDED(object);
				ENTITY::SET_ENTITY_VISIBLE(PLAYER::PLAYER_PED_ID(), false);
				PLAYER::SET_PLAYER_CONTROL(PLAYER::PLAYER_ID(), false, 0);
				if(!CAM::DOES_CAM_EXIST(playerCam))
					playerCam = CAM::CREATE_CAMERA(0x19286a9, 0);
				if (CAM::DOES_CAM_EXIST(playerCam)) {
					CAM::SET_CAM_ACTIVE(playerCam, 1);
					CAM::RENDER_SCRIPT_CAMS(true, 0, playerCam, true, 0);
					playerObject->PointCam(playerCam);
				}
				sendPlayerMessage(string("Object created ") + ((objId == -2) ? objName : objects[objId]), 0, 200, 0);
			}
			else
				sendPlayerMessage("Unknown error!", 255, 0, 0);
			objId = -1;
		}
		WAIT(0);
	}
}
/* ---------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
	struct aiLogStream stream;

	glutInitWindowSize(900,600);
	glutInitWindowPosition(100,100);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
	glutInit(&argc, argv);

	glutCreateWindow("Assimp - Very simple OpenGL sample");
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);

	/* get a handle to the predefined STDOUT log stream and attach
	   it to the logging system. It remains active for all further
	   calls to aiImportFile(Ex) and aiApplyPostProcessing. */
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_STDOUT,NULL);
	aiAttachLogStream(&stream);

	/* ... same procedure, but this stream now writes the
	   log messages to assimp_log.txt */
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_FILE,"assimp_log.txt");
	aiAttachLogStream(&stream);

	/* the model name can be specified on the command line. If none
	  is specified, we try to locate one of the more expressive test 
	  models from the repository (/models-nonbsd may be missing in 
	  some distributions so we need a fallback from /models!). */
	if( 0 != loadasset( argc >= 2 ? argv[1] : "X/dwarf.x")) {
		if( argc != 1 || (0 != loadasset( "X/dwarf.x") && 0 != loadasset( "X/Testwuson.X"))) { 
			return -1;
		}
	}

	glClearColor(0.1f,0.1f,0.1f,1.f);

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);    /* Uses default lighting parameters */

	glEnable(GL_DEPTH_TEST);

	glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
	glEnable(GL_NORMALIZE);

	/* XXX docs say all polygons are emitted CCW, but tests show that some aren't. */
	char * buf = 0;
	size_t sz = 0;
	if(_dupenv_s(&buf,&sz,"MODEL_IS_BROKEN"))
		glFrontFace(GL_CW);

	glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);

	glutGet(GLUT_ELAPSED_TIME);
	glutMainLoop();

	/* cleanup - calling 'aiReleaseImport' is important, as the library 
	   keeps internal resources until the scene is freed again. Not 
	   doing so can cause severe resource leaking. */
	aiReleaseImport(scene);

	/* We added a log stream to the library, it's our job to disable it
	   again. This will definitely release the last resources allocated
	   by Assimp.*/
	aiDetachAllLogStreams();
	return 0;
}
Beispiel #27
0
/*
* getopt_internal --
*  Parse argc/argv argument vector.  Called by user level routines.
*/
static int
getopt_internal(int nargc, char * const *nargv, const char *options,
const struct option *long_options, int *idx, int flags)
{
    const char *oli;                /* option letter list index */
    int optchar, short_too;
    static int posixly_correct = -1;

    if (options == NULL)
        return (-1);

    /*
    * XXX Some GNU programs (like cvs) set optind to 0 instead of
    * XXX using optreset.  Work around this braindamage.
    */
    if (optind == 0)
        optind = optreset = 1;

    /*
    * Disable GNU extensions if POSIXLY_CORRECT is set or options
    * string begins with a '+'.
    */
	if (posixly_correct == -1 || optreset){
		char *p;
		size_t len;
		auto ret=_dupenv_s(&p, &len, "POSIXLY_CORRECT");
		posixly_correct = (ret == 0);
	}
    if (*options == '-')
        flags |= FLAG_ALLARGS;
    else if (posixly_correct || *options == '+')
        flags &= ~FLAG_PERMUTE;
    if (*options == '+' || *options == '-')
        options++;

    optarg = NULL;
    if (optreset)
        nonopt_start = nonopt_end = -1;
start:
    if (optreset || !*place) {      /* update scanning pointer */
        optreset = 0;
        if (optind >= nargc) {          /* end of argument vector */
            place = EMSG;
            if (nonopt_end != -1) {
                /* do permutation, if we have to */
                permute_args(nonopt_start, nonopt_end,
                    optind, nargv);
                optind -= nonopt_end - nonopt_start;
            }
            else if (nonopt_start != -1) {
                /*
                * If we skipped non-options, set optind
                * to the first of them.
                */
                optind = nonopt_start;
            }
            nonopt_start = nonopt_end = -1;
            return (-1);
        }
        if (*(place = nargv[optind]) != '-' ||
            (place[1] == '\0' && strchr(options, '-') == NULL)) {
            place = EMSG;       /* found non-option */
            if (flags & FLAG_ALLARGS) {
                /*
                * GNU extension:
                * return non-option as argument to option 1
                */
                optarg = nargv[optind++];
                return (INORDER);
            }
            if (!(flags & FLAG_PERMUTE)) {
                /*
                * If no permutation wanted, stop parsing
                * at first non-option.
                */
                return (-1);
            }
            /* do permutation */
            if (nonopt_start == -1)
                nonopt_start = optind;
            else if (nonopt_end != -1) {
                permute_args(nonopt_start, nonopt_end,
                    optind, nargv);
                nonopt_start = optind -
                    (nonopt_end - nonopt_start);
                nonopt_end = -1;
            }
            optind++;
            /* process next argument */
            goto start;
        }
        if (nonopt_start != -1 && nonopt_end == -1)
            nonopt_end = optind;

        /*
        * If we have "-" do nothing, if "--" we are done.
        */
        if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
            optind++;
            place = EMSG;
            /*
            * We found an option (--), so if we skipped
            * non-options, we have to permute.
            */
            if (nonopt_end != -1) {
                permute_args(nonopt_start, nonopt_end,
                    optind, nargv);
                optind -= nonopt_end - nonopt_start;
            }
            nonopt_start = nonopt_end = -1;
            return (-1);
        }
    }

    /*
    * Check long options if:
    *  1) we were passed some
    *  2) the arg is not just "-"
    *  3) either the arg starts with -- we are getopt_long_only()
    */
    if (long_options != NULL && place != nargv[optind] &&
        (*place == '-' || (flags & FLAG_LONGONLY))) {
        short_too = 0;
        if (*place == '-')
            place++;        /* --foo long option */
        else if (*place != ':' && strchr(options, *place) != NULL)
            short_too = 1;      /* could be short option too */

        optchar = parse_long_options(nargv, options, long_options,
            idx, short_too);
        if (optchar != -1) {
            place = EMSG;
            return (optchar);
        }
    }

    if ((optchar = (int)*place++) == (int)':' ||
        (optchar == (int)'-' && *place != '\0') ||
        (oli = strchr(options, optchar)) == NULL) {
        /*
        * If the user specified "-" and  '-' isn't listed in
        * options, return -1 (non-option) as per POSIX.
        * Otherwise, it is an unknown option character (or ':').
        */
        if (optchar == (int)'-' && *place == '\0')
            return (-1);
        if (!*place)
            ++optind;
        if (PRINT_ERROR)
            warnx(illoptchar, optchar);
        optopt = optchar;
        return (BADCH);
    }
    if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
        /* -W long-option */
        if (*place)         /* no space */
            /* NOTHING */;
        else if (++optind >= nargc) {   /* no arg */
            place = EMSG;
            if (PRINT_ERROR)
                warnx(recargchar, optchar);
            optopt = optchar;
            return (BADARG);
        }
        else              /* white space */
            place = nargv[optind];
        optchar = parse_long_options(nargv, options, long_options,
            idx, 0);
        place = EMSG;
        return (optchar);
    }
    if (*++oli != ':') {            /* doesn't take argument */
        if (!*place)
            ++optind;
    }
    else {                /* takes (optional) argument */
        optarg = NULL;
        if (*place)         /* no white space */
            optarg = place;
        else if (oli[1] != ':') {   /* arg not optional */
            if (++optind >= nargc) {    /* no arg */
                place = EMSG;
                if (PRINT_ERROR)
                    warnx(recargchar, optchar);
                optopt = optchar;
                return (BADARG);
            }
            else
                optarg = nargv[optind];
        }
        place = EMSG;
        ++optind;
    }
    /* dump back option letter */
    return (optchar);
}
int
clemuGPU :: initDevice(void)
{
int ret = CL_EMU_SUCCESS;
   if ( !IsInit())
   {


 char  *env_root;
 size_t var_len;
 char root_location[512];
 char propert_file_location[512];
 FILE * property_file;



      _dupenv_s(&env_root,&var_len, "CLEMU_ROOT");
 
	  assert(var_len > 0);
	  if ( !var_len )
	  {
        return(CL_EMU_FAILURE);
	  }
	  strcpy_s(root_location, 512,env_root);
      if ( root_location[var_len-1] != '\\' )
	  {
         root_location[var_len-1] = '\\';
         root_location[var_len] = 0;
	  }
    
      sprintf_s(propert_file_location,512,"%s%s\\%s.txt", root_location, DEFAULTE_PROPERTY_FOLDER, DEFAULT_EMULATOR_PROPERTIES_NM);
	  property_file = fopen( propert_file_location,"rt");
	  if ( property_file )
	  {
char in_buffer[512];
char data_buffer[512];
char format_buffer[512];
int class_len = strlen("class=");
int found_class, found_device;

          fgets( in_buffer, 512, property_file);
          sscanf(in_buffer, "emu_class=%s\n",  data_buffer);
		  SetDevClass( (const char * )data_buffer);

          fgets( in_buffer, 512, property_file);
          sscanf(in_buffer, "emu_name=%s\n",  data_buffer);
		  SetDevNm( (const char * )data_buffer);

          found_class = 0;
		  while(fgets( in_buffer, 512, property_file))
		  {
             sscanf(in_buffer, "class=%s\n",  data_buffer);
			 if  (!strcmp(data_buffer, m_class))
			 {
                    found_class = 1;
				    break;
			 }
		  }

		  if ( found_class )
		  {
               found_device = 0;
		       while(fgets( in_buffer, 512, property_file))
		       {
                    sscanf(in_buffer, "name=%s\n",  data_buffer);
			        if  (!strcmp(data_buffer, m_name))
			        {
                         found_device = 1;
				         break;
			        }
		       }
			   if ( found_device )
			   {
		    int propery;
/*
   m_nbr_groupsperSIMD = 2;
   m_nbr_SE = 1;
   m_nbr_SIMD = 1;
   m_wavefront_size = 64;
   m_local_mem_sz = (1 << 15);
*/

				   for(int p = 0; emulator_device_properties_nm[p]; p++)
				   {
				      sprintf_s(format_buffer,512,"%s.%s=%%d\n", m_name,emulator_device_properties_nm[p]);
                      fscanf(property_file, format_buffer,  &propery);
                      if ( !strcmp(emulator_device_properties_nm[p], "se" ) )
					  {
                          m_nbr_SE = propery;
					  }
                      if ( !strcmp(emulator_device_properties_nm[p], "SIMD" ) )
					  {
						  m_nbr_SIMD = propery;
					  }
                      if ( !strcmp(emulator_device_properties_nm[p], "width" ) )
					  {
						  m_wavefront_size = propery;
					  }
                      if ( !strcmp(emulator_device_properties_nm[p], "local_memory" ) )
					  {
						  m_local_mem_sz = propery;
					  }
                      if ( !strcmp(emulator_device_properties_nm[p], "groups_per_SIMD" ) )
					  {
						  m_nbr_groupsperSIMD = propery;
					  }

				   }
				   

// ALIGNED??
                    m_localMem = new __int64*[GetNbrSIMD()];
	                assert(m_localMem);
	                for(int i = 0; i < GetNbrSIMD(); i++)
	                {
                        m_localMem[i] = (__int64*)new __int64[GetTotalLclSz()];
	                    assert(m_localMem[i]);
	                }
	                m_init = 1;
			   }
		  }
		fclose(property_file);
	  }
   }
   return(ret);
}
Beispiel #29
0
std::string Sys::GetConfigPath( std::string appname ) {
	char path[EE_MAX_CFG_PATH_LEN];

	#if EE_PLATFORM == EE_PLATFORM_WIN
		#ifdef EE_COMPILER_MSVC

		char * ppath;
		size_t ssize = EE_MAX_CFG_PATH_LEN;

		_dupenv_s( &ppath, &ssize, "APPDATA" );

		String::StrCopy( path, ppath, EE_MAX_CFG_PATH_LEN );

		free( ppath );

		if( !ssize )
			return std::string();

		#else
		char * home = getenv("APPDATA");

		if( !home )
			return std::string();

		_snprintf(path, EE_MAX_CFG_PATH_LEN, "%s\\%s", home, appname.c_str() );

		#endif
	#elif EE_PLATFORM == EE_PLATFORM_MACOSX
		char *home = getenv("HOME");

		if( NULL == home ) {
			return std::string();
		}

		snprintf(path, EE_MAX_CFG_PATH_LEN, "%s/Library/Application Support/%s", home, appname.c_str() );
	#elif EE_PLATFORM == EE_PLATFORM_HAIKU
		char *home = getenv("HOME");

		if( NULL == home ) {
			return std::string();
		}

		snprintf(path, EE_MAX_CFG_PATH_LEN, "%s/config/settings/%s", home, appname.c_str() );
	#elif EE_PLATFORM == EE_PLATFORM_LINUX || EE_PLATFORM == EE_PLATFORM_BSD || EE_PLATFORM == EE_PLATFORM_SOLARIS
		char * config = getenv("XDG_CONFIG_HOME");

		if ( NULL != config ) {
			snprintf(path, EE_MAX_CFG_PATH_LEN, "%s/%s", config, appname.c_str() );
		} else {
			char *home = getenv("HOME");

			if( NULL == home ) {
				return std::string();
			}

			snprintf(path, EE_MAX_CFG_PATH_LEN, "%s/.config/%s", home, appname.c_str() );
		}
	#elif EE_PLATFORM == EE_PLATFORM_IOS
		return GetProcessPath() + "config";
	#elif EE_PLATFORM == EE_PLATFORM_ANDROID
		if ( NULL != Window::cEngine::instance() )
			return Window::cEngine::instance()->GetCurrentWindow()->GetInternalStoragePath();

		return std::string();
	#else
		#warning Sys::GetConfigPath not implemented for this platform ( it will use HOME directory + /.appname )

		char *home = getenv("HOME");

		if( NULL == home ) {
			return std::string();
		}

		snprintf(path, EE_MAX_CFG_PATH_LEN, "%s/.%s", home, appname.c_str() );
    #endif

	return std::string( path );
}
Beispiel #30
0
int GetGraceSerializationPaths(int &OutputCount, char **List, int MaxCount)
{
	OutputCount = 0;
	if (*List == NULL)
		return 1;
	//add local directory
	{
		char *LocalPath = new char[2];
		strcpy_s(LocalPath, 2, ".");
		if (DirExists(LocalPath) && OutputCount<MaxCount)
			List[OutputCount++] = LocalPath;
		else
			delete LocalPath;
	}

	//add temp directory 1
	{
		char *TempPath = new char[500];
		DWORD ret = GetTempPath(500, TempPath);
		if (ret < MAX_PATH && ret != 0)
		{
			RemoveEndSlashes(TempPath);
			if (HaveStringInList(TempPath, List, OutputCount) == 0 && DirExists(TempPath) && OutputCount<MaxCount)
				List[OutputCount++] = TempPath;
			else
				delete[] TempPath;
		}
		else
			delete[] TempPath;
	}

	//add temp directory 2
	{
		char *env_p;
		size_t len;
		errno_t err = _dupenv_s(&env_p, &len, "TMP");
		if (err == 0 && len > 0)
		{
			RemoveEndSlashes(env_p);
			if (HaveStringInList(env_p, List, OutputCount) == 0 && DirExists(env_p) && OutputCount < MaxCount)
			{
				char *TempPath = new char[500];
				strcpy_s(TempPath, 500, env_p);
				List[OutputCount++] = TempPath;
			}
			free(env_p);
		}
	}

	//add temp directory 3
	{
		char *env_p;
		size_t len;
		errno_t err = _dupenv_s(&env_p, &len, "TEMP");
		if (err == 0 && len > 0)
		{
			RemoveEndSlashes(env_p);
			if (HaveStringInList(env_p, List, OutputCount) == 0 && DirExists(env_p) && OutputCount < MaxCount)
			{
				char *TempPath = new char[500];
				strcpy_s(TempPath, 500, env_p);
				List[OutputCount++] = TempPath;
			}
			free(env_p);
		}
	}

	//add temp directory 4
	{
		char *env_p;
		size_t len;
		errno_t err = _dupenv_s(&env_p, &len, "USERPROFILE");
		if (err == 0 && len > 0)
		{
			RemoveEndSlashes(env_p);
			if (HaveStringInList(env_p, List, OutputCount) == 0 && DirExists(env_p) && OutputCount < MaxCount)
			{
				char *TempPath = new char[500];
				strcpy_s(TempPath, 500, env_p);
				List[OutputCount++] = TempPath;
			}
			free(env_p);
		}
	}

	//add temp directory 5
	{
		char *env_p;
		size_t len;
		errno_t err = _dupenv_s(&env_p, &len, "%WINDIR%\temp");
		if (err == 0 && len > 0)
		{
			RemoveEndSlashes(env_p);
			if (HaveStringInList(env_p, List, OutputCount) == 0 && DirExists(env_p) && OutputCount < MaxCount)
			{
				char *TempPath = new char[500];
				strcpy_s(TempPath, 500, env_p);
				List[OutputCount++] = TempPath;
			}
			free(env_p);
		}
	}
	return 0;
}