Example #1
0
void WinHttpStream::initRequest()
{
	TextParser<wchar_t> parser;
	if (!parser(L"%1://%[*-_.a-zA-Z0-9:@]2%%[/](*)*3",url))
		throw FileOpenError(THISLOCATION,ERROR_FILE_NOT_FOUND,url);

	String protocol = parser[1].str();
	String hostident = parser[2].str();
	String::SplitIterator hostidentsplit = hostident.split('@');
	String ident;
	String domain;
	domain = hostidentsplit.getNext();
	while (hostidentsplit.hasItems()) {
		ident = ident + domain + ConstStrW('@');
		domain = hostidentsplit.getNext();
	}
	String path = parser[3].str();
	natural port;
	String username;
	String password;
	bool secure;

	if (parser( L"%1:%u2",domain)) {
		domain = parser[1].str();
		port = parser[2];
		secure = false;
	} else if (protocol == ConstStrW(L"http")) {
		port = INTERNET_DEFAULT_HTTP_PORT;
		secure = false;
	} else if (protocol == ConstStrW(L"https")) {
		port = INTERNET_DEFAULT_HTTPS_PORT;
		secure = true;
	} else
		throw FileOpenError(THISLOCATION,ERROR_NOT_FOUND,url);

	if (!ident.empty()) {
		if (parser(L"%1:%2@",ident))  {
			username = parser[1].str();
			password = parser[2].str();
		} else {
			throw FileMsgException(THISLOCATION,0,url,"Invalid identification field in the url");
		}
	}
	DWORD accessType;
	switch (settings.proxyMode) {
	case pmManual:  accessType = INTERNET_OPEN_TYPE_PROXY;
	case pmDirect:  accessType = INTERNET_OPEN_TYPE_DIRECT;
	case pmAuto:  accessType = INTERNET_OPEN_TYPE_PRECONFIG;
	}

	TextFormatBuff<wchar_t> fmt;

	String proxyName;
	if (accessType == INTERNET_OPEN_TYPE_PROXY) {
		fmt(L"%1:%2") << settings.proxyAddr << settings.proxyPort;
		proxyName = fmt.write();
	}

	if (hInternet) InternetCloseHandle(hInternet);
	hInternet = InternetOpenW(settings.userAgent.cStr(),accessType,proxyName.cStr(),0,0);
	if (hInternet == 0) 
		throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot initialize WinInet");

	if (hConnect) InternetCloseHandle(hConnect);
	hConnect = InternetConnectW(hInternet,domain.cStr(),(INTERNET_PORT)port,
		username.empty()?0:username.cStr(),
		password.empty()?0:password.cStr(),
		INTERNET_SERVICE_HTTP ,0,0);
	if (hConnect == 0) 
		throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
	
	DWORD reqFlags = INTERNET_FLAG_NO_UI |INTERNET_FLAG_HYPERLINK ;
	if (redirDisabled) reqFlags|=INTERNET_FLAG_NO_AUTO_REDIRECT ;
	if (!settings.cookiesEnabled) reqFlags|=INTERNET_FLAG_NO_COOKIES;
	if (secure) reqFlags|=INTERNET_FLAG_SECURE;
	

	hHTTPConn = HttpOpenRequestW(hConnect,String(method).cStr(),path.cStr(),
					0,0,0,reqFlags,0);
	if (hHTTPConn == 0) 
		throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
	AutoArray<wchar_t> hdrall;
	for (HeaderMap::Iterator iter = hdrmap.getFwIter(); iter.hasItems();) {

		const HeaderMap::Entity &e = iter.getNext();
		fmt(L"%1: %2\n") << e.key << e.value;
		hdrall.append(fmt.write());
	}	
	if (!hdrall.empty() &&
		!HttpAddRequestHeadersW(hHTTPConn,hdrall.data(),(DWORD)hdrall.length(),HTTP_ADDREQ_FLAG_REPLACE|HTTP_ADDREQ_FLAG_ADD))
		throw FileMsgException(THISLOCATION,GetLastError(),url,"AddRequest failed");
	
	if (!HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length())) {
		bool stillError = true;
		DWORD dwError = GetLastError();	
		if (dwError == ERROR_INTERNET_INVALID_CA && settings.allowUntrustedCert) {
			DWORD dwFlags;
			DWORD dwBuffLen = sizeof(dwFlags);

			InternetQueryOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
				(LPVOID)&dwFlags, &dwBuffLen);

			dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
				&dwFlags, sizeof (dwFlags) );
			if (HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length()))
				stillError = false;			
		}
		if (stillError)
			throw FileMsgException(THISLOCATION,GetLastError(),url,"Failed to SendRequest");
	}
	postBuffer.clear();
}
Example #2
0
void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_line) const {


	Vector<String> lines = p_code.split("\n");
	List<int> indent_stack;

	for(int i=0;i<lines.size();i++) {

		String l = lines[i];
		int tc=0;
		for(int j=0;j<l.length();j++) {
			if (l[j]==' ' || l[j]=='\t') {

				tc++;
			} else {
				break;
			}
		}


		String st = l.substr(tc,l.length()).strip_edges();
		if (st=="" || st.begins_with("#"))
			continue; //ignore!

		int ilevel=0;
		if (indent_stack.size()) {
			ilevel=indent_stack.back()->get();
		}

		if (tc>ilevel) {
			indent_stack.push_back(tc);
		} else if (tc<ilevel) {
			while(indent_stack.size() && indent_stack.back()->get()>tc) {
				indent_stack.pop_back();
			}

			if (indent_stack.size() && indent_stack.back()->get()!=tc)
				indent_stack.push_back(tc); //this is not right but gets the job done
		}

		if (i>=p_from_line) {

			l="";
			for(int j=0;j<indent_stack.size();j++)
				l+="\t";
			l+=st;


		} else if (i>p_to_line) {
			break;
		}

		//print_line(itos(indent_stack.size())+","+itos(tc)+": "+l);
		lines[i]=l;
	}

	p_code="";
	for(int i=0;i<lines.size();i++) {
		if (i>0)
			p_code+="\n";
		p_code+=lines[i];
	}

}
Example #3
0
  ExitCodes main_(int, const char**) override
  {
    //-------------------------------------------------------------
    // parsing parameters
    //-------------------------------------------------------------
    String in(getStringOption_("in"));
    String out(getStringOption_("out"));
    String feature_out(getStringOption_("feature_out"));
    String pair_in(getStringOption_("pair_in"));
    double mass_tolerance(getDoubleOption_("mass_tolerance"));
    double RT_tolerance(getDoubleOption_("RT_tolerance"));
    double RT_pair_tolerance(getDoubleOption_("RT_pair_tolerance"));

    //-------------------------------------------------------------
    // reading input
    //-------------------------------------------------------------

    FeatureMap all_mrm_features;
    FeatureXMLFile().load(in, all_mrm_features);

    // read pair file
    ifstream is(pair_in.c_str());
    String line;
    Map<double, Map<double, vector<SILAC_pair> > > pairs;
    while (getline(is, line))
    {
      line.trim();
      if (line.empty() || line[0] == '#')
      {
        continue;
      }
      vector<String> split;
      line.split(' ', split);
      if (split.empty())
      {
        line.split('\t', split);
      }
      if (split.size() != 5)
      {
        cerr << "missformated line ('" << line << "') should be (space separated) 'prec-m/z-light prec-m/z-heavy frag-m/z-light frag-m/z-heavy rt'" << endl;
        continue;
      }
      SILAC_pair p;
      double prec_mz_light = split[0].toDouble();
      double prec_mz_heavy = split[1].toDouble();
      p.mz_light = split[2].toDouble();
      p.mz_heavy = split[3].toDouble();
      p.rt = split[4].toDouble();
      pairs[prec_mz_light][prec_mz_heavy].push_back(p);
    }
    is.close();

    //-------------------------------------------------------------
    // calculations
    //-------------------------------------------------------------

    ConsensusMap results_map;
    results_map.getColumnHeaders()[0].label = "light";
    results_map.getColumnHeaders()[0].filename = in;
    results_map.getColumnHeaders()[1].label = "heavy";
    results_map.getColumnHeaders()[1].filename = in;

    // collect the different MRM XIC pairs for each SILAC pair as quantlets
    // then calculate the ratio over the quanlets and calculate some statistics
    FeatureMap all_features;
    for (Map<double, Map<double, vector<SILAC_pair> > >::ConstIterator it1 = pairs.begin(); it1 != pairs.end(); ++it1)
    {
      for (Map<double, vector<SILAC_pair> >::ConstIterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
      {
        vector<SILACQuantitation> quantlets;
        writeDebug_("Analyzing SILAC pair: " + String(it1->first) + " <-> " + String(it2->first), 3);
        Size idx = 0;
        for (vector<SILAC_pair>::const_iterator pit = it2->second.begin(); pit != it2->second.end(); ++pit, ++idx)
        {
          FeatureMap feature_map_light, feature_map_heavy;
          for (FeatureMap::const_iterator it = all_mrm_features.begin(); it != all_mrm_features.end(); ++it)
          {
            if (fabs((double)it->getMetaValue("MZ") - it1->first) < mass_tolerance &&
                fabs(it->getMZ() - pit->mz_light) < mass_tolerance &&
                fabs(it->getRT() - pit->rt) < RT_tolerance)
            {
              feature_map_light.push_back(*it);
            }

            if (fabs((double)it->getMetaValue("MZ") - it2->first) < mass_tolerance &&
                fabs(it->getMZ() - pit->mz_heavy) < mass_tolerance &&
                fabs(it->getRT() - pit->rt) < RT_tolerance)
            {
              feature_map_heavy.push_back(*it);
            }
          }

          // search if feature maps to m/z value of pair
          vector<MatchedFeature> light, heavy;
          for (FeatureMap::const_iterator fit = feature_map_light.begin(); fit != feature_map_light.end(); ++fit)
          {
            all_features.push_back(*fit);
            light.push_back(MatchedFeature(*fit, idx));
          }
          for (FeatureMap::const_iterator fit = feature_map_heavy.begin(); fit != feature_map_heavy.end(); ++fit)
          {
            all_features.push_back(*fit);
            heavy.push_back(MatchedFeature(*fit, idx));
          }

          if (!heavy.empty() && !light.empty())
          {
            writeDebug_("Finding best feature pair out of " + String(light.size()) + " light and " + String(heavy.size()) + " heavy matching features.", 1);
            // now find "good" matches, means the pair with the smallest m/z deviation
            Feature best_light, best_heavy;
            double best_deviation(numeric_limits<double>::max());
            Size best_idx(it2->second.size());
            for (vector<MatchedFeature>::const_iterator fit1 = light.begin(); fit1 != light.end(); ++fit1)
            {
              for (vector<MatchedFeature>::const_iterator fit2 = heavy.begin(); fit2 != heavy.end(); ++fit2)
              {
                if (fit1->idx != fit2->idx || fabs(fit1->f.getRT() - fit2->f.getRT()) > RT_pair_tolerance)
                {
                  continue;
                }
                double deviation(0);
                deviation = fabs(fit1->f.getMZ() - it2->second[fit1->idx].mz_light) +
                            fabs(fit2->f.getMZ() - it2->second[fit2->idx].mz_heavy);
                if (deviation < best_deviation && deviation < mass_tolerance)
                {
                  best_light = fit1->f;
                  best_heavy = fit2->f;
                  best_idx = fit1->idx;
                }
              }
            }

            if (best_idx == it2->second.size())
            {
              continue;
            }

            ConsensusFeature SILAC_feature;
            SILAC_feature.setMZ((best_light.getMZ() + best_heavy.getMZ()) / 2.0);
            SILAC_feature.setRT((best_light.getRT() + best_heavy.getRT()) / 2.0);
            SILAC_feature.insert(0, best_light);
            SILAC_feature.insert(1, best_heavy);
            results_map.push_back(SILAC_feature);

            quantlets.push_back(SILACQuantitation(best_light.getIntensity(), best_heavy.getIntensity(), best_idx));
            writeDebug_("Ratio of XIC: " + String(best_heavy.getIntensity() / best_light.getIntensity()) + " " + String(best_light.getMZ()) + " <-> " + String(best_heavy.getMZ()) + " @" + String(SILAC_feature.getRT()) + " RT-heavy=" + String(best_heavy.getRT()) + ", RT-light=" + String(best_light.getRT()) + ", RT-diff=" + String(best_heavy.getRT() - best_light.getRT()) +
                        " avg. int " + String((best_heavy.getIntensity() + best_light.getIntensity()) / 2.0), 1);

          }
        }

        writeDebug_("Quantitation of pair " + String(it1->first) + " <-> " + String(it2->first) + " (#XIC pairs for quantation=" + String(quantlets.size()) + ")", 1);

        if (quantlets.empty())
        {
          continue;
        }

        // simply add up all intensities and calculate the final ratio
        double light_sum(0), heavy_sum(0);
        vector<double> light_ints, heavy_ints, ratios;
        for (vector<SILACQuantitation>::const_iterator qit1 = quantlets.begin(); qit1 != quantlets.end(); ++qit1)
        {
          light_sum += qit1->light_intensity;
          light_ints.push_back(qit1->light_intensity);
          heavy_sum += qit1->heavy_intensity;
          heavy_ints.push_back(qit1->heavy_intensity);
          ratios.push_back(qit1->heavy_intensity / qit1->light_intensity * (qit1->heavy_intensity + qit1->light_intensity));
        }

        double absdev_ratios = Math::absdev(ratios.begin(), ratios.begin() + (ratios.size()) / (light_sum + heavy_sum));
        cout << "Ratio: " << it1->first << " <-> " << it2->first << " @ " << it2->second.begin()->rt << " s, ratio(h/l) " << heavy_sum / light_sum << " +/- " << absdev_ratios <<  " " << "(#XIC-pairs for quantation: " + String(ratios.size()) + " )" << endl;
      }
    }

    //-------------------------------------------------------------
    // writing output
    //-------------------------------------------------------------

    if (feature_out != "")
    {
      FeatureXMLFile().store(feature_out, all_features);
    }
    writeDebug_("Writing output", 1);
    ConsensusXMLFile().store(out, results_map);

    return EXECUTION_OK;
  }
Example #4
0
RES ResourceFormatLoaderTheme::load(const String &p_path,const String& p_original_path) {

	Error err;
	FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);

	ERR_EXPLAIN("Unable to open theme file: "+p_path);
	ERR_FAIL_COND_V(err,RES());
	String base_path = p_path.get_base_dir();
	Ref<Theme> theme( memnew( Theme ) );
	Map<StringName,Variant> library;

	bool reading_library=false;
	int line=0;

	while(!f->eof_reached()) {

		String l = f->get_line().strip_edges();
		line++;

		int comment = l.find(";");
		if (comment!=-1)
			l=l.substr(0,comment);
		if (l=="")
			continue;

		if (l.begins_with("[")) {
			if (l=="[library]") {
				reading_library=true;
			}  else if (l=="[theme]") {
				reading_library=false;
			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
				ERR_FAIL_V(RES());
			}
			continue;
		}

		int eqpos = l.find("=");
		if (eqpos==-1) {
			memdelete(f);
			ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
			ERR_FAIL_V(RES());
		}


		String right=l.substr(eqpos+1,l.length()).strip_edges();
		if (right=="") {
			memdelete(f);
			ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
			ERR_FAIL_V(RES());
		}

		Variant value;

		if (right.is_valid_integer()) {
			//is number
			value = right.to_int();
		} else if (right.is_valid_html_color()) {
			//is html color
			value = Color::html(right);
		} else if (right.begins_with("@")) { //reference

			String reference = right.substr(1,right.length());
			if (!library.has(reference)) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid reference to '"+reference+"'.");
				ERR_FAIL_V(RES());

			}

			value=library[reference];

		} else if (right.begins_with("default")) { //use default
			//do none
		} else {
			//attempt to parse a constructor
			int popenpos = right.find("(");

			if (popenpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
				ERR_FAIL_V(RES());
			}

			int pclosepos = right.find_last(")");

			if (pclosepos==-1) {
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
				ERR_FAIL_V(RES());

			}

			String type = right.substr(0,popenpos);
			String param = right.substr(popenpos+1,pclosepos-popenpos-1);



			if (type=="icon") {

				String path;

				if (param.is_abs_path())
					path=param;
				else
					path=base_path+"/"+param;

				Ref<Texture> texture = ResourceLoader::load(path);
				if (!texture.is_valid()) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
					ERR_FAIL_V(RES());
				}

				value=texture;

			} else if (type=="sbox") {

				String path;

				if (param.is_abs_path())
					path=param;
				else
					path=base_path+"/"+param;

				Ref<StyleBox> stylebox = ResourceLoader::load(path);
				if (!stylebox.is_valid()) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find stylebox at path: "+path);
					ERR_FAIL_V(RES());
				}

				value=stylebox;

			} else if (type=="sboxt") {

				Vector<String> params = param.split(",");
				if (params.size()!=5 && params.size()!=9) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxt(): '"+right+"'.");
					ERR_FAIL_V(RES());

				}

				String path=params[0];

				if (!param.is_abs_path())
					path=base_path+"/"+path;

				Ref<Texture> tex = ResourceLoader::load(path);
				if (tex.is_null()) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Could not open texture for sboxt at path: '"+params[0]+"'.");
					ERR_FAIL_V(RES());

				}

				Ref<StyleBoxTexture> sbtex( memnew(StyleBoxTexture) );

				sbtex->set_texture(tex);

				for(int i=0;i<4;i++) {
					if (!params[i+1].is_valid_integer()) {

						memdelete(f);
						ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+1) +", expected integer constant, got: '"+params[i+1]+"'.");
						ERR_FAIL_V(RES());
					}

					int margin = params[i+1].to_int();
					sbtex->set_expand_margin_size(Margin(i),margin);
				}

				if (params.size()==9) {

					for(int i=0;i<4;i++) {

						if (!params[i+5].is_valid_integer()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+5) +", expected integer constant, got: '"+params[i+5]+"'.");
							ERR_FAIL_V(RES());
						}

						int margin = params[i+5].to_int();
						sbtex->set_margin_size(Margin(i),margin);
					}
				}

				value = sbtex;
			} else if (type=="sboxf") {

				Vector<String> params = param.split(",");
				if (params.size()<2) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxf(): '"+right+"'.");
					ERR_FAIL_V(RES());

				}

				Ref<StyleBoxFlat> sbflat( memnew(StyleBoxFlat) );

				if (!params[0].is_valid_integer()) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
					ERR_FAIL_V(RES());

				}

				sbflat->set_border_size(params[0].to_int());

				if (!params[0].is_valid_integer()) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
					ERR_FAIL_V(RES());

				}


				int left = MIN( params.size()-1, 3 );

				int ccodes=0;

				for(int i=0;i<left;i++) {

					if (params[i+1].is_valid_html_color())
						ccodes++;
					else
						break;
				}

				Color normal;
				Color bright;
				Color dark;

				if (ccodes<1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Expected at least 1, 2 or 3 html color codes.");
					ERR_FAIL_V(RES());
				} else if (ccodes==1) {

					normal=Color::html(params[1]);
					bright=Color::html(params[1]);
					dark=Color::html(params[1]);
				} else if (ccodes==2) {

					normal=Color::html(params[1]);
					bright=Color::html(params[2]);
					dark=Color::html(params[2]);
				} else {

					normal=Color::html(params[1]);
					bright=Color::html(params[2]);
					dark=Color::html(params[3]);
				}

				sbflat->set_dark_color(dark);
				sbflat->set_light_color(bright);
				sbflat->set_bg_color(normal);

				if (params.size()==ccodes+5) {
					//margins
					for(int i=0;i<4;i++) {

						if (!params[i+ccodes+1].is_valid_integer()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxf #"+itos(i+ccodes+1) +", expected integer constant, got: '"+params[i+ccodes+1]+"'.");
							ERR_FAIL_V(RES());
						}

//						int margin = params[i+ccodes+1].to_int();
						//sbflat->set_margin_size(Margin(i),margin);
					}
				} else if (params.size()!=ccodes+1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid amount of margin parameters for sboxt.");
					ERR_FAIL_V(RES());

				}


				value=sbflat;

			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
				ERR_FAIL_V(RES());

			}

		}


		//parse left and do something with it
		String left= l.substr(0,eqpos);

		if (reading_library) {

			left=left.strip_edges();
			if (!left.is_valid_identifier()) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": <LibraryItem> is not a valid identifier.");
				ERR_FAIL_V(RES());
			}
			if (library.has(left)) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Already in library: '"+left+"'.");
				ERR_FAIL_V(RES());
			}

			library[left]=value;
		} else {

			int pointpos = left.find(".");
			if (pointpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected 'control.item=..' assign syntax.");
				ERR_FAIL_V(RES());
			}

			String control=left.substr(0,pointpos).strip_edges();
			if (!control.is_valid_identifier()) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": <Control> is not a valid identifier.");
				ERR_FAIL_V(RES());
			}
			String item=left.substr(pointpos+1,left.size()).strip_edges();
			if (!item.is_valid_identifier()) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": <Item> is not a valid identifier.");
				ERR_FAIL_V(RES());
			}

			if (value.get_type()==Variant::NIL) {
				//try to use exiting
				if (Theme::get_default()->has_stylebox(item,control))
					value=Theme::get_default()->get_stylebox(item,control);
				else if (Theme::get_default()->has_font(item,control))
					value=Theme::get_default()->get_font(item,control);
				else if (Theme::get_default()->has_icon(item,control))
					value=Theme::get_default()->get_icon(item,control);
				else if (Theme::get_default()->has_color(item,control))
					value=Theme::get_default()->get_color(item,control);
				else if (Theme::get_default()->has_constant(item,control))
					value=Theme::get_default()->get_constant(item,control);
				else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Default not present for: '"+control+"."+item+"'.");
					ERR_FAIL_V(RES());
				}

			}

			if (value.get_type()==Variant::OBJECT) {

				Ref<Resource> res = value;
				if (!res.is_valid()) {

					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource (NULL).");
					ERR_FAIL_V(RES());
				}

				if (res->cast_to<StyleBox>()) {

					theme->set_stylebox(item,control,res);
				} else if (res->cast_to<Font>()) {
					theme->set_font(item,control,res);
				} else if (res->cast_to<Font>()) {
					theme->set_font(item,control,res);
				} else if (res->cast_to<Texture>()) {
					theme->set_icon(item,control,res);
				} else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource type.");
					ERR_FAIL_V(RES());
				}
			} else if (value.get_type()==Variant::COLOR) {

				theme->set_color(item,control,value);

			} else if (value.get_type()==Variant::INT) {

				theme->set_constant(item,control,value);

			} else {

				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't even determine what this setting is! what did you do!?");
				ERR_FAIL_V(RES());
			}

		}


	}

	f->close();
	memdelete(f);

	return theme;
}
static Error _parse_material_library(const String &p_path, Map<String, Ref<SpatialMaterial> > &material_map, List<String> *r_missing_deps) {

	FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
	ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

	Ref<SpatialMaterial> current;
	String current_name;
	String base_path = p_path.get_base_dir();
	while (true) {

		String l = f->get_line().strip_edges();

		if (l.begins_with("newmtl ")) {
			//vertex

			current_name = l.replace("newmtl", "").strip_edges();
			current.instance();
			current->set_name(current_name);
			material_map[current_name] = current;
		} else if (l.begins_with("Ka ")) {
			//uv
			print_line("Warning: Ambient light for material '" + current_name + "' is ignored in PBR");

		} else if (l.begins_with("Kd ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
			Color c = current->get_albedo();
			c.r = v[1].to_float();
			c.g = v[2].to_float();
			c.b = v[3].to_float();
			current->set_albedo(c);
		} else if (l.begins_with("Ks ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
			float r = v[1].to_float();
			float g = v[2].to_float();
			float b = v[3].to_float();
			float metalness = MAX(r, MAX(g, b));
			current->set_metallic(metalness);
		} else if (l.begins_with("Ns ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
			float s = v[1].to_float();
			current->set_metallic((1000.0 - s) / 1000.0);
		} else if (l.begins_with("d ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
			float d = v[1].to_float();
			Color c = current->get_albedo();
			c.a = d;
			current->set_albedo(c);
			if (c.a < 0.99) {
				current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
			}
		} else if (l.begins_with("Tr ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
			float d = v[1].to_float();
			Color c = current->get_albedo();
			c.a = 1.0 - d;
			current->set_albedo(c);
			if (c.a < 0.99) {
				current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
			}

		} else if (l.begins_with("map_Ka ")) {
			//uv
			print_line("Warning: Ambient light texture for material '" + current_name + "' is ignored in PBR");

		} else if (l.begins_with("map_Kd ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_Kd", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}

		} else if (l.begins_with("map_Ks ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_Ks", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}

		} else if (l.begins_with("map_Ns ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_Ns", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}
		} else if (l.begins_with("map_bump ")) {
			//normal
			ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);

			String p = l.replace("map_bump", "").replace("\\", "/").strip_edges();
			String path = base_path.plus_file(p);

			Ref<Texture> texture = ResourceLoader::load(path);

			if (texture.is_valid()) {
				current->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true);
				current->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
			} else if (r_missing_deps) {
				r_missing_deps->push_back(path);
			}
		} else if (f->eof_reached()) {
			break;
		}
	}

	return OK;
}
Example #6
0
		String File::absolutePath(const String &filePath)
		{
			String path = normalizePath(filePath);
			if(path.isEmpty())
				return String();
				
			String base;
			unsigned int start;
#if WITCHENGINE_PLATFORM == WITCHENGINE_PLATFORM_WIN32 || WITCHENGINE_PLATFORM == WITCHENGINE_PLATFORM_WIN64
			if(path.match("?:*"))
				start = 1;
			else if(path.match("\\\\*"))
			{
				base = "\\\\";
				start = 2;
			}
			else if(path.startsWith('\\'))
			{
				String drive = Directory::current().substrTo('\\');
				String end = path.substr(1, -1);
				if(end.isEmpty())
					path = drive;
				else
					path = drive + '\\' + end;
					
				start = 1;
			}
			else
			{
				// Throw an exception.
				return path;
			}
#else
			base = '';
			start = 0;
#endif

			static String upDir = WITCH_DIRECTORY_SEPARATOR + String('.');
			
			if(path.find(upDir) == String::npos)
				return path;
				
			std::vector<String> sep;
			if(path.split(sep, WITCH_DIRECTORY_SEPARATOR) <= 1)
				return path;
				
			unsigned int pathLen = base.size();
			for(unsigned int i = 0; i < sep.size(); ++i)
			{
				if(sep[i] == '.')
					sep.erase(sep.begin() + i--);
				else if(sep[i] == "..")
				{
					if(i > start)
						sep.erase(sep.begin() - i--);
						
					sep.erase(sep.begin() + i--);
				}
				else
					pathLen += sep[i].size();
			}
			
			pathLen += sep.size() - 1;
			
			String stream;
			stream.reserve(pathLen);
			stream.append(base);
			for(unsigned int i = 0; i < sep.size(); ++i)
			{
				stream.append(sep[i]);
				if(i != sep.size() - 1)
					stream.append(WITCH_DIRECTORY_SEPARATOR);
			}
			
			return stream;
		}
Example #7
0
P<BundleData> DirBundleLoader::loadBundle(String location)
{
	P<BundleData> bundleData = new BundleData();

	bundleData->setLocation(location);

	String path = location;
	path.append(L"\\META-INF\\MANIFEST.MF");
	P<File> file = new File(path);

	P<Manifest> mf = new Manifest(file);
	P<Map<String,String>> entries = mf->getEntries();

	String symbolicName = entries->get(Constants::BUNDLE_SYMBOLICNAME);
	if (symbolicName == (String)null || symbolicName.equals(L"") ) 
	{
        throw BundleException(String(L"Bundle symbolic name not found: ") + file->getAbsolutePath());
    }

	//if (framework->getBundle(symbolicName) != null) 
	//{
 //       throw BundleException(String(L"Bundle(SymbolicName: ") + symbolicName + String(L") already exists: ") + file->getAbsolutePath());
 //   }

	bundleData->setSymbolicName(symbolicName);

	//get Bundle-Name
	String name = entries->get(Constants::BUNDLE_NAME);
    if (name == (String)null || name.equals(L"")) 
	{
		name = File(location).getName();
    }

	bundleData->setName(name);

    // Validate the bundle activator.

	String activator = entries->get(Constants::BUNDLE_ACTIVATOR);
    if (activator == (String)null || symbolicName.equals(L"") )
	{
        throw BundleException(String(L"Bundle activator definition not found: ") + file->getAbsolutePath());
    }

	bundleData->setActivator(activator);

	String nativeLib = entries->get(Constants::BUNDLE_NATIVE_LIB);
	if (nativeLib == (String)null || nativeLib.equals(L"") )
	{
		nativeLib = name + String(L".dll");
	}

	nativeLib = String(location) + String(L"\\") + nativeLib;

	bundleData->setNativeLib(nativeLib);

	//P<Library> lib= new DllLibrary();
	//lib->load(this->nativeLib);

	//if (!lib->containsClass(activator)) 
	//{
 //       throw BundleException(String(L"Bundle activator class(\"") + activator + String(L"\") not found: ") + file->getAbsolutePath());
 //   }

	//lib->free();

	String description = entries->get(Constants::BUNDLE_DESCRIPTION);
    if (description == (String)null || description.equals(L"")) 
	{
        description = L"";
    }

	bundleData->setDescription(description);


	// Parse classpaths
    String classpath = entries->get(Constants::BUNDLE_CLASSPATH);

	P<Array<String>> classPaths = null;

    if (classpath != null) 
	{
        Array<String> theClassPaths =classpath.split(L",");

		int size = theClassPaths.size();
		classPaths = new Array<String>(size);

        for (int i = 0; i < size; i++) 
		{
			String theClassPath =theClassPaths.get(i);

			// Check the classpath entry
			bool entryExists = false;
			
			String theRealPath = generateURL(location, theClassPath);
			File theFile(theRealPath);

			entryExists = theFile.exists();

			if (entryExists) 
			{
				classPaths->set(i, theFile.getCanonicalPath());
			}
			else 
			{
				throw BundleException(String(L"Classpath(\"") + theClassPath + String(L"\") not found: ") + file->getAbsolutePath());
			}
		}
    }
	else 
	{
		classPaths = new Array<String>();
	}

	bundleData->setClassPaths(classPaths);

	// Parse export packages
	String exportPackages = entries->get(Constants::EXPORT_PACKAGE);
	Array<String> exportedPackages;

    if (exportPackages != null) 
	{
         
        exportedPackages =exportPackages.split(L",");
    }
	else 
	{
		exportedPackages = Array<String>();
	}

	bundleData->setExportedPackages(new Array<String>(exportedPackages));

	// Parse import packages, nee
	String importpackages = entries->get(Constants::IMPORT_PACKAGE);
	Array<String> importedPackages;

    if (importpackages != null)
	{
		importedPackages =importpackages.split(L",");
    }
	else 
	{
        importedPackages = Array<String>();
    }

	bundleData->setImportedPackages(new Array<String>(importedPackages));

	// Parse reuqired extensions
	String requiredbundles = entries->get(Constants::REQUIRE_BUNDLE);
	Array<String> requiredBundles;

    if (requiredbundles != null) 
	{
		requiredBundles =requiredbundles.split(L",");
    }
	else 
	{
        requiredBundles =  Array<String>();
    }

	bundleData->setRequiredBundles(new Array<String>(requiredBundles));

	return bundleData;
}
Entity *SceneEntityInstance::loadObjectEntryIntoEntity(ObjectEntry *entry, Entity *targetEntity, int entityFileVersion) {

	Entity *entity = NULL;

	ObjectEntry *entityType = (*entry)["type"];
	if(entityType) {
        if(entityType->stringVal == "SceneEntityInstance") {
            ObjectEntry *instanceEntry = (*entry)["SceneEntityInstance"];
            String filePath = (*instanceEntry)["filePath"]->stringVal;
            SceneEntityInstance *instance = new SceneEntityInstance(parentScene, filePath);
            entity = instance;
         } else if(entityType->stringVal == "SceneSprite") {
			ObjectEntry *spriteEntry = (*entry)["SceneSprite"];
			String filePath = (*spriteEntry)["filePath"]->stringVal;
			
			SceneSprite *sprite = new SceneSprite(filePath);
			
			String animName = (*spriteEntry)["anim"]->stringVal;
			sprite->playAnimation(animName, -1, false);
			entity = sprite;
            applySceneMesh((*entry)["SceneMesh"], sprite);
        } else 	if(entityType->stringVal == "SceneLabel") {
			ObjectEntry *labelEntry = (*entry)["SceneLabel"];
			
			String text = (*labelEntry)["text"]->stringVal;
			String font = (*labelEntry)["font"]->stringVal;
			int size = (*labelEntry)["size"]->intVal;
            Number actualHeight = (*labelEntry)["actualHeight"]->intVal;
			int aaMode = (*labelEntry)["aaMode"]->intVal;
            
			SceneLabel *label = new SceneLabel(text, size, font, aaMode, actualHeight);
            label->setAnchorPoint(0.0, 0.0, 0.0);
            label->snapToPixels = false;
            label->positionAtBaseline = false;
            applySceneMesh((*entry)["SceneMesh"], label);
            if(label->getLocalShaderOptions()) {
                label->getLocalShaderOptions()->clearTexture("diffuse");
                label->getLocalShaderOptions()->addTexture("diffuse", label->getTexture());
            }
            
			entity = label;
        } else if(entityType->stringVal == "SceneParticleEmitter") {
            
			ObjectEntry *emitterEntry = (*entry)["SceneParticleEmitter"];
            SceneParticleEmitter *emitter = new SceneParticleEmitter(1, 1, 1);

            emitter->setParticleType((*emitterEntry)["type"]->intVal);
            emitter->setParticleSpeed((*emitterEntry)["speed"]->NumberVal);
            emitter->setParticleCount((*emitterEntry)["count"]->intVal);
            emitter->setParticleLifetime((*emitterEntry)["lifetime"]->NumberVal);
            emitter->setParticleSize((*emitterEntry)["size"]->NumberVal);
            emitter->setParticlesInWorldSpace((*emitterEntry)["world"]->boolVal);
            emitter->setLoopParticles((*emitterEntry)["loop"]->boolVal);
            
            emitter->setParticleRotationSpeed(Vector3((*emitterEntry)["rX"]->NumberVal, (*emitterEntry)["rY"]->NumberVal, (*emitterEntry)["rZ"]->NumberVal));
            emitter->setGravity(Vector3((*emitterEntry)["gX"]->NumberVal, (*emitterEntry)["gY"]->NumberVal, (*emitterEntry)["gZ"]->NumberVal));
            emitter->setParticleDirection(Vector3((*emitterEntry)["dirX"]->NumberVal, (*emitterEntry)["dirY"]->NumberVal, (*emitterEntry)["dirZ"]->NumberVal));
            emitter->setEmitterSize(Vector3((*emitterEntry)["eX"]->NumberVal, (*emitterEntry)["eY"]->NumberVal, (*emitterEntry)["eZ"]->NumberVal));
            emitter->setDirectionDeviation(Vector3((*emitterEntry)["devX"]->NumberVal, (*emitterEntry)["devY"]->NumberVal, (*emitterEntry)["devZ"]->NumberVal));
            
            emitter->setPerlinEnabled((*emitterEntry)["perlin"]->boolVal);
            if(emitter->getPerlinEnabled()) {
                emitter->setPerlinValue(Vector3((*emitterEntry)["pX"]->NumberVal, (*emitterEntry)["pY"]->NumberVal, (*emitterEntry)["pZ"]->NumberVal));
            }
            
            emitter->useColorCurves = (*emitterEntry)["useColorCurves"]->boolVal;
            emitter->useScaleCurve = (*emitterEntry)["useScaleCurve"]->boolVal;
            
            parseObjectIntoCurve((*emitterEntry)["colorCurveR"], &emitter->colorCurveR);
            parseObjectIntoCurve((*emitterEntry)["colorCurveG"], &emitter->colorCurveG);
            parseObjectIntoCurve((*emitterEntry)["colorCurveB"], &emitter->colorCurveB);
            parseObjectIntoCurve((*emitterEntry)["colorCurveA"], &emitter->colorCurveA);
            parseObjectIntoCurve((*emitterEntry)["scaleCurve"], &emitter->scaleCurve);
            
            applySceneMesh((*entry)["SceneMesh"], emitter);
			entity = emitter;
            
		} else if(entityType->stringVal == "SceneLight") {
            
			ObjectEntry *lightEntry = (*entry)["SceneLight"];
            if(lightEntry) {
                int lightType = (*lightEntry)["type"]->intVal;
                SceneLight *newLight  = new SceneLight(lightType, parentScene, 0);
                
                newLight->setIntensity((*lightEntry)["intensity"]->NumberVal);
                
                ObjectEntry *importanceEntry = (*lightEntry)["importance"];
                if(importanceEntry) {
                    newLight->setLightImportance(importanceEntry->intVal);
                }
                
                newLight->lightColor.setColor((*lightEntry)["cR"]->NumberVal, (*lightEntry)["cG"]->NumberVal, (*lightEntry)["cB"]->NumberVal, (*lightEntry)["cA"]->NumberVal);
                newLight->specularLightColor.setColor((*lightEntry)["scR"]->NumberVal, (*lightEntry)["scG"]->NumberVal, (*lightEntry)["scB"]->NumberVal, (*lightEntry)["scA"]->NumberVal);

                newLight->setAttenuation((*lightEntry)["cAtt"]->NumberVal, (*lightEntry)["lAtt"]->NumberVal, (*lightEntry)["qAtt"]->NumberVal);
                
                if(newLight->getType() == SceneLight::SPOT_LIGHT) {
                    newLight->setSpotlightProperties((*lightEntry)["spotCutoff"]->NumberVal, (*lightEntry)["spotExponent"]->NumberVal);
                    
                    if((*lightEntry)["shadows"]->boolVal) {
                        newLight->enableShadows(true, (*lightEntry)["shadowmapRes"]->intVal);
                        newLight->setShadowMapFOV((*lightEntry)["shadowmapFOV"]->NumberVal);
                    }
                }
                
                parentScene->addLight(newLight);
                entity = newLight;
            }
 
        } else if(entityType->stringVal == "ScenePrimitive") {
			ObjectEntry *scenePrimitiveEntry = (*entry)["ScenePrimitive"];
			int pType = (*scenePrimitiveEntry)["type"]->intVal;
			Number p1 = (*scenePrimitiveEntry)["p1"]->NumberVal;
			Number p2 = (*scenePrimitiveEntry)["p2"]->NumberVal;
			Number p3 = (*scenePrimitiveEntry)["p3"]->NumberVal;
			Number p4 = (*scenePrimitiveEntry)["p4"]->NumberVal;
			Number p5 = (*scenePrimitiveEntry)["p5"]->NumberVal;
            
			ScenePrimitive *primitive = new ScenePrimitive(pType, p1, p2, p3, p4, p5);
			entity = primitive;
            applySceneMesh((*entry)["SceneMesh"], primitive);
		} else if(entityType->stringVal == "SceneMesh") {
			ObjectEntry *meshEntry = (*entry)["SceneMesh"];
            if(meshEntry) {
                ObjectEntry *fileName = (*meshEntry)["file"];
                if(fileName) {
                    SceneMesh *newMesh = new SceneMesh(fileName->stringVal);
                    applySceneMesh(meshEntry, newMesh);
                    entity = newMesh;
                }
            }
        } else if(entityType->stringVal == "SceneSound") {
			ObjectEntry *soundEntry = (*entry)["SceneSound"];
			
			String filePath = (*soundEntry)["filePath"]->stringVal;
			Number refDistance = (*soundEntry)["refDistance"]->NumberVal;
			Number maxDistance = (*soundEntry)["maxDistance"]->NumberVal;
			Number volume = (*soundEntry)["volume"]->NumberVal;
			Number pitch = (*soundEntry)["pitch"]->NumberVal;
            
			SceneSound *sound = new SceneSound(filePath, refDistance, maxDistance);
			sound->getSound()->setVolume(volume);
			sound->getSound()->setPitch(pitch);
			
			entity = sound;
        } else if(entityType->stringVal == "Camera") {
			ObjectEntry *cameraEntry = (*entry)["Camera"];
            
			Camera *camera = new Camera(parentScene);
            
            camera->setExposureLevel((*cameraEntry)["exposure"]->NumberVal);
            camera->setClippingPlanes((*cameraEntry)["nearClip"]->NumberVal, (*cameraEntry)["farClip"]->NumberVal);
            camera->setOrthoMode((*cameraEntry)["ortho"]->boolVal);
            
            if(camera->getOrthoMode()) {
				camera->setOrthoSizeMode((*cameraEntry)["sizeMode"]->intVal);
                camera->setOrthoSize((*cameraEntry)["orthoWidth"]->NumberVal, (*cameraEntry)["orthoHeight"]->NumberVal);
            } else {
                camera->setFOV((*cameraEntry)["fov"]->NumberVal);
            }
            
			entity = camera;
		}

        
	}

	if(!entity) {
		if(targetEntity) {
			entity = targetEntity;
		} else {
			entity = new Entity();
		}
	}
	
	entity->ownsChildren = true;

    Vector3 bBox;
	entry->readNumber("bbX", &bBox.x);
	entry->readNumber("bbY", &bBox.y);
	entry->readNumber("bbZ", &bBox.z);
    entity->setLocalBoundingBox(bBox);
    
	entity->color.r = (*entry)["cR"]->NumberVal;
	entity->color.g = (*entry)["cG"]->NumberVal;
	entity->color.b = (*entry)["cB"]->NumberVal;
	entity->color.a = (*entry)["cA"]->NumberVal;


	if(!targetEntity) {	
		entity->blendingMode = (*entry)["blendMode"]->intVal;

        entity->setScale((*entry)["sX"]->NumberVal, (*entry)["sY"]->NumberVal, (*entry)["sZ"]->NumberVal);
        entity->setPosition((*entry)["pX"]->NumberVal, (*entry)["pY"]->NumberVal, (*entry)["pZ"]->NumberVal);
        
        if(entityFileVersion > 1) {
            entity->setRotationQuat((*entry)["rW"]->NumberVal, (*entry)["rX"]->NumberVal, (*entry)["rY"]->NumberVal, (*entry)["rZ"]->NumberVal);
        } else {
            entity->setRotationEuler(Vector3((*entry)["rX"]->NumberVal, (*entry)["rY"]->NumberVal, (*entry)["rZ"]->NumberVal));
        }
	}
	
	if((*entry)["id"]->stringVal != "") {
		entity->id = (*entry)["id"]->stringVal;
	}
    
    if((*entry)["layerID"]) {
        entity->layerID = (unsigned int)((*entry)["layerID"]->intVal);
    }
	
	String tagString = (*entry)["tags"]->stringVal; 
	
	if(tagString != "") {
		std::vector<String> tags = tagString.split(",");
		for(int i=0; i < tags.size(); i++) {
			entity->addTag(tags[i]);
		}
	}
	
	ObjectEntry *props = (*entry)["props"];
	if(props) {
		for(int i=0; i < props->length; i++) {		
			ObjectEntry *prop = ((*props))[i];		
			if(prop) {
				entity->setEntityProp((*prop)["name"]->stringVal, (*prop)["value"]->stringVal);
			}
		}
	}
														
	ObjectEntry *children = (*entry)["children"];
	
	if(children) {
		for(int i=0; i < children->length; i++) {
			ObjectEntry *childEntry = ((*children))[i];
			ScreenEntity *childEntity = loadObjectEntryIntoEntity(childEntry, NULL, entityFileVersion);
			entity->addChild(childEntity);				
		}
	}

	return entity;
}
Example #9
0
int
main(int argc, char** argv)
{
   String a;
   a = "Testing...";
   cout << a << endl;
   cout << "length: " << a.length() << endl;
   cout << "capacity: " << a.capacity() << endl;

   a = a + "one two three";
   cout << a << endl;
   cout << "length: " << a.length() << endl;
   cout << "capacity: " << a.capacity() << endl;

   a = "stuff on the front:" + a;
   cout << a << endl;
   cout << "length: " << a.length() << endl;
   cout << "capacity: " << a.capacity() << endl;

   long intval = 0;
   if (String("32").parseInt(intval))
      cout << "Converting '32' to int: " << intval << endl;
   else
      cout << "Error converting string to int.\n";

   double doubleval = 0.0;
   String("3.141592654").parseDouble(doubleval);
   cout << "Converting 3.141592654 to double: " << doubleval << endl;

   long hexval = 0;
   if (String("0x34ab").parseHex(hexval))
      cout << "Converting 0x34ab to " << hexval << " (Should be 13483)" << endl;
   else
      cout << "Hex conversion failed.\n";
   
   

   String tflag("true");
   String fflag("false");

   bool boolval;

   tflag.parseBool(boolval);
   if (boolval)
      cout << "This should have been true (and was)" << endl;
   else
      cout << "tflag was false and should have been true." << endl;

   fflag.parseBool(boolval);
   if (boolval)
      cout << "fflag should have been false and wasn't." << endl;
   else
      cout << "fflag was false and should have been." << endl;
   
   char c;
   a.charAt(3, c);
   cout << "\nCharacter at position 3: '" << c << "' \n";

   String b("cat");
   String d = "cat";

   if (b == d)
      cout << "Yup, equal.\n";
   else
      cout << "Nope, not equal.\n";

   if (b == "fark")
      cout << b << " is less than fark\n";

   cout << a.toLower() << endl;
   cout << a.toUpper() << endl;

   cout << "Substring..." << endl;
   String substr_test = "this is a weird string. Much odd.";
   cout << substr_test.substring(4, 4) << endl;
   
   cout << "Regular Expressions\n";
   String astring = "This is a test.";
   if (astring.matches("is a"))
      cout << "   Matched!\n";
   else
      cout << "   Didn't match.\n";

   String csvstuff = "3.1415     2.71828   42   testing";
   ArrayList<String> fields = csvstuff.split(" +");
}
Example #10
0
  void
  PepNovoOutfile::getSearchEngineAndVersion(
    const String & pepnovo_output_without_parameters_filename,
    ProteinIdentification & protein_identification)
  {
    ifstream pepnovo_output_without_parameters(pepnovo_output_without_parameters_filename.c_str());
    if (!pepnovo_output_without_parameters)
    {
      throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, pepnovo_output_without_parameters_filename);
    }

    ProteinIdentification::SearchParameters search_param;
    // searching for something like this: PepNovo v1.03
    String line;
    vector<String> substrings;
    while (getline(pepnovo_output_without_parameters, line))
    {
      if (!line.empty() && (line[line.length() - 1] < 33))
        line.resize(line.length() - 1);
      line.trim();
      if (line.empty())
        continue;
      if (line.hasPrefix("PepNovo"))
      {
        line.split(',', substrings);
        if (substrings.size() == 2) //previous version of PepNovo
        {
          protein_identification.setSearchEngine(substrings[0].trim());
          protein_identification.setSearchEngineVersion(substrings[1].trim()); //else something is strange and we use defaults later
        }
        else
        {
          line.split(' ', substrings);
          if (substrings.size() == 3)
          {
            protein_identification.setSearchEngine(substrings[0].trim());
            protein_identification.setSearchEngineVersion(substrings[2].trim()); //else something is strange and we use defaults later
          }
        }
      }
      if (line.hasPrefix("PM"))
      {
        line.split(' ', substrings);
        search_param.precursor_mass_tolerance = substrings.back().toFloat();
      }
      if (line.hasPrefix("Fragment"))
      {
        line.split(' ', substrings);
        search_param.fragment_mass_tolerance = substrings.back().toFloat();
      }
      if (line.hasPrefix("PTM"))
      {
        line.split(':', substrings);
        substrings.erase(substrings.begin());
        for (vector<String>::iterator ptm_it = substrings.begin(); ptm_it != substrings.end(); ++ptm_it)
        {
          ptm_it->trim();
        }
        if (!substrings.empty() && substrings[0] != "None")
        {
          search_param.variable_modifications = substrings;
        }
      }
      if (line.hasPrefix(">>"))
      {
        break;
      }
    }
    protein_identification.setSearchParameters(search_param);
  }
/** --------------------------------------------------------------------
 * Add new cookie to existing set.
**/
void setCookies(Document* doc/*document*/, const KURL& url, const String& value)
{
    int i, j, len;
    const int n = 7;
    String result, key1, key2, f[n], inCookie, outCookie;
    Vector<String> field;

    // printf("%s: input: %08X %s\n%s\n\n", __func__, (unsigned)doc, url.string().utf8().data(), value.utf8().data());

    if (value.length() == 0)
        return;

    String host = url.host();

    if (doc)
    {
        Vector<String> param;
        f[0] = "";
        f[1] = "TRUE";
        f[2] = "";
        f[3] = "FALSE";
        f[4] = "0";
        f[5] = "";
        f[6] = "";
        bool ok = false;

        value.split(';', param);

        len = param.size();

        for (i = 0; i < len; i++)
        {
            param[i] = param[i].stripWhiteSpace();

            if (param[i] == "secure")
            {
                f[3] = "TRUE";
                continue;
            }

            param[i].split('=', field);
            if (field.size() < 2)
                return;

            field[0] = field[0].stripWhiteSpace();
            field[1] = field[1].stripWhiteSpace();

            if (field[0] == "domain")
            {
                // if (!host.endsWith(field[1], false))
                //     return;

                f[0] = field[1];
            }
            else if (field[0] == "path")
            {
                f[2] = field[1];
            }
            else if (field[0] == "expires")
            {
                // --- Only GMT zone is valid ---
                time_t date = curl_getdate(field[1].utf8().data(), NULL);
                if (date < 0)
                    date = 0;
                f[4] = String::number(date);
            }
            else
            {
                f[5] = field[0];
                f[6] = field[1];
                ok = true;
            }
        }

        if (!ok)
            return;

        // --- Defaults ---
        if (f[0].isEmpty())
            f[0] = host;

        if (f[2].isEmpty())
            f[2] = url.path();

        result = f[0];
        for (i = 1; i < n; i++)
            result += "\t" + f[i];

        key1 = f[0] + f[2] + f[5];
    }
    else
    {
        value.split('\t', true, field);

        if (field.size() != n)
            return;

        if (!host.endsWith(field[0], false))
            return;

        key1 =  field[0] + field[2] + field[5];

        result = value;
    }

    // --- Remove existing entry ---
    inCookie = cookieJar.get(host);
    if (!inCookie.isEmpty())
    {
        inCookie.split('\t', true, field);
        len = field.size();

        for (j = 0; j < len; j += n)
        {
            key2 = field[j] + field[j + 2] + field[j + 5];

            if (key1 == key2)
                continue;

            for (i = 0; i < n; i++)
                outCookie += "\t" + field[j + i];
        }

        outCookie = result + outCookie;
    }
    else
        outCookie = result;

    // printf("%s: result: host=%s, cookie=%s\n\n", __func__, host.utf8().data(), outCookie.utf8().data());
    cookieJar.set(host, outCookie);

    if (doc)
    {
        int cookieJarStatus = getCookieJarStatus();
        if (cookieJarStatus <= COOKIE_JAR_OK)
            setCookieJarStatus(COOKIE_JAR_DIRTY);
    }
}
Example #12
0
int main(int argc, char **argv) {
		
	PHYSFS_init(argv[0]);

#if defined(__APPLE__) && defined(__MACH__)
    uint32_t bufsize = 2048;
	char path[bufsize];
	_NSGetExecutablePath(path, &bufsize);

	String basePath = path;
	vector<String> cpts = basePath.split("/");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("/");
	}
#elif defined (_WINDOWS)
	char path[2049];
	TCHAR tpath[2049];
	GetModuleFileName(NULL, (LPWSTR)tpath, 2048);
	wtoc(path, tpath, 2048);
	
	String basePath = path;
	vector<String> cpts = basePath.split("\\");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("\\");
	}
#else
	String basePath = PHYSFS_getBaseDir();
	vector<String> cpts = basePath.split("/");
	String installPath = "";
	for(int i=0; i < cpts.size() - 2; i++) {
		installPath = installPath + cpts[i];
		installPath += String("/");
	}
#endif

	printf("Polycode build tool v0.8.2\n");

	for(int i=0; i < argc; i++) {
		String argString = String(argv[i]);
		vector<String> bits = argString.split("=");
		if(bits.size() == 2) {
			BuildArg arg;
			arg.name = bits[0];
			arg.value = bits[1];
		//	printf("arg: %s=%s\n", arg.name.c_str(), arg.value.c_str());
			args.push_back(arg);
		}
		
	}
	
	if(getArg("--config") == "") {
		printf("\n\nInput config XML missing. Use --config=path to specify.\n\n");
		return 1;
	}

	
	if(getArg("--out") == "") {
		printf("\n\nOutput file not specified. Use --out=outfile.polyapp to specify.\n\n");
		return 1;		
	}

	char dirPath[4099];
#if defined(__APPLE__) && defined(__MACH__)
	getcwd(dirPath, sizeof(dirPath));
#elif defined (_WINDOWS)
	TCHAR tdirpath[4099];
	GetCurrentDirectory(4098, (LPWSTR)tdirpath);
	wtoc(dirPath, tdirpath, 4098);
#else
	getcwd(dirPath, sizeof(dirPath));
#endif

	String currentPath = String(dirPath);

	String configPath = getArg("--config");

	String finalPath = configPath;
	if(configPath[0] != '/' && configPath[1] !=':') {

#ifdef _WINDOWS
		finalPath = currentPath+"\\"+configPath;
#else
		finalPath = currentPath+"/"+configPath;
#endif
	}

	printf("Reading config file from %s\n", finalPath.c_str());

	Object configFile;
	if(!configFile.loadFromXML(finalPath)) {
		printf("Specified config file doesn't exist!\n");
		return 1;
	}
	printf("OK!\n");
	// start required params

	String entryPoint;
	int defaultWidth;
	int defaultHeight;
	int frameRate = 60;
	int antiAliasingLevel = 0;
	int anisotropyLevel = 0;
	bool vSync = false;
	bool fullScreen = false;
	float backgroundColorR = 0.2;
	float backgroundColorG = 0.2;
	float backgroundColorB = 0.2;
	String textureFiltering = "linear";

	if(configFile.root["entryPoint"]) {
		printf("Entry point: %s\n", configFile.root["entryPoint"]->stringVal.c_str());
		entryPoint = configFile.root["entryPoint"]->stringVal;
	} else {
		printf("Required parameter: \"entryPoint\" is missing from config file!\n");
		return 1;		
	}

	if(configFile.root["defaultWidth"]) {
		printf("Width: %d\n", configFile.root["defaultWidth"]->intVal);
		defaultWidth = configFile.root["defaultWidth"]->intVal;
	} else {
		printf("Required parameter: \"defaultWidth\" is missing from config file!\n");
		return 1;		
	}

	if(configFile.root["defaultHeight"]) {
		printf("Height: %d\n", configFile.root["defaultHeight"]->intVal);
		defaultHeight = configFile.root["defaultHeight"]->intVal;
	} else {
		printf("Required parameter: \"defaultHeight\" is missing from config file!\n");
		return 1;		
	}

	// start optional params

	if(configFile.root["frameRate"]) {
		printf("Frame rate: %d\n", configFile.root["frameRate"]->intVal);
		frameRate = configFile.root["frameRate"]->intVal;
	}

	if(configFile.root["textureFiltering"]) {
		printf("Filtering mode: %s\n", configFile.root["textureFiltering"]->stringVal.c_str());
		textureFiltering = configFile.root["textureFiltering"]->stringVal;
	}

	if(configFile.root["antiAliasingLevel"]) {
		printf("Anti-aliasing level: %d\n", configFile.root["antiAliasingLevel"]->intVal);
		antiAliasingLevel = configFile.root["antiAliasingLevel"]->intVal;
	}

	if(configFile.root["anisotropyLevel"]) {
		printf("Anisotropy level: %d\n", configFile.root["anisotropyLevel"]->intVal);
		anisotropyLevel = configFile.root["anisotropyLevel"]->intVal;
	}
	
	if(configFile.root["vSync"]) {
		vSync = configFile.root["vSync"]->boolVal;
		if(vSync) {
			printf("V-Sync: true\n");
		} else {
			printf("V-Sync: false\n");
		}
	}	

	if(configFile.root["fullScreen"]) {
		fullScreen = configFile.root["fullScreen"]->boolVal;
		if(fullScreen) {
			printf("Full-screen: true\n");
		} else {
			printf("Full-screen: false\n");
		}
	}

	if(configFile.root["backgroundColor"]) {
		ObjectEntry *color = configFile.root["backgroundColor"];
		if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
			backgroundColorR = (*color)["red"]->NumberVal;
			backgroundColorG = (*color)["green"]->NumberVal;
			backgroundColorB = (*color)["blue"]->NumberVal;
			printf("Background color: %f %f %f\n", backgroundColorR, backgroundColorG, backgroundColorB);

		} else {
			printf("backgroundColor node specified, but missing all three color attributes (red,green,blue). Ignoring.\n");
		}
	}

	zipFile z = zipOpen(getArg("--out").c_str(), 0);
	

	Object runInfo;
	runInfo.root.name = "PolycodeApp";
	runInfo.root.addChild("entryPoint", entryPoint);
	runInfo.root.addChild("defaultHeight", defaultHeight);
	runInfo.root.addChild("defaultWidth", defaultWidth);
	runInfo.root.addChild("frameRate", frameRate);
	runInfo.root.addChild("antiAliasingLevel", antiAliasingLevel);
	runInfo.root.addChild("anisotropyLevel", anisotropyLevel);
	runInfo.root.addChild("vSync", vSync);	
	runInfo.root.addChild("fullScreen", fullScreen);
	runInfo.root.addChild("textureFiltering", String(textureFiltering));
		
	ObjectEntry *color = runInfo.root.addChild("backgroundColor");
	color->addChild("red", backgroundColorR);
	color->addChild("green", backgroundColorG);
	color->addChild("blue", backgroundColorB);

	if(configFile.root["fonts"]) {
		runInfo.root.addChild(configFile.root["fonts"]);
	}
	
	if(configFile.root["modules"]) {
#ifdef _WINDOWS
		String modulesPath = installPath + "Modules\\";
#else
		String modulesPath = installPath + "Modules/";
#endif

		ObjectEntry *modules = configFile.root["modules"];
		if(modules) {		
			for(int i=0; i < modules->length; i++) {
				printf("Adding module: %s\n", (*modules)[i]->stringVal.c_str());
				String modulePath = modulesPath + (*modules)[i]->stringVal;
#ifdef _WINDOWS
				String moduleAPIPath = modulePath + "\\API";
				String moduleLibPath = modulePath + "\\Lib";
				moduleAPIPath = moduleAPIPath.replace("\\", "/");
				moduleAPIPath = moduleAPIPath.substr(2, moduleAPIPath.length() - 2);	
				moduleLibPath = moduleLibPath.replace("\\", "/");
				moduleLibPath = moduleLibPath.substr(2, moduleLibPath.length() - 2);	

#else
				String moduleAPIPath = modulePath + "/API";
				String moduleLibPath = modulePath + "/Lib";
#endif
				printf("Path:%s\n", moduleAPIPath.c_str());		


				addFolderToZip(z, moduleAPIPath, "", false);
				addFolderToZip(z, moduleLibPath, "__lib", false);

				//String module = configFile.root["entryPoint"]->stringVal;
			}
			runInfo.root.addChild(configFile.root["modules"]);
		}
	}

	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				ObjectEntry *entryType = (*(*packed)[i])["type"];
				ObjectEntry *entrySource = (*(*packed)[i])["source"];
				if(entryPath && entryType) {
					if (!entrySource) entrySource = entryPath;
					if(entryType->stringVal == "folder") {
						addFolderToZip(z, entrySource->stringVal, entryPath->stringVal, false);
					} else {
						addFileToZip(z, entrySource->stringVal, entryPath->stringVal, false);
					}
				}
			}
			runInfo.root.addChild(configFile.root["packedItems"]);
		}
	}


	runInfo.saveToXML("runinfo_tmp_zzzz.polyrun");
	addFileToZip(z, "runinfo_tmp_zzzz.polyrun", "runinfo.polyrun", true);

	//addFolderToZip(z, getArg("--project"), "");
	
	zipClose(z, "");	

#ifdef _WINDOWS
	char *buffer = _getcwd(NULL, 0);
	String workingDir = String(buffer);
	free(buffer);
	OSBasics::removeItem(workingDir+"/runinfo_tmp_zzzz.polyrun");
#else
	OSBasics::removeItem("runinfo_tmp_zzzz.polyrun");
#endif
	return 0;
}
Example #13
0
void EditorFileSystem::_scan_scenes() {

	ERR_FAIL_COND(!scanning || scandir);

	//read .fscache
	HashMap<String,FileCache> file_cache;
	HashMap<String,DirCache> dir_cache;
	DirCache *dc=NULL;
	String cpath;

	sources_changed.clear();



	String project=Globals::get_singleton()->get_resource_path();
	FileAccess *f =FileAccess::open(project+"/.fscache",FileAccess::READ);

	if (f) {
		//read the disk cache
		while(!f->eof_reached()) {

			String l = f->get_line().strip_edges();
			if (l==String())
				continue;

			if (l.begins_with("::")) {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 3);
				String name = split[1];

				dir_cache[name]=DirCache();
				dc=&dir_cache[name];
				dc->modification_time=split[2].to_int64();

				if (name!="res://") {

					cpath=name+"/";

					int sp=name.find_last("/");
					if (sp==5)
						sp=6;
					String pd = name.substr(0,sp);
					DirCache *dcp = dir_cache.getptr(pd);
					ERR_CONTINUE(!dcp);
					dcp->subdirs.insert(name.get_file());
				} else {

					cpath=name;
				}


			} else {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 4);
				String name = split[0];
				String file;

				if (!name.begins_with("res://")) {
					file=name;
					name=cpath+name;
				} else {
					file=name.get_file();
				}

				FileCache fc;
				fc.type=split[1];
				fc.modification_time=split[2].to_int64();
				String meta = split[3].strip_edges();
				fc.meta.enabled=false;
				if (meta.find("<>")!=-1){
					Vector<String> spl = meta.split("<>");
					int sc = spl.size()-1;
					if (sc%3==0){
						fc.meta.enabled=true;
						fc.meta.import_editor=spl[0];
						fc.meta.sources.resize(sc/3);
						for(int i=0;i<fc.meta.sources.size();i++) {
							fc.meta.sources[i].path=spl[1+i*3+0];
							fc.meta.sources[i].md5=spl[1+i*3+1];
							fc.meta.sources[i].modified_time=spl[1+i*3+2].to_int64();
						}

					}

				}
				file_cache[name]=fc;

				ERR_CONTINUE(!dc);
				dc->files.insert(file);
			}

		}

		f->close();
		memdelete(f);
	}






	total=0;
	DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	//da->change_dir( Globals::get_singleton()->get_resource_path() );


	List<String> extensionsl;
	ResourceLoader::get_recognized_extensions_for_type("",&extensionsl);
	Set<String> extensions;
	for(List<String>::Element *E = extensionsl.front();E;E=E->next()) {

		extensions.insert(E->get());
	}

	EditorProgressBG scan_progress("efs","ScanFS",100);

	md_count=0;
	scandir=_scan_dir(da,extensions,"",0,1,"",file_cache,dir_cache,scan_progress);
	memdelete(da);
	if (abort_scan && scandir) {
		memdelete(scandir);
		scandir=NULL;

	}


	//save back the findings
	f=FileAccess::open(project+"/.fscache",FileAccess::WRITE);
	_save_type_cache_fs(scandir,f);
	f->close();
	memdelete(f);

	scanning=false;

}
Example #14
0
void EditorExportPlatformBB10::_device_poll_thread(void *ud) {

	EditorExportPlatformBB10 *ea=(EditorExportPlatformBB10 *)ud;

	while(!ea->quit_request) {

		String bb_deploy=EditorSettings::get_singleton()->get("export/blackberry/host_tools");
		bb_deploy=bb_deploy.plus_file("blackberry-deploy");
		bool windows = OS::get_singleton()->get_name()=="Windows";
		if (windows)
			bb_deploy+=".bat";

		if (FileAccess::exists(bb_deploy)) {

			Vector<Device> devices;


			for (int i=0;i<MAX_DEVICES;i++) {

				String host = EditorSettings::get_singleton()->get("export/blackberry/device_"+itos(i+1)+"/host");
				if (host==String())
					continue;
				String pass = EditorSettings::get_singleton()->get("export/blackberry/device_"+itos(i+1)+"/password");
				if (pass==String())
					continue;

				List<String> args;
				args.push_back("-listDeviceInfo");
				args.push_back(host);
				args.push_back("-password");
				args.push_back(pass);


				int ec;
				String dp;

				Error err = OS::get_singleton()->execute(bb_deploy,args,true,NULL,&dp,&ec);

				if (err==OK && ec==0) {

					Device dev;
					dev.index=i;
					String descr;
					Vector<String> ls=dp.split("\n");

					for(int i=0;i<ls.size();i++) {

						String l = ls[i].strip_edges();
						if (l.begins_with("modelfullname::")) {
							dev.name=l.get_slice("::",1);
							descr+="Model: "+dev.name+"\n";
						}
						if (l.begins_with("modelnumber::")) {
							String s = l.get_slice("::",1);
							dev.name+=" ("+s+")";
							descr+="Model Number: "+s+"\n";
						}
						if (l.begins_with("scmbundle::"))
							descr+="OS Version: "+l.get_slice("::",1)+"\n";
						if (l.begins_with("[n]debug_token_expiration::"))
							descr+="Debug Token Expires:: "+l.get_slice("::",1)+"\n";

					}

					dev.description=descr;
					devices.push_back(dev);
				}

			}

			bool changed=false;


			ea->device_lock->lock();

			if (ea->devices.size()!=devices.size()) {
				changed=true;
			} else {

				for(int i=0;i<ea->devices.size();i++) {

					if (ea->devices[i].index!=devices[i].index) {
						changed=true;
						break;
					}
				}
			}

			if (changed) {

				ea->devices=devices;
				ea->devices_changed=true;
			}

			ea->device_lock->unlock();
		}


		uint64_t wait = 3000000;
		uint64_t time = OS::get_singleton()->get_ticks_usec();
		while(OS::get_singleton()->get_ticks_usec() - time < wait ) {
			OS::get_singleton()->delay_usec(1000);
			if (ea->quit_request)
				break;
		}
	}

}
Example #15
0
void EditorFileSystem::_scan_filesystem() {

	ERR_FAIL_COND(!scanning || new_filesystem);

	//read .fscache
	String cpath;

	sources_changed.clear();
	file_cache.clear();

	String project = ProjectSettings::get_singleton()->get_resource_path();

	String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_cache3");
	FileAccess *f = FileAccess::open(fscache, FileAccess::READ);

	if (f) {
		//read the disk cache
		while (!f->eof_reached()) {

			String l = f->get_line().strip_edges();
			if (l == String())
				continue;

			if (l.begins_with("::")) {
				Vector<String> split = l.split("::");
				ERR_CONTINUE(split.size() != 3);
				String name = split[1];

				cpath = name;

			} else {
				Vector<String> split = l.split("::");
				ERR_CONTINUE(split.size() != 6);
				String name = split[0];
				String file;

				file = name;
				name = cpath.plus_file(name);

				FileCache fc;
				fc.type = split[1];
				fc.modification_time = split[2].to_int64();
				fc.import_modification_time = split[3].to_int64();
				fc.import_valid = split[4].to_int64() != 0;

				String deps = split[5].strip_edges();
				if (deps.length()) {
					Vector<String> dp = deps.split("<>");
					for (int i = 0; i < dp.size(); i++) {
						String path = dp[i];
						fc.deps.push_back(path);
					}
				}

				file_cache[name] = fc;
			}
		}

		f->close();
		memdelete(f);
	}

	String update_cache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_update3");

	if (FileAccess::exists(update_cache)) {
		{
			FileAccessRef f = FileAccess::open(update_cache, FileAccess::READ);
			String l = f->get_line().strip_edges();
			while (l != String()) {

				file_cache.erase(l); //erase cache for this, so it gets updated
				l = f->get_line().strip_edges();
			}
		}

		DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
		d->remove(update_cache); //bye bye update cache
	}

	EditorProgressBG scan_progress("efs", "ScanFS", 1000);

	ScanProgress sp;
	sp.low = 0;
	sp.hi = 1;
	sp.progress = &scan_progress;

	new_filesystem = memnew(EditorFileSystemDirectory);
	new_filesystem->parent = NULL;

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
	d->change_dir("res://");
	_scan_new_dir(new_filesystem, d, sp);

	file_cache.clear(); //clear caches, no longer needed

	memdelete(d);

	f = FileAccess::open(fscache, FileAccess::WRITE);
	_save_filesystem_cache(new_filesystem, f);
	f->close();
	memdelete(f);

	scanning = false;
}
Example #16
0
Vec2i GLContext::drawLabel(const String& str, const Vec4f& pos, const Vec2f& align, U32 fgABGR, U32 bgABGR)
{
    // Split the string into lines.

    Array<String> lines;
    str.split('\n', lines, true);
    while (lines.getSize() && !lines.getLast().getLength())
        lines.removeLast();

    // Compute metrics.

    Vec2i strSize = 0;
    for (int i = 0; i < lines.getSize(); i++)
    {
        if (!lines[i].getLength())
            lines[i] = " "; // To avoid lineSize.y being zero.

        Vec2i lineSize = getStringSize(lines[i]);
        strSize.x = max(strSize.x, lineSize.x);
        strSize.y += lineSize.y;
    }

    // Empty or fully transparent => skip.

    if (strSize.x <= 0 || strSize.y <= 0 || ((fgABGR | bgABGR) & 0xFF000000) == 0)
        return strSize;

    // Initialize GL state.

    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Draw each line.

    Vec4f fgColor = Vec4f::fromABGR(fgABGR);
    Vec4f bgColor = Vec4f::fromABGR(bgABGR);
    Vec2f linePos(0.0f, (F32)strSize.y);

    for (int i = 0; i < lines.getSize(); i++)
    {
        Vec2i lineSize = (lines.getSize() == 1) ? strSize : getStringSize(lines[i]);
        if (lineSize.x <= 0 || lineSize.y <= 0)
            continue;

        linePos.y -= (F32)lineSize.y;
        const Vec2i& texSize = uploadString(lines[i], lineSize);

        Vec4f tpos = m_vgXform * pos;
        Vec2f pixel = m_viewScale * tpos.w;
        tpos.x += (linePos.x - align.x * (F32)lineSize.x) * pixel.x;
        tpos.y += (linePos.y - align.y * (F32)strSize.y) * pixel.y;
        tpos.x = floor((tpos.x + tpos.w) / pixel.x + 0.5f) * pixel.x - tpos.w;
        tpos.y = floor((tpos.y + tpos.w) / pixel.y + 0.5f) * pixel.y - tpos.w;

        if (bgColor.w > 0.0f)
            for (int j = -1; j <= 1; j++)
                for (int k = -1; k <= 1; k++)
                    drawString(tpos + Vec4f(Vec2f((F32)j, (F32)k) * pixel, 0.0f, 0.0f), lineSize, texSize, bgColor);

        if (fgColor.w > 0.0f)
            drawString(tpos, lineSize, texSize, fgColor);
    }

    // Clean up.

    glPopAttrib();
    checkErrors();
    return strSize;
}
Example #17
0
void ProjectExportDialog::_edit_preset(int p_index) {

	if (p_index < 0 || p_index >= presets->get_item_count()) {
		name->set_text("");
		name->set_editable(false);
		runnable->set_disabled(true);
		parameters->edit(NULL);
		delete_preset->set_disabled(true);
		sections->hide();
		patches->clear();
		export_error->hide();
		export_templates_error->hide();
		return;
	}

	Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(p_index);
	ERR_FAIL_COND(current.is_null());

	updating = true;

	presets->select(p_index);
	sections->show();

	name->set_editable(true);
	delete_preset->set_disabled(false);
	name->set_text(current->get_name());
	runnable->set_disabled(false);
	runnable->set_pressed(current->is_runnable());
	parameters->edit(current.ptr());

	export_filter->select(current->get_export_filter());
	include_filters->set_text(current->get_include_filter());
	exclude_filters->set_text(current->get_exclude_filter());

	patches->clear();
	TreeItem *patch_root = patches->create_item();
	Vector<String> patchlist = current->get_patches();
	for (int i = 0; i < patchlist.size(); i++) {
		TreeItem *patch = patches->create_item(patch_root);
		patch->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		String file = patchlist[i].get_file();
		patch->set_editable(0, true);
		patch->set_text(0, file.get_file().replace("*", ""));
		if (file.ends_with("*"))
			patch->set_checked(0, true);
		patch->set_tooltip(0, patchlist[i]);
		patch->set_metadata(0, i);
		patch->add_button(0, get_icon("Remove", "EditorIcons"), 0);
		patch->add_button(0, get_icon("folder", "FileDialog"), 1);
	}

	TreeItem *patch_add = patches->create_item(patch_root);
	patch_add->set_metadata(0, patchlist.size());
	if (patchlist.size() == 0)
		patch_add->set_text(0, "Add initial export..");
	else
		patch_add->set_text(0, "Add previous patches..");

	patch_add->add_button(0, get_icon("folder", "FileDialog"), 1);

	_fill_resource_tree();

	bool needs_templates;
	String error;
	if (!current->get_platform()->can_export(current, error, needs_templates)) {

		if (error != String()) {

			Vector<String> items = error.split("\n");
			error = "";
			for (int i = 0; i < items.size(); i++) {
				if (i > 0)
					error += "\n";
				error += " - " + items[i];
			}

			export_error->set_text(error);
			export_error->show();
		} else {
			export_error->hide();
		}
		if (needs_templates)
			export_templates_error->show();
		else
			export_templates_error->hide();

		export_button->set_disabled(true);

	} else {
		export_error->hide();
		export_templates_error->hide();
		export_button->set_disabled(false);
	}

	custom_features->set_text(current->get_custom_features());
	_update_feature_list();

	updating = false;
}
Material *MaterialManager::materialFromXMLNode(TiXmlNode *node) {
	String mname = node->ToElement()->Attribute("name");
	TiXmlNode* pChild, *pChild2,*pChild3;
	Shader *materialShader;
	ShaderBinding *newShaderBinding;
	
	vector<Shader*> materialShaders;
	vector<ShaderBinding*> newShaderBindings;
	vector<ShaderRenderTarget*> renderTargets;	

	Material *newMaterial = new Material(mname);

	for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) {
		if(strcmp(pChild3->Value(), "rendertargets") == 0) {
			for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
				if(strcmp(pChild->Value(), "rendertarget") == 0) {
					ShaderRenderTarget *newTarget = new ShaderRenderTarget;
					newTarget->id = pChild->ToElement()->Attribute("id");
					newTarget->width = CoreServices::getInstance()->getRenderer()->getXRes();
					newTarget->height = CoreServices::getInstance()->getRenderer()->getYRes();
					newTarget->sizeMode = ShaderRenderTarget::SIZE_MODE_PIXELS;					
					if(pChild->ToElement()->Attribute("width") && pChild->ToElement()->Attribute("height")) {
						newTarget->width = atof(pChild->ToElement()->Attribute("width"));
						newTarget->height = atof(pChild->ToElement()->Attribute("height"));
						if(pChild->ToElement()->Attribute("sizeMode")) {
							if(strcmp(pChild->ToElement()->Attribute("sizeMode"), "normalized") == 0) {
								if(newTarget->width > 1.0f)
									newTarget->width = 1.0f;
								if(newTarget->height > 1.0f)
									newTarget->height = 1.0f;
									
								newTarget->width = ((Number)CoreServices::getInstance()->getRenderer()->getXRes()) * newTarget->width;
								newTarget->height = ((Number)CoreServices::getInstance()->getRenderer()->getYRes()) * newTarget->height;
							}						
						}
					}						
//					Texture *newTexture = CoreServices::getInstance()->getMaterialManager()->createNewTexture(newTarget->width, newTarget->height, true);
					Texture *newTexture, *temp;
					CoreServices::getInstance()->getRenderer()->createRenderTextures(&newTexture, &temp, (int)newTarget->width, (int)newTarget->height);
					newTexture->setResourceName(newTarget->id);
					//CoreServices::getInstance()->getResourceManager()->addResource(newTexture);
					newTarget->texture = newTexture;
					renderTargets.push_back(newTarget);

				}
			}
		}	
	}
	
	for (pChild3 = node->FirstChild(); pChild3 != 0; pChild3 = pChild3->NextSibling()) {
	
		if(strcmp(pChild3->Value(), "specularValue") == 0) {
			newMaterial->specularValue = atof(pChild3->ToElement()->GetText());
		}

		if(strcmp(pChild3->Value(), "specularColor") == 0) {		
			String value = pChild3->ToElement()->GetText();
			vector<String> values = value.split(" ");
			if(values.size() == 4) {
				newMaterial->specularColor.setColor(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()),atof(values[3].c_str()));
			} else {
				Logger::log("Error: Incorrect number of values for specularColor (%d provided)!\n", values.size());
			}
		}

		if(strcmp(pChild3->Value(), "diffuseColor") == 0) {
			String value = pChild3->ToElement()->GetText();
			vector<String> values = value.split(" ");
			if(values.size() == 4) {
				newMaterial->diffuseColor.setColor(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()),atof(values[3].c_str()));
			} else {
				Logger::log("Error: Incorrect number of values for diffuseColor (%d provided)!\n", values.size());
			}

		}
		
		if(strcmp(pChild3->Value(), "shader") == 0) {
			materialShader = setShaderFromXMLNode(pChild3);
			if(materialShader) {
				newShaderBinding = materialShader->createBinding();
				materialShaders.push_back(materialShader);
				newShaderBindings.push_back(newShaderBinding);
				for (pChild = pChild3->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
					if(strcmp(pChild->Value(), "params") == 0) {
						for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) {
							if(strcmp(pChild2->Value(), "param") == 0){
								String pname =  pChild2->ToElement()->Attribute("name");
								String ptype =  pChild2->ToElement()->Attribute("type");
								String pvalue =  pChild2->ToElement()->Attribute("value");
								newShaderBinding->addParam(ptype, pname, pvalue);
							}						
						}
					}
					if(strcmp(pChild->Value(), "targettextures") == 0) {
						for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) {
							if(strcmp(pChild2->Value(), "targettexture") == 0){
							
								RenderTargetBinding* newBinding = new RenderTargetBinding;
								newBinding->id = pChild2->ToElement()->Attribute("id");
								
								newBinding->name = "";
								if(pChild2->ToElement()->Attribute("name")) {
									newBinding->name = pChild2->ToElement()->Attribute("name");
								}
								String mode = pChild2->ToElement()->Attribute("mode");
								if(strcmp(mode.c_str(), "in") == 0) {
									newBinding->mode = RenderTargetBinding::MODE_IN;
								} else {
									newBinding->mode = RenderTargetBinding::MODE_OUT;								
								}
																
								newShaderBinding->addRenderTargetBinding(newBinding);
								//Texture *texture =  (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, newBinding->id);
//								newBinding->texture = texture;
								
								for(int l=0; l < renderTargets.size(); l++) {
									if(renderTargets[l]->id == newBinding->id) {
										printf("Assigning texture to %s\n", newBinding->id.c_str());
										newBinding->texture = renderTargets[l]->texture;
										newBinding->width = renderTargets[l]->width;
										newBinding->height = renderTargets[l]->height;
									}
								}
								
								if(newBinding->mode == RenderTargetBinding::MODE_IN) {
									newShaderBinding->addTexture(newBinding->name, newBinding->texture);
								}
							}						
						}
					}					
					if(strcmp(pChild->Value(), "textures") == 0) {
						for (pChild2 = pChild->FirstChild(); pChild2 != 0; pChild2 = pChild2->NextSibling()) {
							if(strcmp(pChild2->Value(), "texture") == 0){
								String tname = "";
								if(pChild2->ToElement()->Attribute("name")) {
									tname =  pChild2->ToElement()->Attribute("name");
								}
								newShaderBinding->addTexture(tname, (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, pChild2->ToElement()->GetText()));
							}
							
							if(strcmp(pChild2->Value(), "cubemap") == 0){
								String tname = "";
								if(pChild2->ToElement()->Attribute("name")) {
									tname =  pChild2->ToElement()->Attribute("name");
								}
								newShaderBinding->addCubemap(tname, (Cubemap*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_CUBEMAP, pChild2->ToElement()->GetText()));
							}
							
						}
					}
				}
			}
		}
	}
	

	for(int i=0; i< materialShaders.size(); i++) {
		newMaterial->addShader(materialShaders[i],newShaderBindings[i]);
	}
	for(int i=0; i< renderTargets.size(); i++) {
		newMaterial->addShaderRenderTarget(renderTargets[i]);
	}
	
	return newMaterial;
}
Example #19
0
Error HTTPClient::poll(){

	switch(status) {


		case STATUS_RESOLVING: {
			ERR_FAIL_COND_V(resolving==IP::RESOLVER_INVALID_ID,ERR_BUG);

			IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving);
			switch(rstatus) {
				case IP::RESOLVER_STATUS_WAITING: return OK; //still resolving

				case IP::RESOLVER_STATUS_DONE: {

					IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving);
					Error err = tcp_connection->connect(host,conn_port);
					IP::get_singleton()->erase_resolve_item(resolving);
					resolving=IP::RESOLVER_INVALID_ID;
					if (err) {
						status=STATUS_CANT_CONNECT;
						return err;
					}

					status=STATUS_CONNECTING;
				} break;
				case IP::RESOLVER_STATUS_NONE:
				case IP::RESOLVER_STATUS_ERROR: {

					IP::get_singleton()->erase_resolve_item(resolving);
					resolving=IP::RESOLVER_INVALID_ID;
					close();
					status=STATUS_CANT_RESOLVE;
					return ERR_CANT_RESOLVE;
				} break;

			}
		} break;
		case STATUS_CONNECTING: {

			StreamPeerTCP::Status s = tcp_connection->get_status();
			switch(s) {

				case StreamPeerTCP::STATUS_CONNECTING: {
					return OK; //do none
				} break;
				case StreamPeerTCP::STATUS_CONNECTED: {
					status=STATUS_CONNECTED;
					return OK;
				} break;
				case StreamPeerTCP::STATUS_ERROR:
				case StreamPeerTCP::STATUS_NONE: {

					close();
					status=STATUS_CANT_CONNECT;
					return ERR_CANT_CONNECT;
				} break;
			}
		} break;
		case STATUS_CONNECTED: {
			//request something please
			return OK;
		} break;
		case STATUS_REQUESTING: {


			while(true) {
				uint8_t byte;
				int rec=0;
				Error err = connection->get_partial_data(&byte,1,rec);
				if (err!=OK) {
					close();
					status=STATUS_CONNECTION_ERROR;
					return ERR_CONNECTION_ERROR;
				}

				if (rec==0)
					return OK; //keep trying!

				response_str.push_back(byte);
				int rs = response_str.size();
				if (
					(rs>=2 && response_str[rs-2]=='\n' && response_str[rs-1]=='\n') ||
					(rs>=4 && response_str[rs-4]=='\r' && response_str[rs-3]=='\n' && rs>=4 && response_str[rs-2]=='\r' && response_str[rs-1]=='\n')
				) {


					//end of response, parse.
					response_str.push_back(0);
					String response;
					response.parse_utf8((const char*)response_str.ptr());
					print_line("END OF RESPONSE? :\n"+response+"\n------");
					Vector<String> responses = response.split("\n");
					body_size=0;
					chunked=false;
					body_left=0;
					chunk_left=0;
					response_headers.clear();
					response_num = RESPONSE_OK;

					for(int i=0;i<responses.size();i++) {

						String s = responses[i].strip_edges();
						if (s.length()==0)
							continue;						
						if (s.begins_with("Content-Length:")) {
							body_size = s.substr(s.find(":")+1,s.length()).strip_edges().to_int();
							body_left=body_size;
						}

						if (s.begins_with("Transfer-Encoding:")) {
							String encoding = s.substr(s.find(":")+1,s.length()).strip_edges();
							print_line("TRANSFER ENCODING: "+encoding);
							if (encoding=="chunked") {
								chunked=true;
							}

						}

						if (i==0 && responses[i].begins_with("HTTP")) {

							String num = responses[i].get_slice(" ",1);
							response_num=num.to_int();
						} else {

							response_headers.push_back(s);
						}

					}

					if (body_size==0 && !chunked) {

						status=STATUS_CONNECTED; //ask for something again?
					} else {
						status=STATUS_BODY;
					}
					return OK;
				}
			}
			//wait for response
			return OK;
		} break;
		case STATUS_DISCONNECTED: {
			return ERR_UNCONFIGURED;
		} break;
		case STATUS_CONNECTION_ERROR: {
			return ERR_CONNECTION_ERROR;
		} break;
		case STATUS_CANT_CONNECT: {
			return ERR_CANT_CONNECT;
		} break;
		case STATUS_CANT_RESOLVE: {
			return ERR_CANT_RESOLVE;
		} break;
	}


	return OK;
}
Example #20
0
	void List::loadFromPath(const String& folder)
	{
		String path;
		IO::Canonicalize(path, folder);
		if (pOptDebug)
			std::cout << "[yuni-config][debug] :: reading `" << path << "`" << std::endl;

		VersionInfo::Settings info;
		info.mapping = mappingStandard;

		String s;
		s << path << SEP << "yuni.version";
		if (not IO::File::Exists(s))
		{
			s.clear() << path << SEP << "include" << SEP << "yuni" << SEP << "yuni.version";
			if (not IO::File::Exists(s))
			{
				info.mapping = mappingSVNSources;
				s.clear() << path << SEP << "src" << SEP << "yuni" << SEP << "yuni.version";
				if (not IO::File::Exists(s))
                {
					if (pOptDebug)
						std::cout << "[yuni-config][debug] :: " << s << " not found" << std::endl;
					return;
                }
			}
		}

		IO::File::Stream file;
		if (file.open(s))
		{
			String key;
			String value;

			Version version;

			// A buffer. The given capacity will be the maximum length for a single line
			Clob buffer;
			buffer.reserve(8000);
			while (file.readline(buffer))
			{
				buffer.extractKeyValue(key, value);

				if (key.empty() || key == "[")
					continue;
				if (key == "version.hi")
					version.hi = value.to<unsigned int>();
				if (key == "version.lo")
					version.lo = value.to<unsigned int>();
				if (key == "version.rev")
					version.revision = value.to<unsigned int>();
				if (key == "version.target")
					info.compilationMode = value;
				if (key == "modules.available")
					value.split(info.modules, ";\"', \t", false);
				if (key == "support.opengl")
					info.supportOpenGL = value.to<bool>();
				if (key == "support.directx")
					info.supportDirectX = value.to<bool>();
				if (key == "redirect")
					loadFromPath(value);
				if (key == "path.include")
				{
					if (not value.empty())
						info.includePath.push_back(value);
				}
				if (key == "path.lib")
				{
					if (not value.empty())
						info.libPath.push_back(value);
				}
			}

			if (not version.null() and not info.modules.empty())
			{
				info.path = path;
				info.compiler = pCompiler;
				pList[version] = info;

				if (pOptDebug)
				{
					std::cout << "[yuni-config][debug]  - found installation `" << path
						<< "` (" << version << ")" << std::endl;
				}
			}
			else
			{
				std::cerr << "error: " << s << ": invalid file";
				if (version.null())
					std::cerr << " (invalid version)" << std::endl;
				else if (info.modules.empty())
					std::cerr << " (no module)" << std::endl;
			}
		}
	}
Example #21
0
int main(int argc, char** argv)
{
    RemoveCrashDump removeCrashDump;
#ifdef OS_Darwin
    struct rlimit rlp;
    if (getrlimit(RLIMIT_NOFILE, &rlp) == 0) {
        if (rlp.rlim_cur < 1000) {
            rlp.rlim_cur = 1000;
            setrlimit(RLIMIT_NOFILE, &rlp);
        }
    }
#endif

    {
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_getstacksize(&attr, &defaultStackSize);
        pthread_attr_destroy(&attr);
        if (defaultStackSize < 1024 * 1024 * 4) { // 4 megs should be enough for everyone right?
            defaultStackSize = 1024 * 1024 * 4;
        }
    }

    Rct::findExecutablePath(*argv);

    struct option opts[] = {
        { "help", no_argument, 0, 'h' },
        { "version", no_argument, 0, 2 },
        { "include-path", required_argument, 0, 'I' },
        { "isystem", required_argument, 0, 's' },
        { "define", required_argument, 0, 'D' },
        { "log-file", required_argument, 0, 'L' },
        { "crash-dump-file", required_argument, 0, 19 },
        { "setenv", required_argument, 0, 'e' },
        { "no-Wall", no_argument, 0, 'W' },
        { "Weverything", no_argument, 0, 'u' },
        { "cache-AST", required_argument, 0, 'A' },
        { "verbose", no_argument, 0, 'v' },
        { "job-count", required_argument, 0, 'j' },
        { "header-error-job-count", required_argument, 0, 'H' },
        { "test", required_argument, 0, 't' },
        { "test-timeout", required_argument, 0, 'z' },
        { "clean-slate", no_argument, 0, 'C' },
        { "disable-sighandler", no_argument, 0, 'x' },
        { "silent", no_argument, 0, 'S' },
        { "exclude-filter", required_argument, 0, 'X' },
        { "socket-file", required_argument, 0, 'n' },
        { "config", required_argument, 0, 'c' },
        { "no-rc", no_argument, 0, 'N' },
        { "data-dir", required_argument, 0, 'd' },
        { "ignore-printf-fixits", no_argument, 0, 'F' },
        { "no-unlimited-errors", no_argument, 0, 'f' },
        { "block-argument", required_argument, 0, 'G' },
        { "no-spell-checking", no_argument, 0, 'l' },
        { "large-by-value-copy", required_argument, 0, 'r' },
        { "disallow-multiple-sources", no_argument, 0, 'm' },
        { "no-startup-project", no_argument, 0, 'o' },
        { "no-no-unknown-warnings-option", no_argument, 0, 'Y' },
        { "ignore-compiler", required_argument, 0, 'b' },
        { "watch-system-paths", no_argument, 0, 'w' },
        { "rp-visit-file-timeout", required_argument, 0, 'Z' },
        { "rp-indexer-message-timeout", required_argument, 0, 'T' },
        { "rp-connect-timeout", required_argument, 0, 'O' },
        { "rp-connect-attempts", required_argument, 0, 3 },
        { "rp-nice-value", required_argument, 0, 'a' },
        { "thread-stack-size", required_argument, 0, 'k' },
        { "suspend-rp-on-crash", no_argument, 0, 'q' },
        { "rp-log-to-syslog", no_argument, 0, 7 },
        { "start-suspended", no_argument, 0, 'Q' },
        { "separate-debug-and-release", no_argument, 0, 'E' },
        { "max-crash-count", required_argument, 0, 'K' },
        { "completion-cache-size", required_argument, 0, 'i' },
        { "completion-no-filter", no_argument, 0, 8 },
        { "extra-compilers", required_argument, 0, 'U' },
        { "allow-Wpedantic", no_argument, 0, 'P' },
        { "enable-compiler-manager", no_argument, 0, 'R' },
        { "enable-NDEBUG", no_argument, 0, 'g' },
        { "progress", no_argument, 0, 'p' },
        { "max-file-map-cache-size", required_argument, 0, 'y' },
#ifdef OS_FreeBSD
        { "filemanager-watch", no_argument, 0, 'M' },
#else
        { "no-filemanager-watch", no_argument, 0, 'M' },
#endif
        { "no-filemanager", no_argument, 0, 15 },
        { "no-file-lock", no_argument, 0, 13 },
        { "pch-enabled", no_argument, 0, 14 },
        { "no-filesystem-watcher", no_argument, 0, 'B' },
        { "arg-transform", required_argument, 0, 'V' },
        { "no-comments", no_argument, 0, 1 },
#ifdef RTAGS_HAS_LAUNCHD
        { "launchd", no_argument, 0, 4 },
#endif
        { "inactivity-timeout", required_argument, 0, 5 },
        { "daemon", no_argument, 0, 6 },
        { "log-file-log-level", required_argument, 0, 9 },
        { "watch-sources-only", no_argument, 0, 10 },
        { "debug-locations", no_argument, 0, 11 },
        { "validate-file-maps", no_argument, 0, 16 },
        { "tcp-port", required_argument, 0, 12 },
        { "rp-path", required_argument, 0, 17 },
        { "log-timestamp", no_argument, 0, 18 },
        { "root", required_argument, 0, 20 },
        { 0, 0, 0, 0 }
    };
    const String shortOptions = Rct::shortOptions(opts);
    if (getenv("RTAGS_DUMP_UNUSED")) {
        String unused;
        for (int i=0; i<26; ++i) {
            if (!shortOptions.contains('a' + i))
                unused.append('a' + i);
            if (!shortOptions.contains('A' + i))
                unused.append('A' + i);
        }
        printf("Unused: %s\n", unused.constData());
        for (int i=0; opts[i].name; ++i) {
            if (opts[i].name) {
                if (!opts[i].val) {
                    printf("No shortoption for %s\n", opts[i].name);
                } else if (opts[i].name[0] != opts[i].val) {
                    printf("Not ideal option for %s|%c\n", opts[i].name, opts[i].val);
                }
            }
        }
        return 0;
    }

    bool daemon = false;
    List<String> argCopy;
    List<char*> argList;
    {
        bool norc = false;
        Path rcfile = Path::home() + ".rdmrc";
        opterr = 0;

        StackBuffer<128, char*> originalArgv(argc);
        memcpy(originalArgv, argv, sizeof(char*) * argc);
        /* getopt will molest argv by moving pointers around when it sees
         * fit. Their idea of an optional argument is different from ours so we
         * have to take a copy of argv before they get their sticky fingers all
         * over it.
         *
         * We think this should be okay for an optional argument:
         * -s something
         *
         * They only populate optarg if you do:
         * -ssomething.
         *
         * We don't want to copy argv into argList before processing rc files
         * since command line args should take precedence over things in rc
         * files.
         *
         */

        while (true) {
            const int c = getopt_long(argc, argv, shortOptions.constData(), opts, 0);
            if (c == -1)
                break;
            switch (c) {
            case 'N':
                norc = true;
                break;
            case 'c':
                rcfile = optarg;
                break;
            default:
                break;
            }
        }
        opterr = 1;
        argList.append(argv[0]);
        if (!norc) {
            String rc = Path("/etc/rdmrc").readAll();
            if (!rc.isEmpty()) {
                for (const String& s : rc.split('\n')) {
                    if (!s.isEmpty() && !s.startsWith('#'))
                        argCopy += s.split(' ');
                }
            }
            if (!rcfile.isEmpty()) {
                rc = rcfile.readAll();
                if (!rc.isEmpty()) {
                    for (const String& s : rc.split('\n')) {
                        if (!s.isEmpty() && !s.startsWith('#'))
                            argCopy += s.split(' ');
                    }
                }
            }
            const int s = argCopy.size();
            for (int i=0; i<s; ++i) {
                String &arg = argCopy.at(i);
                if (!arg.isEmpty())
                    argList.append(arg.data());
            }
        }

        for (int i=1; i<argc; ++i)
            argList.append(originalArgv[i]);

        optind = 1;
    }

    Server::Options serverOpts;
    serverOpts.threadStackSize = defaultStackSize;
    serverOpts.socketFile = String::format<128>("%s.rdm", Path::home().constData());
    serverOpts.jobCount = std::max(2, ThreadPool::idealThreadCount());
    serverOpts.headerErrorJobCount = -1;
    serverOpts.rpVisitFileTimeout = DEFAULT_RP_VISITFILE_TIMEOUT;
    serverOpts.rpIndexDataMessageTimeout = DEFAULT_RP_INDEXER_MESSAGE_TIMEOUT;
    serverOpts.rpConnectTimeout = DEFAULT_RP_CONNECT_TIMEOUT;
    serverOpts.rpConnectAttempts = DEFAULT_RP_CONNECT_ATTEMPTS;
    serverOpts.maxFileMapScopeCacheSize = DEFAULT_RDM_MAX_FILE_MAP_CACHE_SIZE;
    serverOpts.rpNiceValue = INT_MIN;
    serverOpts.options = Server::Wall|Server::SpellChecking;
    serverOpts.maxCrashCount = DEFAULT_MAX_CRASH_COUNT;
    serverOpts.completionCacheSize = DEFAULT_COMPLETION_CACHE_SIZE;
    serverOpts.rp = defaultRP();
    strcpy(crashDumpFilePath, "crash.dump");
#ifdef OS_FreeBSD
    serverOpts.options |= Server::NoFileManagerWatch;
#endif
// #ifndef NDEBUG
//     serverOpts.options |= Server::SuspendRPOnCrash;
// #endif
    serverOpts.dataDir = String::format<128>("%s.rtags", Path::home().constData());

    const char *logFile = 0;
    Flags<LogFlag> logFlags = DontRotate|LogStderr;
    LogLevel logLevel(LogLevel::Error);
    LogLevel logFileLogLevel(LogLevel::Error);
    bool sigHandler = true;
    assert(Path::home().endsWith('/'));
    int argCount = argList.size();
    char **args = argList.data();
    bool defaultDataDir = true;
    int inactivityTimeout = 0;

    while (true) {
        const int c = getopt_long(argCount, args, shortOptions.constData(), opts, 0);
        if (c == -1)
            break;
        switch (c) {
        case 'N':
        case 'c':
            // ignored
            break;
        case 'S':
            logLevel = LogLevel::None;
            break;
        case 'X':
            serverOpts.excludeFilters += String(optarg).split(';');
            break;
        case 'G':
            serverOpts.blockedArguments << optarg;
            break;
        case 1:
            serverOpts.options |= Server::NoComments;
            break;
        case 10:
            serverOpts.options |= Server::WatchSourcesOnly;
            break;
        case 11:
            if (!strcmp(optarg, "clear") || !strcmp(optarg, "none")) {
                serverOpts.debugLocations.clear();
            } else {
                serverOpts.debugLocations << optarg;
            }
            break;
        case 12:
            serverOpts.tcpPort = atoi(optarg);
            if (!serverOpts.tcpPort) {
                fprintf(stderr, "Invalid port %s for --tcp-port\n", optarg);
                return 1;
            }
            break;
        case 13:
            serverOpts.options |= Server::NoFileLock;
            break;
        case 14:
            serverOpts.options |= Server::PCHEnabled;
            break;
        case 15:
            serverOpts.options |= Server::NoFileManager;
            break;
        case 16:
            serverOpts.options |= Server::ValidateFileMaps;
            break;
        case 17:
            serverOpts.rp = optarg;
            if (serverOpts.rp.isFile())
                serverOpts.rp.resolve();
            break;
        case 18:
            logFlags |= LogTimeStamp;
            break;
        case 19:
            strcpy(crashDumpFilePath, optarg);
            break;
        case 20:
            serverOpts.root = optarg;
            if (!serverOpts.root.resolve() || !serverOpts.root.isDir()) {
                fprintf(stderr, "%s is not a directory\n", optarg);
                return 1;
            }
            break;
        case 2:
            fprintf(stdout, "%s\n", RTags::versionString().constData());
            return 0;
        case 6:
            daemon = true;
            logLevel = LogLevel::None;
            break;
        case 9:
            if (!strcasecmp(optarg, "verbose-debug")) {
                logFileLogLevel = LogLevel::VerboseDebug;
            } else if (!strcasecmp(optarg, "debug")) {
                logFileLogLevel = LogLevel::Debug;
            } else if (!strcasecmp(optarg, "warning")) {
                logFileLogLevel = LogLevel::Warning;
            } else if (!strcasecmp(optarg, "error")) {
                logFileLogLevel = LogLevel::Error;
            } else {
                fprintf(stderr, "Unknown log level: %s options are error, warning, debug or verbose-debug\n",
                        optarg);
                return 1;
            }
            break;
        case 'U':
            serverOpts.extraCompilers.append(std::regex(optarg));
            break;
        case 'E':
            serverOpts.options |= Server::SeparateDebugAndRelease;
            break;
        case 'g':
            serverOpts.options |= Server::EnableNDEBUG;
            break;
        case 'Q':
            serverOpts.options |= Server::StartSuspended;
            break;
        case 'Z':
            serverOpts.rpVisitFileTimeout = atoi(optarg);
            if (serverOpts.rpVisitFileTimeout < 0) {
                fprintf(stderr, "Invalid argument to -Z %s\n", optarg);
                return 1;
            }
            if (!serverOpts.rpVisitFileTimeout)
                serverOpts.rpVisitFileTimeout = -1;
            break;
        case 'y':
            serverOpts.maxFileMapScopeCacheSize = atoi(optarg);
            if (serverOpts.maxFileMapScopeCacheSize <= 0) {
                fprintf(stderr, "Invalid argument to -y %s\n", optarg);
                return 1;
            }
            break;
        case 'O':
            serverOpts.rpConnectTimeout = atoi(optarg);
            if (serverOpts.rpConnectTimeout < 0) {
                fprintf(stderr, "Invalid argument to -O %s\n", optarg);
                return 1;
            }
            break;
        case 3:
            serverOpts.rpConnectAttempts = atoi(optarg);
            if (serverOpts.rpConnectAttempts <= 0) {
                fprintf(stderr, "Invalid argument to --rp-connect-attempts %s\n", optarg);
                return 1;
            }
            break;
        case 'k':
            serverOpts.threadStackSize = atoi(optarg);
            if (serverOpts.threadStackSize < 0) {
                fprintf(stderr, "Invalid argument to -k %s\n", optarg);
                return 1;
            }
            break;
        case 'b':
            serverOpts.ignoredCompilers.insert(Path::resolved(optarg));
            break;
        case 't': {
            Path test(optarg);
            if (!test.resolve() || !test.isFile()) {
                fprintf(stderr, "%s doesn't seem to be a file\n", optarg);
                return 1;
            }
            serverOpts.tests += test;
            break; }
        case 'z':
            serverOpts.testTimeout = atoi(optarg);
            if (serverOpts.testTimeout <= 0) {
                fprintf(stderr, "Invalid argument to -z %s\n", optarg);
                return 1;
            }
            break;
        case 'n':
            serverOpts.socketFile = optarg;
            break;
        case 'd':
            defaultDataDir = false;
            serverOpts.dataDir = String::format<128>("%s", Path::resolved(optarg).constData());
            break;
        case 'h':
            usage(stdout);
            return 0;
        case 'Y':
            serverOpts.options |= Server::NoNoUnknownWarningsOption;
            break;
        case 'p':
            serverOpts.options |= Server::Progress;
            break;
        case 'R':
            serverOpts.options |= Server::EnableCompilerManager;
            break;
        case 'm':
            serverOpts.options |= Server::DisallowMultipleSources;
            break;
        case 'o':
            serverOpts.options |= Server::NoStartupCurrentProject;
            break;
        case 'w':
            serverOpts.options |= Server::WatchSystemPaths;
            break;
        case 'q':
            serverOpts.options |= Server::SuspendRPOnCrash;
            break;
        case 'M':
#ifdef OS_FreeBSD
            serverOpts.options &= ~Server::NoFileManagerWatch;
#else
            serverOpts.options |= Server::NoFileManagerWatch;
#endif
            break;
        case 'B':
            serverOpts.options |= Server::NoFileSystemWatch;
            break;
        case 'V':
            serverOpts.argTransform = Process::findCommand(optarg);
            if (strlen(optarg) && serverOpts.argTransform.isEmpty()) {
                fprintf(stderr, "Invalid argument to -V. Can't resolve %s", optarg);
                return 1;
            }

            break;
      case 'F':
            serverOpts.options |= Server::IgnorePrintfFixits;
            break;
        case 'f':
            serverOpts.options |= Server::NoUnlimitedErrors;
            break;
        case 'l':
            serverOpts.options &= ~Server::SpellChecking;
            break;
        case 'W':
            serverOpts.options &= ~Server::Wall;
            break;
        case 'u':
            serverOpts.options |= Server::Weverything;
            break;
        case 'P':
            serverOpts.options |= Server::AllowPedantic;
            break;
        case 'C':
            serverOpts.options |= Server::ClearProjects;
            break;
        case 'e':
            putenv(optarg);
            break;
        case 'x':
            sigHandler = false;
            break;
        case 'K':
            serverOpts.maxCrashCount = atoi(optarg);
            if (serverOpts.maxCrashCount <= 0) {
                fprintf(stderr, "Invalid argument to -K %s\n", optarg);
                return 1;
            }
            break;
        case 'i':
            serverOpts.completionCacheSize = atoi(optarg);
            if (serverOpts.completionCacheSize <= 0) {
                fprintf(stderr, "Invalid argument to -i %s\n", optarg);
                return 1;
            }
            break;
        case 'T':
            serverOpts.rpIndexDataMessageTimeout = atoi(optarg);
            if (serverOpts.rpIndexDataMessageTimeout <= 0) {
                fprintf(stderr, "Can't parse argument to -T %s.\n", optarg);
                return 1;
            }
            break;
        case 'a': {
            bool ok;
            serverOpts.rpNiceValue = String(optarg).toLong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -a %s.\n", optarg);
                return 1;
            }
            break; }
        case 'j': {
            bool ok;
            serverOpts.jobCount = String(optarg).toULong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -j %s. -j must be a positive integer.\n", optarg);
                return 1;
            }
            break; }
        case 'H': {
            bool ok;
            serverOpts.headerErrorJobCount = String(optarg).toULong(&ok);
            if (!ok) {
                fprintf(stderr, "Can't parse argument to -H %s. -H must be a positive integer.\n", optarg);
                return 1;
            }
            break; }
        case 'r': {
            int large = atoi(optarg);
            if (large <= 0) {
                fprintf(stderr, "Can't parse argument to -r %s\n", optarg);
                return 1;
            }
            serverOpts.defaultArguments.append("-Wlarge-by-value-copy=" + String(optarg)); // ### not quite working
            break; }
        case 'D': {
            const char *eq = strchr(optarg, '=');
            Source::Define def;
            if (!eq) {
                def.define = optarg;
            } else {
                def.define = String(optarg, eq - optarg);
                def.value = eq + 1;
            }
            serverOpts.defines.append(def);
            break; }
        case 'I':
            serverOpts.includePaths.append(Source::Include(Source::Include::Type_Include, Path::resolved(optarg)));
            break;
        case 's':
            serverOpts.includePaths.append(Source::Include(Source::Include::Type_System, Path::resolved(optarg)));
            break;
        case 'L':
            logFile = optarg;
            logLevel = LogLevel::None;
            break;
        case 'v':
            if (logLevel != LogLevel::None)
                ++logLevel;
            break;
#ifdef RTAGS_HAS_LAUNCHD
        case 4:
            serverOpts.options |= Server::Launchd;
            break;
#endif
        case 5:
            inactivityTimeout = atoi(optarg); // seconds.
            if (inactivityTimeout <= 0) {
                fprintf(stderr, "Invalid argument to --inactivity-timeout %s\n", optarg);
                return 1;
            }
            break;
        case 7:
            serverOpts.options |= Server::RPLogToSyslog;
            break;
        case 8:
            serverOpts.options |= Server::CompletionsNoFilter;
            break;
        case '?': {
            fprintf(stderr, "Run rdm --help for help\n");
            return 1; }
        }
    }
    if (optind < argCount) {
        fprintf(stderr, "rdm: unexpected option -- '%s'\n", args[optind]);
        return 1;
    }

    if (daemon) {
        switch (fork()) {
        case -1:
            fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno));
            return 1;
        case 0:
            setsid();
            switch (fork()) {
            case -1:
                fprintf(stderr, "Failed to fork (%d) %s\n", errno, strerror(errno));
                return 1;
            case 0:
                break;
            default:
                return 0;
            }
            break;
        default:
            return 0;
        }
    }

    if (serverOpts.excludeFilters.isEmpty())
        serverOpts.excludeFilters = String(EXCLUDEFILTER_DEFAULT).split(';');

    if (!serverOpts.headerErrorJobCount) {
        serverOpts.headerErrorJobCount = std::max<size_t>(1, serverOpts.jobCount / 2);
    } else {
        serverOpts.headerErrorJobCount = std::min(serverOpts.headerErrorJobCount, serverOpts.jobCount);
    }

    if (sigHandler) {
        signal(SIGSEGV, signalHandler);
        signal(SIGBUS, signalHandler);
        signal(SIGILL, signalHandler);
        signal(SIGABRT, signalHandler);
    }

    // Shell-expand logFile
    Path logPath(logFile); logPath.resolve();

    if (!initLogging(argv[0], logFlags, logLevel, logPath.constData(), logFileLogLevel)) {
        fprintf(stderr, "Can't initialize logging with %d %s %s\n",
                logLevel.toInt(), logFile ? logFile : "", logFlags.toString().constData());
        return 1;
    }

#ifdef RTAGS_HAS_LAUNCHD
    if (serverOpts.options & Server::Launchd) {
        // Clamp inactivity timeout. launchd starts to worry if the
        // process runs for less than 10 seconds.

        static const int MIN_INACTIVITY_TIMEOUT = 15; // includes
                                                      // fudge factor.

        if (inactivityTimeout < MIN_INACTIVITY_TIMEOUT) {
            inactivityTimeout = MIN_INACTIVITY_TIMEOUT;
            fprintf(stderr, "launchd mode - clamped inactivity timeout to %d to avoid launchd warnings.\n", inactivityTimeout);
        }
    }
#endif

    EventLoop::SharedPtr loop(new EventLoop);
    loop->init(EventLoop::MainEventLoop|EventLoop::EnableSigIntHandler|EventLoop::EnableSigTermHandler);

    std::shared_ptr<Server> server(new Server);
    if (!serverOpts.tests.isEmpty()) {
        char buf[1024];
        Path path;
        while (true) {
            strcpy(buf, "/tmp/rtags-test-XXXXXX");
            if (!mkdtemp(buf)) {
                fprintf(stderr, "Failed to mkdtemp (%d)\n", errno);
                return 1;
            }
            path = buf;
            path.resolve();
            break;
        }
        serverOpts.dataDir = path;
        strcpy(buf, "/tmp/rtags-sock-XXXXXX");
        const int fd = mkstemp(buf);
        if (fd == -1) {
            fprintf(stderr, "Failed to mkstemp (%d)\n", errno);
            return 1;
        }
        close(fd);
        serverOpts.socketFile = buf;
        serverOpts.socketFile.resolve();
    }
    if (defaultDataDir) {
        Path migration = String::format<128>("%s.rtags-file", Path::home().constData());
        if (migration.isDir()) {
            Rct::removeDirectory(serverOpts.dataDir);
            rename(migration.constData(), serverOpts.dataDir.constData());
            error() << "Migrated datadir from ~/.rtags-file ~/.rtags";
        }
    }
    serverOpts.dataDir = serverOpts.dataDir.ensureTrailingSlash();

#ifdef HAVE_BACKTRACE
    if (strlen(crashDumpFilePath)) {
        if (crashDumpFilePath[0] != '/') {
            const String f = crashDumpFilePath;
            snprintf(crashDumpFilePath, sizeof(crashDumpFilePath), "%s%s", serverOpts.dataDir.constData(), f.constData());
        }
        snprintf(crashDumpTempFilePath, sizeof(crashDumpTempFilePath), "%s.tmp", crashDumpFilePath);
        Path::mkdir(serverOpts.dataDir);
        crashDumpFile = fopen(crashDumpTempFilePath, "w");
        if (!crashDumpFile) {
            fprintf(stderr, "Couldn't open temp file %s for write (%d)", crashDumpTempFilePath, errno);
            return 1;
        }
    }
#endif

    if (!server->init(serverOpts)) {
        cleanupLogging();
        return 1;
    }

    if (!serverOpts.tests.isEmpty()) {
        return server->runTests() ? 0 : 1;
    }

    loop->setInactivityTimeout(inactivityTimeout * 1000);

    loop->exec();
    const int ret = server->exitCode();
    server.reset();
    cleanupLogging();
    return ret;
}
Example #22
0
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
    struct engine* engine = (struct engine*)app->userData;
  // LOGI("**** CMD %i\n",cmd);
    switch (cmd) {
	case APP_CMD_SAVE_STATE:
	    // The system has asked us to save our current state.  Do so.
	    //engine->app->savedState = malloc(sizeof(struct saved_state));
	    //*((struct saved_state*)engine->app->savedState) = engine->state;
	    //engine->app->savedStateSize = sizeof(struct saved_state);
	    break;
	case APP_CMD_CONFIG_CHANGED:
	case APP_CMD_WINDOW_RESIZED: {

#if 0
// android blows
		if (engine->display_active) {

			EGLint w,h;
			eglQuerySurface(engine->display, engine->surface, EGL_WIDTH, &w);
			eglQuerySurface(engine->display, engine->surface, EGL_HEIGHT, &h);
			engine->os->init_video_mode(w,h);
			//print_line("RESIZED VIDEO MODE: "+itos(w)+","+itos(h));
			engine_draw_frame(engine);

		}
#else

		    if (engine->display_active) {


			    EGLint w,h;
			    eglQuerySurface(engine->display, engine->surface, EGL_WIDTH, &w);
			    eglQuerySurface(engine->display, engine->surface, EGL_HEIGHT, &h);
			  //  if (w==engine->os->get_video_mode().width && h==engine->os->get_video_mode().height)
				//    break;

			    engine_term_display(engine);


		    }


		    engine->os->reload_gfx();
		    engine_draw_frame(engine);
		    engine->animating=1;

		    /*
			    EGLint w,h;
			    eglQuerySurface(engine->display, engine->surface, EGL_WIDTH, &w);
			    eglQuerySurface(engine->display, engine->surface, EGL_HEIGHT, &h);
			    engine->os->init_video_mode(w,h);
			    //print_line("RESIZED VIDEO MODE: "+itos(w)+","+itos(h));

		    }*/

#endif

	} break;
	case APP_CMD_INIT_WINDOW:
	     //The window is being shown, get it ready.
	//	LOGI("INIT WINDOW");
		if (engine->app->window != NULL) {

			if (engine->os==NULL) {

				//do initialization here, when there's OpenGL! hackish but the only way
				engine->os = new OS_Android(_gfx_init,engine);

			//	char *args[]={"-test","gui",NULL};
				__android_log_print(ANDROID_LOG_INFO,"godot","pre asdasd setup...");
#if 0
				Error err  = Main::setup("apk",2,args);
#else
				Error err  = Main::setup("apk",0,NULL);

				String modules = GlobalConfig::get_singleton()->get("android/modules");
				Vector<String> mods = modules.split(",",false);
				mods.push_back("GodotOS");
				__android_log_print(ANDROID_LOG_INFO,"godot","mod count: %i",mods.size());

				if (mods.size()) {

					jclass activityClass = engine->jni->FindClass("android/app/NativeActivity");

					jmethodID getClassLoader = engine->jni->GetMethodID(activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");

					jobject cls = engine->jni->CallObjectMethod(app->activity->clazz, getClassLoader);

					jclass classLoader = engine->jni->FindClass("java/lang/ClassLoader");

					jmethodID findClass = engine->jni->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");


					static JNINativeMethod methods[] = {
					    {"registerSingleton",    "(Ljava/lang/String;Ljava/lang/Object;)V",(void *)&Java_org_godotengine_godot_Godot_registerSingleton},
					    {"registerMethod",        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V",(void *)&Java_org_godotengine_godot_Godot_registerMethod},
					    {"getGlobal",      "(Ljava/lang/String;)Ljava/lang/String;",                    (void *)&Java_org_godotengine_godot_Godot_getGlobal},
					};

					jstring gstrClassName = engine->jni->NewStringUTF("org/godotengine/godot/Godot");
					jclass GodotClass = (jclass)engine->jni->CallObjectMethod(cls, findClass, gstrClassName);

					__android_log_print(ANDROID_LOG_INFO,"godot","godot ****^*^*?^*^*class data %x",GodotClass);

					engine->jni->RegisterNatives(GodotClass,methods,sizeof(methods)/sizeof(methods[0]));

					for (int i=0;i<mods.size();i++) {

						String m = mods[i];
						//jclass singletonClass = engine->jni->FindClass(m.utf8().get_data());

						jstring strClassName = engine->jni->NewStringUTF(m.utf8().get_data());
						jclass singletonClass = (jclass)engine->jni->CallObjectMethod(cls, findClass, strClassName);

						__android_log_print(ANDROID_LOG_INFO,"godot","****^*^*?^*^*class data %x",singletonClass);
						jmethodID initialize = engine->jni->GetStaticMethodID(singletonClass, "initialize", "(Landroid/app/Activity;)Lorg/godotengine/godot/Godot$SingletonBase;");


						jobject obj = engine->jni->CallStaticObjectMethod(singletonClass,initialize,app->activity->clazz);
						__android_log_print(ANDROID_LOG_INFO,"godot","****^*^*?^*^*class instance %x",obj);
						jobject gob = engine->jni->NewGlobalRef(obj);


					}

				}

#endif


				if (!Main::start())
					 return; //should exit instead and print the error

				engine->os->main_loop_begin();
			} else {
				//i guess recreate resources?
				engine->os->reload_gfx();
			}


			engine->animating=1;
			engine_draw_frame(engine);
		}
	    break;
	case APP_CMD_TERM_WINDOW:
	    // The window is being hidden or closed, clean it up.
	//    LOGI("TERM WINDOW");
	    engine_term_display(engine);
	    break;
	case APP_CMD_GAINED_FOCUS:
	    // When our app gains focus, we start monitoring the accelerometer.
	    if (engine->accelerometerSensor != NULL) {
		ASensorEventQueue_enableSensor(engine->sensorEventQueue,
			engine->accelerometerSensor);
		// We'd like to get 60 events per second (in us).
		ASensorEventQueue_setEventRate(engine->sensorEventQueue,
			engine->accelerometerSensor, (1000L/60)*1000);

	    }
	    // Also start monitoring the magnetometer.
	    if (engine->magnetometerSensor != NULL) {
		ASensorEventQueue_enableSensor(engine->sensorEventQueue,
			engine->magnetometerSensor);
		// We'd like to get 60 events per second (in us).
		ASensorEventQueue_setEventRate(engine->sensorEventQueue,
			engine->magnetometerSensor, (1000L/60)*1000);

	    }
	    // And the gyroscope.
	    if (engine->gyroscopeSensor != NULL) {
		ASensorEventQueue_enableSensor(engine->sensorEventQueue,
			engine->gyroscopeSensor);
		// We'd like to get 60 events per second (in us).
		ASensorEventQueue_setEventRate(engine->sensorEventQueue,
			engine->gyroscopeSensor, (1000L/60)*1000);

	    }
	    engine->animating = 1;
	    break;
	case APP_CMD_LOST_FOCUS:
	    // When our app loses focus, we stop monitoring the sensors.
	    // This is to avoid consuming battery while not being used.
	    if (engine->accelerometerSensor != NULL) {
		ASensorEventQueue_disableSensor(engine->sensorEventQueue,
			engine->accelerometerSensor);
	    }
	    if (engine->magnetometerSensor != NULL) {
		ASensorEventQueue_disableSensor(engine->sensorEventQueue,
			engine->magnetometerSensor);
	    }
	    if (engine->gyroscopeSensor != NULL) {
		ASensorEventQueue_disableSensor(engine->sensorEventQueue,
			engine->gyroscopeSensor);
	    }
	    // Also stop animating.
	    engine->animating = 0;
	    engine_draw_frame(engine);
	    break;
    }
}
static Error _parse_obj(const String &p_path, List<Ref<Mesh> > &r_meshes, bool p_single_mesh, bool p_generate_tangents, Vector3 p_scale_mesh, List<String> *r_missing_deps) {

	FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);

	ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

	Ref<ArrayMesh> mesh;
	mesh.instance();

	bool generate_tangents = p_generate_tangents;
	Vector3 scale_mesh = p_scale_mesh;
	bool flip_faces = false;
	//bool flip_faces = p_options["force/flip_faces"];
	//bool force_smooth = p_options["force/smooth_shading"];
	//bool weld_vertices = p_options["force/weld_vertices"];
	//float weld_tolerance = p_options["force/weld_tolerance"];

	Vector<Vector3> vertices;
	Vector<Vector3> normals;
	Vector<Vector2> uvs;
	String name;

	Map<String, Map<String, Ref<SpatialMaterial> > > material_map;

	Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
	surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);

	String current_material_library;
	String current_material;
	String current_group;

	while (true) {

		String l = f->get_line().strip_edges();

		if (l.begins_with("v ")) {
			//vertex
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
			Vector3 vtx;
			vtx.x = v[1].to_float() * scale_mesh.x;
			vtx.y = v[2].to_float() * scale_mesh.y;
			vtx.z = v[3].to_float() * scale_mesh.z;
			vertices.push_back(vtx);
		} else if (l.begins_with("vt ")) {
			//uv
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT);
			Vector2 uv;
			uv.x = v[1].to_float();
			uv.y = 1.0 - v[2].to_float();
			uvs.push_back(uv);

		} else if (l.begins_with("vn ")) {
			//normal
			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
			Vector3 nrm;
			nrm.x = v[1].to_float();
			nrm.y = v[2].to_float();
			nrm.z = v[3].to_float();
			normals.push_back(nrm);
		} else if (l.begins_with("f ")) {
			//vertex

			Vector<String> v = l.split(" ", false);
			ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);

			//not very fast, could be sped up

			Vector<String> face[3];
			face[0] = v[1].split("/");
			face[1] = v[2].split("/");
			ERR_FAIL_COND_V(face[0].size() == 0, ERR_FILE_CORRUPT);
			ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT);
			for (int i = 2; i < v.size() - 1; i++) {

				face[2] = v[i + 1].split("/");
				ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT);
				for (int j = 0; j < 3; j++) {

					int idx = j;

					if (!flip_faces && idx < 2) {
						idx = 1 ^ idx;
					}

					if (face[idx].size() == 3) {
						int norm = face[idx][2].to_int() - 1;
						if (norm < 0)
							norm += normals.size() + 1;
						ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT);
						surf_tool->add_normal(normals[norm]);
					}

					if (face[idx].size() >= 2 && face[idx][1] != String()) {
						int uv = face[idx][1].to_int() - 1;
						if (uv < 0)
							uv += uvs.size() + 1;
						ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT);
						surf_tool->add_uv(uvs[uv]);
					}

					int vtx = face[idx][0].to_int() - 1;
					if (vtx < 0)
						vtx += vertices.size() + 1;
					ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT);

					Vector3 vertex = vertices[vtx];
					//if (weld_vertices)
					//	vertex.snap(Vector3(weld_tolerance, weld_tolerance, weld_tolerance));
					surf_tool->add_vertex(vertex);
				}

				face[1] = face[2];
			}
		} else if (l.begins_with("s ")) { //smoothing
			String what = l.substr(2, l.length()).strip_edges();
			if (what == "off")
				surf_tool->add_smooth_group(false);
			else
				surf_tool->add_smooth_group(true);
		} else if (/*l.begins_with("g ") ||*/ l.begins_with("usemtl ") || (l.begins_with("o ") || f->eof_reached())) { //commit group to mesh
			//groups are too annoying
			if (surf_tool->get_vertex_array().size()) {
				//another group going on, commit it
				if (normals.size() == 0) {
					surf_tool->generate_normals();
				}

				if (generate_tangents && uvs.size()) {
					surf_tool->generate_tangents();
				}

				surf_tool->index();

				print_line("current material library " + current_material_library + " has " + itos(material_map.has(current_material_library)));
				print_line("current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material)));

				if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) {
					surf_tool->set_material(material_map[current_material_library][current_material]);
				}

				mesh = surf_tool->commit(mesh);

				if (current_material != String()) {
					mesh->surface_set_name(mesh->get_surface_count() - 1, current_material.get_basename());
				} else if (current_group != String()) {
					mesh->surface_set_name(mesh->get_surface_count() - 1, current_group);
				}

				print_line("Added surface :" + mesh->surface_get_name(mesh->get_surface_count() - 1));
				surf_tool->clear();
				surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
			}

			if (l.begins_with("o ") || f->eof_reached()) {

				if (!p_single_mesh) {
					mesh->set_name(name);
					r_meshes.push_back(mesh);
					mesh.instance();
					current_group = "";
					current_material = "";
				}
			}

			if (f->eof_reached()) {
				break;
			}

			if (l.begins_with("o ")) {
				name = l.substr(2, l.length()).strip_edges();
			}

			if (l.begins_with("usemtl ")) {

				current_material = l.replace("usemtl", "").strip_edges();
			}

			if (l.begins_with("g ")) {

				current_group = l.substr(2, l.length()).strip_edges();
			}

		} else if (l.begins_with("mtllib ")) { //parse material

			current_material_library = l.replace("mtllib", "").strip_edges();
			if (!material_map.has(current_material_library)) {
				Map<String, Ref<SpatialMaterial> > lib;
				Error err = _parse_material_library(current_material_library, lib, r_missing_deps);
				if (err == ERR_CANT_OPEN) {
					String dir = p_path.get_base_dir();
					err = _parse_material_library(dir.plus_file(current_material_library), lib, r_missing_deps);
				}
				if (err == OK) {
					material_map[current_material_library] = lib;
				}
			}
		}
	}

	if (p_single_mesh) {

		r_meshes.push_back(mesh);
	}

	return OK;
}
bool PluginPackage::fetchInfo()
{
    DWORD versionInfoSize, zeroHandle;
    versionInfoSize = GetFileVersionInfoSizeW(const_cast<UChar*>(m_path.charactersWithNullTermination()), &zeroHandle);
    if (versionInfoSize == 0)
        return false;

    OwnArrayPtr<char> versionInfoData(new char[versionInfoSize]);

    if (!GetFileVersionInfoW(const_cast<UChar*>(m_path.charactersWithNullTermination()),
            0, versionInfoSize, versionInfoData.get()))
        return false;

    m_name = getVersionInfo(versionInfoData.get(), "ProductName");
    m_description = getVersionInfo(versionInfoData.get(), "FileDescription");
    if (m_name.isNull() || m_description.isNull())
        return false;

    VS_FIXEDFILEINFO* info;
    UINT infoSize;
    if (!VerQueryValue(versionInfoData.get(), TEXT("\\"), (LPVOID*) &info, &infoSize) || infoSize < sizeof(VS_FIXEDFILEINFO))
        return false;
    m_moduleVersion.leastSig = info->dwFileVersionLS;
    m_moduleVersion.mostSig = info->dwFileVersionMS;

    if (isPluginBlacklisted())
        return false;

    Vector<String> types;
    getVersionInfo(versionInfoData.get(), "MIMEType").split('|', types);
    Vector<String> extensionLists;
    getVersionInfo(versionInfoData.get(), "FileExtents").split('|', extensionLists);
    Vector<String> descriptions;
    getVersionInfo(versionInfoData.get(), "FileOpenName").split('|', descriptions);

    for (unsigned i = 0; i < types.size(); i++) {
        String type = types[i].lower();
        String description = i < descriptions.size() ? descriptions[i] : "";
        String extensionList = i < extensionLists.size() ? extensionLists[i] : "";

        Vector<String> extensionsVector;
        extensionList.split(',', extensionsVector);

        // Get rid of the extension list that may be at the end of the description string.
        int pos = description.find("(*");
        if (pos != -1) {
            // There might be a space that we need to get rid of.
            if (pos > 1 && description[pos - 1] == ' ')
                pos--;
            description = description.left(pos);
        }

        // Determine the quirks for the MIME types this plug-in supports
        determineQuirks(type);

        m_mimeToExtensions.add(type, extensionsVector);
        m_mimeToDescriptions.add(type, description);
    }

    return true;
}
Example #25
0
	void UvaErdo() {
		int scenarios, papers = 0, names = 0;
		int scenario;

		Scanner *scanIn = new Scanner();
		String s = scanIn->nextLine();
		scenarios = Integer->parseInt(s->trim());
		for (scenario = 1; scenario <= scenarios; scenario++) {
			printf("Scenario %d\n", scenario);

			String nextLine = scanIn->nextLine();
			String s2[] = nextLine->split(" ");
			int i = 0;
			for (; s2[i] != null; i++) {
				try {
					papers = Integer.parseInt(s2[i].trim());
					#ifdef DEBUG
						printf("\tConverted '%s' to %d\n", s2[i].trim(), papers);
					#endif
					break;
				} catch (NumberFormatException e) {
				}
			}
			i++;
			for (; i < s2.length; i++) {
				try {
					names = Integer.parseInt(s2[i].trim());
					#ifdef DEBUG
						printf("\tConverted '%s' to %d\n", s2[i].trim(), names);
					#endif
					break;
				} catch (NumberFormatException e) {
				}
			}
			#ifdef DEBUG
				printf("\tConverted '%s' to %d papers and %d names\n", nextLine, papers,
						names);
			#endif

			readPapers(papers, scanIn);

			#ifdef DEBUG
				printf("Scenario %d\n", scenario);
			#endif

			List<Entry<String, Author>> theMap = new ArrayList<Map.Entry<String, Author>>(names);
			Set<Author> targets = new TreeSet<Author>();

			readCases(names, scanIn, theMap, targets);

			if (Author.erdosPtr != null) {
				Author.erdosPtr.process(targets);
				#ifdef DEBUG
					printf("Author::erdosPtr not null\n");
				#endif
			}

			for (Entry<String, Author> it : theMap) {
				Author a = it.getValue();
				String bigname = it.getKey();
				if (a == null) {
					printf("%s infinity\n", bigname);
				} else {
					int d = a.depht;
					if (d <= 0 && Author.erdosPtr != a) {
						printf("%s, %s infinity\n", a.lname, a.fname);
					} else {
						printf("%s, %s %d\n", a.lname, a.fname, d);
					}
				}
			}

			theMap.clear();
			Author.freeMemory();
		}
	}
Example #26
0
  void MzTabModificationList::fromCellString(const String& s)
  {
    String lower = s;
    lower.toLower().trim();
    if (lower == "null")
    {
      setNull(true);
    }
    else
    {
      String ss = s;
      std::vector<String> fields;

      if (!ss.hasSubstring("[")) // no parameters
      {
        ss.split(",", fields);
        for (Size i = 0; i != fields.size(); ++i)
        {
          MzTabModification ms;
          ms.fromCellString(fields[i]);
          entries_.push_back(ms);
        }
      }
      else
      {
        // example string: 3|4[a,b,,v]|8[,,"blabla, [bla]",v],1|2|3[a,b,,v]-mod:123
        // we don't want to split at the , inside of [ ]  MzTabParameter brackets.
        // Additionally,  and we don't want to recognise quoted brackets inside the MzTabParameter where they can occur in quoted text (see example string)
        bool in_param_bracket = false;
        bool in_quotes = false;

        for (Size pos = 0; pos != ss.size(); ++pos)
        {
          // param_bracket state
          if (ss[pos] == '[' && !in_quotes)
          {
            in_param_bracket = true;
            continue;
          }

          if (ss[pos] == ']' && !in_quotes)
          {
            in_param_bracket = false;
            continue;
          }

          // quote state
          if (ss[pos] == '\"')
          {
            in_quotes = !in_quotes;
            continue;
          }

          // comma in param bracket
          if (ss[pos] == ',' && !in_quotes && in_param_bracket)
          {
            ss[pos] = ((char)007); // use ASCII bell as temporary separator
            continue;
          }
        }

        // now the split at comma is save
        ss.split(",", fields);

        for (Size i = 0; i != fields.size(); ++i)
        {
          fields[i].substitute(((char)007), ','); // resubstitute comma after split
          MzTabModification ms;
          ms.fromCellString(fields[i]);
          entries_.push_back(ms);
        }
      }
    }
  }
Example #27
0
Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phase) {

	RID_OwnerBase::init_rid();

	OS::get_singleton()->initialize_core();
	ObjectTypeDB::init();

	MAIN_PRINT("Main: Initialize CORE");

	register_core_types();
	register_core_driver_types();

	MAIN_PRINT("Main: Initialize Globals");


	Thread::_main_thread_id = Thread::get_caller_ID();

	globals = memnew( Globals );
	input_map = memnew( InputMap );


	path_remap = memnew( PathRemap );
	translation_server = memnew( TranslationServer );
	performance = memnew( Performance );
	globals->add_singleton(Globals::Singleton("Performance",performance));

	MAIN_PRINT("Main: Parse CMDLine");

	/* argument parsing and main creation */
	List<String> args;
	List<String> main_args;
	
	for(int i=0;i<argc;i++) {

		args.push_back(String::utf8(argv[i]));
	}

	List<String>::Element *I=args.front();

	I=args.front();

	while (I) {

		I->get()=unescape_cmdline(I->get().strip_escapes());
//		print_line("CMD: "+I->get());
		I=I->next();
	}

	I=args.front();
	
	video_mode = OS::get_singleton()->get_default_video_mode();

	String video_driver="";
	String audio_driver="";
	String game_path=".";
	String debug_mode;
	String debug_host;
	String main_pack;
	bool quiet_stdout=false;
	int rtm=-1;

	String remotefs;
	String remotefs_pass;

	String screen = "";

	List<String> pack_list;
	Vector<String> breakpoints;
	bool use_custom_res=true;
	bool force_res=false;

	I=args.front();

	packed_data = PackedData::get_singleton();
	if (!packed_data)
		packed_data = memnew(PackedData);

#ifdef MINIZIP_ENABLED
	
	//XXX: always get_singleton() == 0x0
	zip_packed_data = ZipArchive::get_singleton();
	//TODO: remove this temporary fix
	if (!zip_packed_data) {
		zip_packed_data = memnew(ZipArchive);
	}

	packed_data->add_pack_source(zip_packed_data);
#endif

	bool editor=false;

	while(I) {

		List<String>::Element *N=I->next();

		if (I->get() == "-noop") {

			// no op
		} else if (I->get()=="-h" || I->get()=="--help" || I->get()=="/?") { // resolution
			
			goto error;
			
			
		} else if (I->get()=="-r") { // resolution
		
			if (I->next()) {
			
				String vm=I->next()->get();
				
				if (vm.find("x")==-1) { // invalid parameter format
				
					goto error;
					
				
				}
				
				int w=vm.get_slice("x",0).to_int();
				int h=vm.get_slice("x",1).to_int();
				
				if (w==0 || h==0) {
				
					goto error;
					
				}
				
				video_mode.width=w;
				video_mode.height=h;
				force_res=true;
				
				N=I->next()->next();
			} else {
				goto error;
				
			
			}
		} else if (I->get()=="-p") { // position

			if (I->next()) {

				String vm=I->next()->get();

				if (vm.find("x")==-1) { // invalid parameter format

					goto error;


				}

				int x=vm.get_slice("x",0).to_int();
				int y=vm.get_slice("x",1).to_int();

				init_custom_pos=Point2(x,y);
				init_use_custom_pos=true;
				force_res=true;

				N=I->next()->next();
			} else {
				goto error;


			}


		} else if (I->get()=="-mx") { // video driver

			init_maximized=true;
		} else if (I->get()=="-vd") { // video driver
		
			if (I->next()) {
			
				video_driver=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;
				
			}
		} else if (I->get()=="-lang") { // language

			if (I->next()) {

				locale=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;

			}
		} else if (I->get()=="-rfs") { // language

			if (I->next()) {

				remotefs=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;

			}
		} else if (I->get()=="-rfs_pass") { // language

			if (I->next()) {

				remotefs_pass=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;

			}
		} else if (I->get()=="-rthread") { // language

			if (I->next()) {

				if (I->next()->get()=="safe")
					rtm=OS::RENDER_THREAD_SAFE;
				else if (I->next()->get()=="unsafe")
					rtm=OS::RENDER_THREAD_UNSAFE;
				else if (I->next()->get()=="separate")
					rtm=OS::RENDER_SEPARATE_THREAD;


				N=I->next()->next();
			} else {
				goto error;

			}

		} else if (I->get()=="-ad") { // video driver
		
			if (I->next()) {
			
				audio_driver=I->next()->get();
				N=I->next()->next();
			} else {
				goto error;
				
			}
			
		} else if (I->get()=="-f") { // fullscreen
		
			//video_mode.fullscreen=false;
			init_fullscreen=true;
		} else if (I->get()=="-e" || I->get()=="-editor") { // fonud editor

			editor=true;
			init_maximized=true;
		} else if (I->get()=="-nowindow") { // fullscreen

			OS::get_singleton()->set_no_window_mode(true);
		} else if (I->get()=="-quiet") { // fullscreen

			quiet_stdout=true;
		} else if (I->get()=="-v") { // fullscreen
			OS::get_singleton()->_verbose_stdout=true;
		} else if (I->get()=="-path") { // resolution
		
			if (I->next()) {
			
				String p = I->next()->get();
				if (OS::get_singleton()->set_cwd(p)==OK) {
					//nothing
				} else {
					game_path=I->next()->get(); //use game_path instead
				}

				N=I->next()->next();
			} else {
				goto error;
				
			}
		} else if (I->get()=="-bp") { // /breakpoints

			if (I->next()) {

				String bplist = I->next()->get();
				breakpoints= bplist.split(",");
				N=I->next()->next();
			} else {
				goto error;

			}


		} else if (I->get()=="-fdelay") { // resolution

			if (I->next()) {

				OS::get_singleton()->set_frame_delay(I->next()->get().to_int());
				N=I->next()->next();
			} else {
				goto error;

			}

		} else if (I->get()=="-timescale") { // resolution

			if (I->next()) {

				OS::get_singleton()->set_time_scale(I->next()->get().to_double());
				N=I->next()->next();
			} else {
				goto error;

			}


		} else if (I->get() == "-pack") {

			if (I->next()) {

				pack_list.push_back(I->next()->get());
				N = I->next()->next();
			} else {

				goto error;
			};

		} else if (I->get() == "-main_pack") {

			if (I->next()) {

				main_pack=I->next()->get();
				N = I->next()->next();
			} else {

				goto error;
			};

		} else if (I->get()=="-debug" || I->get()=="-d") {
			debug_mode="local";
		} else if (I->get()=="-editor_scene") {

			if (I->next()) {

				Globals::get_singleton()->set("editor_scene",game_path=I->next()->get());
			} else {
				goto error;

			}

		} else if (I->get()=="-rdebug") {
			if (I->next()) {

				debug_mode="remote";
				debug_host=I->next()->get();
				if (debug_host.find(":")==-1) //wrong host
					goto error;
				N=I->next()->next();
			} else {
				goto error;

			}
		} else {

			//test for game path
			bool gpfound=false;

			if (!I->get().begins_with("-") && game_path=="") {
				DirAccess* da = DirAccess::open(I->get());
				if (da!=NULL) {
					game_path=I->get();
					gpfound=true;
					memdelete(da);
				}

			}

			if (!gpfound) {
				main_args.push_back(I->get());
			}
		}
			
		I=N;
	}


	GLOBAL_DEF("debug/max_remote_stdout_chars_per_second",2048);
	if (debug_mode == "remote") {

		ScriptDebuggerRemote *sdr = memnew( ScriptDebuggerRemote );
		uint16_t debug_port = GLOBAL_DEF("debug/remote_port",6007);
		if (debug_host.find(":")!=-1) {
		    debug_port=debug_host.get_slicec(':',1).to_int();
		    debug_host=debug_host.get_slicec(':',0);
		}
		Error derr = sdr->connect_to_host(debug_host,debug_port);

		if (derr!=OK) {
			memdelete(sdr);
		} else {
			script_debugger=sdr;

		}
	} else if (debug_mode=="local") {

		script_debugger = memnew( ScriptDebuggerLocal );
	}


	if (remotefs!="") {

		file_access_network_client=memnew(FileAccessNetworkClient);
		int port;
		if (remotefs.find(":")!=-1) {
			port=remotefs.get_slicec(':',1).to_int();
			remotefs=remotefs.get_slicec(':',0);
		} else {
			port=6010;
		}

		Error err = file_access_network_client->connect(remotefs,port,remotefs_pass);
		if (err) {
			OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n",remotefs.utf8().get_data(),port);
			goto error;
		}

		FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
	}
	if (script_debugger) {
		//there is a debugger, parse breakpoints

		for(int i=0;i<breakpoints.size();i++) {

			String bp = breakpoints[i];
			int sp=bp.find_last(":");
			if (sp==-1) {
				ERR_EXPLAIN("Invalid breakpoint: '"+bp+"', expected file:line format.");
				ERR_CONTINUE(sp==-1);
			}

			script_debugger->insert_breakpoint(bp.substr(sp+1,bp.length()).to_int(),bp.substr(0,sp));
		}
	}


#ifdef TOOLS_ENABLED
	if (editor) {
		packed_data->set_disabled(true);
		globals->set_disable_platform_override(true);
	}

#endif


	if (globals->setup(game_path,main_pack)!=OK) {
		
#ifdef TOOLS_ENABLED
		editor=false;
#else
		OS::get_singleton()->print("error: Couldn't load game path '%s'\n",game_path.ascii().get_data());

		goto error;
#endif
	}

	if (editor) {
		main_args.push_back("-editor");
		use_custom_res=false;
	}

	if (bool(Globals::get_singleton()->get("application/disable_stdout"))) {
		quiet_stdout=true;
	}
	if (bool(Globals::get_singleton()->get("application/disable_stderr"))) {
		_print_error_enabled = false;
	};

	if (quiet_stdout)
		_print_line_enabled=false;

	OS::get_singleton()->set_cmdline(execpath, main_args);

#ifdef TOOLS_ENABLED

	if (main_args.size()==0 && (!Globals::get_singleton()->has("application/main_loop_type")) && (!Globals::get_singleton()->has("application/main_scene") || String(Globals::get_singleton()->get("application/main_scene"))==""))
		use_custom_res=false; //project manager (run without arguments)

#endif

	input_map->load_from_globals();

	if (video_driver=="") // specified in engine.cfg
		video_driver=_GLOBAL_DEF("display/driver",Variant((const char*)OS::get_singleton()->get_video_driver_name(0)));

	if (!force_res && use_custom_res && globals->has("display/width"))
		video_mode.width=globals->get("display/width");
	if (!force_res &&use_custom_res && globals->has("display/height"))
		video_mode.height=globals->get("display/height");
	if (use_custom_res && globals->has("display/fullscreen"))
		video_mode.fullscreen=globals->get("display/fullscreen");
	if (use_custom_res && globals->has("display/resizable"))
		video_mode.resizable=globals->get("display/resizable");

	if (!force_res && use_custom_res && globals->has("display/test_width") && globals->has("display/test_height")) {
		int tw = globals->get("display/test_width");
		int th = globals->get("display/test_height");
		if (tw>0 && th>0) {
			video_mode.width=tw;
			video_mode.height=th;
		}
	}


	GLOBAL_DEF("display/width",video_mode.width);
	GLOBAL_DEF("display/height",video_mode.height);
	GLOBAL_DEF("display/fullscreen",video_mode.fullscreen);
	GLOBAL_DEF("display/resizable",video_mode.resizable);
	GLOBAL_DEF("display/test_width",0);
	GLOBAL_DEF("display/test_height",0);
	if (rtm==-1) {
		rtm=GLOBAL_DEF("render/thread_model",OS::RENDER_THREAD_SAFE);
		if (rtm>=1) //hack for now
			rtm=1;

	}

	if (rtm>=0 && rtm<3)
		OS::get_singleton()->_render_thread_mode=OS::RenderThreadMode(rtm);



	/* Determine Video Driver */

	if (audio_driver=="") // specified in engine.cfg
		audio_driver=GLOBAL_DEF("audio/driver",OS::get_singleton()->get_audio_driver_name(0));
		
	
	for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {

		if (video_driver==OS::get_singleton()->get_video_driver_name(i)) {
		
			video_driver_idx=i;
			break;
		}
	}

	if (video_driver_idx<0) {
	
		OS::get_singleton()->alert( "Invalid Video Driver: "+video_driver );
		video_driver_idx = 0;
		//goto error;
	}

	for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
	
		if (audio_driver==OS::get_singleton()->get_audio_driver_name(i)) {
		
			audio_driver_idx=i;
			break;
		}
	}

	if (audio_driver_idx<0) {
	
		OS::get_singleton()->alert( "Invalid Audio Driver: "+audio_driver );
		goto error;
	}

	{
		String orientation = GLOBAL_DEF("display/orientation","landscape");

		if (orientation=="portrait")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
		else if (orientation=="reverse_landscape")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
		else if (orientation=="reverse_portrait")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
		else if (orientation=="sensor_landscape")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
		else if (orientation=="sensor_portrait")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
		else if (orientation=="sensor")
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
		else
			OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
	}

	OS::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/fixed_fps",60));
	OS::get_singleton()->set_target_fps(GLOBAL_DEF("application/target_fps",0));

	if (!OS::get_singleton()->_verbose_stdout) //overrided
		OS::get_singleton()->_verbose_stdout=GLOBAL_DEF("debug/verbose_stdout",false);

	message_queue = memnew( MessageQueue );

	Globals::get_singleton()->register_global_defaults();

	if (p_second_phase)
		return setup2();

	return OK;

	error:
	
	video_driver="";	
	audio_driver="";
	game_path="";
		
	args.clear(); 
	main_args.clear();
	
	print_help(execpath);
	

	if (performance)
		memdelete(performance);
	if (input_map)
		memdelete(input_map);
	if (translation_server)
		memdelete( translation_server );
	if (globals)
		memdelete(globals);
	if (script_debugger)
		memdelete(script_debugger);
	if (packed_data)
		memdelete(packed_data);
	if (file_access_network_client)
		memdelete(file_access_network_client);

// Note 1: *zip_packed_data live into *packed_data
// Note 2: PackedData::~PackedData destroy this.
//#ifdef MINIZIP_ENABLED
//	if (zip_packed_data)
//		memdelete( zip_packed_data );
//#endif


	unregister_core_types();
	
	OS::get_singleton()->_cmdline.clear();

	if (message_queue)
		memdelete( message_queue);
	OS::get_singleton()->finalize_core();
	locale=String();
	
	return ERR_INVALID_PARAMETER;
}
Example #28
0
bool EditorFileSystem::_find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const {
	//todo make faster

	if (!filesystem || scanning)
		return false;

	String f = ProjectSettings::get_singleton()->localize_path(p_file);

	if (!f.begins_with("res://"))
		return false;
	f = f.substr(6, f.length());
	f = f.replace("\\", "/");

	Vector<String> path = f.split("/");

	if (path.size() == 0)
		return false;
	String file = path[path.size() - 1];
	path.resize(path.size() - 1);

	EditorFileSystemDirectory *fs = filesystem;

	for (int i = 0; i < path.size(); i++) {

		if (path[i].begins_with("."))
			return false;

		int idx = -1;
		for (int j = 0; j < fs->get_subdir_count(); j++) {

			if (fs->get_subdir(j)->get_name() == path[i]) {
				idx = j;
				break;
			}
		}

		if (idx == -1) {
			//does not exist, create i guess?
			EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory);

			efsd->name = path[i];
			efsd->parent = fs;

			int idx2 = 0;
			for (int j = 0; j < fs->get_subdir_count(); j++) {

				if (efsd->name < fs->get_subdir(j)->get_name())
					break;
				idx2++;
			}

			if (idx2 == fs->get_subdir_count())
				fs->subdirs.push_back(efsd);
			else
				fs->subdirs.insert(idx2, efsd);
			fs = efsd;
		} else {

			fs = fs->get_subdir(idx);
		}
	}

	int cpos = -1;
	for (int i = 0; i < fs->files.size(); i++) {

		if (fs->files[i]->file == file) {
			cpos = i;
			break;
		}
	}

	r_file_pos = cpos;
	*r_d = fs;

	if (cpos != -1) {

		return true;
	} else {

		return false;
	}
}
Example #29
0
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) {

	enum Status {

		STATUS_NONE,
		STATUS_READING_ID,
		STATUS_READING_STRING,
	};

	Status status = STATUS_NONE;

	String msg_id;
	String msg_str;
	String config;

	if (r_error)
		*r_error = ERR_FILE_CORRUPT;

	Ref<Translation> translation = Ref<Translation>(memnew(Translation));
	int line = 1;
	bool skip_this;
	bool skip_next;

	while (true) {

		String l = f->get_line();

		if (f->eof_reached()) {

			if (status == STATUS_READING_STRING) {

				if (msg_id != "") {
					if (!skip_this)
						translation->add_message(msg_id, msg_str);
				} else if (config == "")
					config = msg_str;
				break;

			} else if (status == STATUS_NONE)
				break;

			memdelete(f);
			ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
			ERR_FAIL_V(RES());
		}

		l = l.strip_edges();

		if (l.begins_with("msgid")) {

			if (status == STATUS_READING_ID) {

				memdelete(f);
				ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
				ERR_FAIL_V(RES());
			}

			if (msg_id != "") {
				if (!skip_this)
					translation->add_message(msg_id, msg_str);
			} else if (config == "")
				config = msg_str;

			l = l.substr(5, l.length()).strip_edges();
			status = STATUS_READING_ID;
			msg_id = "";
			msg_str = "";
			skip_this = skip_next;
			skip_next = false;
		}

		if (l.begins_with("msgstr")) {

			if (status != STATUS_READING_ID) {

				memdelete(f);
				ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
				ERR_FAIL_V(RES());
			}

			l = l.substr(6, l.length()).strip_edges();
			status = STATUS_READING_STRING;
		}

		if (l == "" || l.begins_with("#")) {
			if (l.find("fuzzy") != -1) {
				skip_next = true;
			}
			line++;
			continue; //nothing to read or comment
		}

		if (!l.begins_with("\"") || status == STATUS_NONE) {
			//not a string? failure!
			ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
			ERR_FAIL_V(RES());
		}

		l = l.substr(1, l.length());
		//find final quote
		int end_pos = -1;
		for (int i = 0; i < l.length(); i++) {

			if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) {
				end_pos = i;
				break;
			}
		}

		if (end_pos == -1) {
			ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
			ERR_FAIL_V(RES());
		}

		l = l.substr(0, end_pos);
		l = l.c_unescape();

		if (status == STATUS_READING_ID)
			msg_id += l;
		else
			msg_str += l;

		line++;
	}

	f->close();
	memdelete(f);

	if (config == "") {
		ERR_EXPLAIN("No config found in file: " + p_path);
		ERR_FAIL_V(RES());
	}

	Vector<String> configs = config.split("\n");
	for (int i = 0; i < configs.size(); i++) {

		String c = configs[i].strip_edges();
		int p = c.find(":");
		if (p == -1)
			continue;
		String prop = c.substr(0, p).strip_edges();
		String value = c.substr(p + 1, c.length()).strip_edges();

		if (prop == "X-Language") {
			translation->set_locale(value);
		}
	}

	if (r_error)
		*r_error = OK;

	return translation;
}
Example #30
0
void WebCLProgram::build(const RefPtr<WebCLDeviceList> devices,
                         const String& buildOptions, 
                         PassOwnPtr<WebCLCallback> callback, 
                         ExceptionState& es) {
    cl_int err = 0; 
    cl_device_id cl_device = NULL;
    
    if (m_cl_program == NULL) {
        printf("Error: Invalid program object\n");
        es.throwWebCLException(
                WebCLException::INVALID_PROGRAM,
                WebCLException::invalidProgramMessage);
        return ;
    }

    if (buildOptions.length() > 0) {
        DEFINE_STATIC_LOCAL(AtomicString, buildOptionDashD, 
                ("-D", AtomicString::ConstructFromLiteral));
        DEFINE_STATIC_LOCAL(HashSet<AtomicString>, 
                webCLSupportedBuildOptions, ());
        if (webCLSupportedBuildOptions.isEmpty()) {
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-opt-disable", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-single-precision-constant", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-denorms-are-zero", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-mad-enable", 
                             AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-no-signed-zeros", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-unsafe-math-optimizations", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-finite-math-only", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-cl-fast-relaxed-math", 
                AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-w", AtomicString::ConstructFromLiteral));
            webCLSupportedBuildOptions.add(
                AtomicString("-Werror", AtomicString::ConstructFromLiteral));
        }
      
        Vector<String> webCLBuildOptionsVector;
        buildOptions.split(" ", false /* allowEmptyEntries */, 
          webCLBuildOptionsVector);
      
        for (size_t i = 0; i < webCLBuildOptionsVector.size(); i++) {
            // Every build option must start with a hyphen.
            if (!webCLBuildOptionsVector[i].startsWith("-")) {
                es.throwWebCLException(
                        WebCLException::INVALID_BUILD_OPTIONS,
                        WebCLException::invalidBuildOptionsMessage);
                return;
            }

            if (webCLSupportedBuildOptions.contains(
                AtomicString(webCLBuildOptionsVector[i])))
                continue;
             /* If the token begins with "-D" it can be one of "-D NAME" 
                or "-D name=definition". Currently OpenCL specification does not 
                 state any restriction adding spaces in between.So on encounter 
                 of a token starting with "-D" we skip validation till we reach 
                 next build option. Pushing the validation of "-D" options to 
                 underlying OpenCL. */
            if (webCLBuildOptionsVector[i].startsWith(buildOptionDashD)) {
                size_t j;
                for (j = ++i; j < webCLBuildOptionsVector.size() 
                     && !webCLBuildOptionsVector[j].startsWith("-"); ++j){}
                    i = --j;
                    continue;
                }
            es.throwWebCLException(
                    WebCLException::INVALID_BUILD_OPTIONS,
                    WebCLException::invalidBuildOptionsMessage);
            return;
        }
    }