Beispiel #1
0
void ScenesDock::_thumbnail_done(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata) {

	bool valid=false;

	if (!search_box->is_hidden()) {
		valid=true;
	} else {
		valid=(path==p_path.get_base_dir());
	}

	if (p_preview.is_valid() && valid) {

		Array uarr=p_udata;
		int idx=uarr[0];
		String file=uarr[1];
		if (idx>=files->get_item_count())
			return;
		if (files->get_item_text(idx)!=file)
			return;
		String fpath = files->get_item_metadata(idx);
		if (fpath!=p_path)
			return;
		files->set_item_icon(idx,p_preview);

	}

}
	void popup_import(const String& p_path) {

		popup_centered(Size2(400,400));
		if (p_path!="") {

			Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_path);
			ERR_FAIL_COND(!rimd.is_valid());

			save_path->set_text(p_path.get_base_dir());
			List<String> opts;
			rimd->get_options(&opts);
			for(List<String>::Element *E=opts.front();E;E=E->next()) {

				options->_set(E->get(),rimd->get_option(E->get()));
			}

			String src = "";
			for(int i=0;i<rimd->get_source_count();i++) {
				if (i>0)
					src+=",";
				src+=EditorImportPlugin::expand_source_path(rimd->get_source_path(i));
			}
			import_path->set_text(src);
		}
	}
void EditorSceneImportDialog::popup_import(const String &p_from) {

	popup_centered(Size2(700,500));
	if (p_from!="") {
		Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_from);
		if (rimd.is_null())
			return;

		int flags = rimd->get_option("flags");

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

			int md = scene_flags[i]->get_metadata(0);
			scene_flags[i]->set_checked(0,flags&md);
		}

		texture_options->set_flags(rimd->get_option("texture_flags"));
		texture_options->set_format(EditorTextureImportPlugin::ImageFormat(int(rimd->get_option("texture_format"))));
		texture_options->set_quality(rimd->get_option("texture_quality"));
		animation_options->set_flags(rimd->get_option("animation_flags"));
		script_path->set_text(rimd->get_option("post_import_script"));

		save_path->set_text(p_from.get_base_dir());
		import_path->set_text(EditorImportPlugin::expand_source_path(rimd->get_source_path(0)));

	}
}
Beispiel #4
0
void PluginConfigDialog::config(const String &p_config_path) {
	if (p_config_path.length()) {
		Ref<ConfigFile> cf = memnew(ConfigFile);
		cf->load(p_config_path);

		name_edit->set_text(cf->get_value("plugin", "name", ""));
		subfolder_edit->set_text(p_config_path.get_base_dir().get_basename().get_file());
		desc_edit->set_text(cf->get_value("plugin", "description", ""));
		author_edit->set_text(cf->get_value("plugin", "author", ""));
		version_edit->set_text(cf->get_value("plugin", "version", ""));
		script_edit->set_text(cf->get_value("plugin", "script", ""));

		_edit_mode = true;
		active_edit->hide();
		Object::cast_to<Label>(active_edit->get_parent()->get_child(active_edit->get_index() - 1))->hide();
		subfolder_edit->hide();
		Object::cast_to<Label>(subfolder_edit->get_parent()->get_child(subfolder_edit->get_index() - 1))->hide();
		set_title(TTR("Edit a Plugin"));
	} else {
		_clear_fields();
		_edit_mode = false;
		active_edit->show();
		Object::cast_to<Label>(active_edit->get_parent()->get_child(active_edit->get_index() - 1))->show();
		subfolder_edit->show();
		Object::cast_to<Label>(subfolder_edit->get_parent()->get_child(subfolder_edit->get_index() - 1))->show();
		set_title(TTR("Create a Plugin"));
	}
	get_ok()->set_disabled(!_edit_mode);
	get_ok()->set_text(_edit_mode ? TTR("Update") : TTR("Create"));
}
Beispiel #5
0
void GDMono::metadata_set_api_assembly_invalidated(APIAssembly::Type p_api_type, bool p_invalidated) {

	String section = APIAssembly::to_string(p_api_type);
	String path = _get_api_assembly_metadata_path();

	Ref<ConfigFile> metadata;
	metadata.instance();
	metadata->load(path);

	metadata->set_value(section, "invalidated", p_invalidated);

	String assembly_path = GodotSharpDirs::get_res_assemblies_dir()
								   .plus_file(p_api_type == APIAssembly::API_CORE ?
													  API_ASSEMBLY_NAME ".dll" :
													  EDITOR_API_ASSEMBLY_NAME ".dll");

	ERR_FAIL_COND(!FileAccess::exists(assembly_path));

	uint64_t modified_time = FileAccess::get_modified_time(assembly_path);

	metadata->set_value(section, "invalidated_asm_modified_time", String::num_uint64(modified_time));

	String dir = path.get_base_dir();
	if (!DirAccess::exists(dir)) {
		DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
		ERR_FAIL_COND(!da);
		Error err = da->make_dir_recursive(ProjectSettings::get_singleton()->globalize_path(dir));
		ERR_FAIL_COND(err != OK);
	}

	Error save_err = metadata->save(path);
	ERR_FAIL_COND(save_err != OK);
}
void EditorSceneImportDialog::_choose_script(const String& p_path) {

	String p = Globals::get_singleton()->localize_path(p_path);
	if (!p.is_resource_file())
		p=Globals::get_singleton()->get_resource_path().path_to(p_path.get_base_dir())+p_path.get_file();
	script_path->set_text(p);

}
	void popup_import(const String& p_from) {

		popup_centered(Size2(400,400));

		if (p_from!="") {

			Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_from);
			ERR_FAIL_COND(!rimd.is_valid());
			ERR_FAIL_COND(rimd->get_source_count()!=1);
			_choose_file(EditorImportPlugin::expand_source_path(rimd->get_source_path(0)));
			_choose_save_dir(p_from.get_base_dir());
			String locale = rimd->get_option("locale");
			bool skip_first=rimd->get_option("skip_first");
			bool compressed = rimd->get_option("compress");

			int idx=-1;

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

				String il = TranslationServer::get_all_locales()[items[i]->get_range(1)];
				if (il==locale) {
					idx=i;
					break;
				}
			}

			if (idx!=-1) {
				idx=rimd->get_option("index");
			}

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

				if (i==idx) {

					Vector<String> locs = TranslationServer::get_all_locales();
					for(int j=0;j<locs.size();j++) {
						if (locs[j]==locale) {
							items[i]->set_range(1,j);
						}

					}
					items[i]->set_checked(0,true);
				} else {
					items[i]->set_checked(0,false);

				}
			}

			ignore_first->set_pressed(skip_first);
			compress->set_pressed(compressed);



		}

	}
Beispiel #8
0
	void _file_selected(const String& p_path) {

		String p = p_path;
		if (import_mode) {
			if (p.ends_with("engine.cfg")) {

				p=p.get_base_dir();
			}
		}
		String sp = p.simplify_path();
		project_path->set_text(sp);
		_path_text_changed(p);
	}
Beispiel #9
0
	void _file_selected(const String& p_path) {

		String p = p_path;
		if (mode==MODE_IMPORT) {
			if (p.ends_with("engine.cfg")) {

				p=p.get_base_dir();
			}
		}
		String sp = p.simplify_path();
		project_path->set_text(sp);
		_path_text_changed(p);
		get_ok()->call_deferred("grab_focus");
	}
Beispiel #10
0
void ScenesDock::_thumbnail_done(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata) {

	if (p_preview.is_valid() && path==p_path.get_base_dir()) {

		int idx=p_udata;
		if (idx>=files->get_item_count())
			return;
		String fpath = files->get_item_metadata(idx);
		if (fpath!=p_path)
			return;
		files->set_item_icon(idx,p_preview);

	}

}
Beispiel #11
0
void ScenesDock::open(const String& p_path) {


	String npath;
	String nfile;

	if (p_path.ends_with("/")) {

		if (p_path!="res://")
			npath=p_path.substr(0,p_path.length()-1);
		else
			npath="res://";
	} else {
		nfile=p_path.get_file();
		npath=p_path.get_base_dir();
	}

	path=npath;

	if (tree_mode && nfile=="") {
		_update_tree();
		tree->grab_focus();
		tree->call_deferred("ensure_cursor_is_visible");
		_push_to_history();
		return;
	} else if (tree_mode){
		_update_tree();
		tree->grab_focus();
		tree->ensure_cursor_is_visible();
		_open_pressed();
		current_path->set_text(path);
	} else {
		_update_files(false);
		_push_to_history();
	}

	for(int i=0;i<files->get_item_count();i++) {

		String md = files->get_item_metadata(i);
		if (md==p_path) {
			files->select(i,true);
			files->ensure_current_is_visible();
			break;
		}
	}

}
	void popup_import(const String& p_path) {

		popup_centered(Size2(400, 100)*EDSCALE);
		if (p_path != "") {

			Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_path);
			ERR_FAIL_COND(!rimd.is_valid());

			save_path->set_text(p_path.get_base_dir());

			String src = "";
			for (int i = 0; i<rimd->get_source_count(); i++) {
				if (i>0)
					src += ",";
				src += EditorImportPlugin::expand_source_path(rimd->get_source_path(i));
			}
			import_path->set_text(src);
		}
	}
Beispiel #13
0
void FileSystemDock::_preview_invalidated(const String& p_path) {

	if (p_path.get_base_dir()==path && search_box->get_text()==String() && file_list_vb->is_visible()) {


		for(int i=0;i<files->get_item_count();i++) {

			if (files->get_item_metadata(i)==p_path) {
				//re-request preview
				Array udata;
				udata.resize(2);
				udata[0]=i;
				udata[1]=files->get_item_text(i);
				EditorResourcePreview::get_singleton()->queue_resource_preview(p_path,this,"_thumbnail_done",udata);
				break;
			}
		}
	}
}
void EditorTextureImportDialog::popup_import(const String& p_from) {

	popup_centered(Size2(400,400));
	if (p_from!="") {
		Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(p_from);
		ERR_FAIL_COND(!rimd.is_valid());

		save_path->set_text(p_from.get_base_dir());
		texture_options->set_format(EditorTextureImportPlugin::ImageFormat(int(rimd->get_option("format"))));
		texture_options->set_flags(rimd->get_option("flags"));
		texture_options->set_quality(rimd->get_option("quality"));
		String src = "";
		for(int i=0;i<rimd->get_source_count();i++) {
			if (i>0)
				src+=",";
			src+=EditorImportPlugin::expand_source_path(rimd->get_source_path(i));
		}
		import_path->set_text(src);
	}
}
Error EditorSceneImporterFBXConv::_parse_fbx(State& state,const String& p_path) {

	state.base_path=p_path.get_base_dir();

	if (p_path.to_lower().ends_with("g3dj")) {
		return _parse_json(state,p_path.basename()+".g3dj");
	}

	String tool = EDITOR_DEF("fbxconv/path","");
	ERR_FAIL_COND_V( !FileAccess::exists(tool),ERR_UNCONFIGURED);
	String wine = EDITOR_DEF("fbxconv/use_wine","");

	List<String> args;
	String path=p_path;
	if (wine!="") {
		List<String> wpargs;
		wpargs.push_back("-w");
		wpargs.push_back(p_path);
		String pipe; //winepath to convert to windows path
		int wpres;
		Error wperr = OS::get_singleton()->execute(wine+"path",wpargs,true,NULL,&pipe,&wpres);
		ERR_FAIL_COND_V(wperr!=OK,ERR_CANT_CREATE);
		ERR_FAIL_COND_V(wpres!=0,ERR_CANT_CREATE);
		path=pipe.strip_edges();
		args.push_back(tool);
		tool=wine;
	}

	args.push_back("-o");
	args.push_back(TTR("G3DJ"));
	args.push_back(path);

	int res;
	Error err = OS::get_singleton()->execute(tool,args,true,NULL,NULL,&res);
	ERR_FAIL_COND_V(err!=OK,ERR_CANT_CREATE);
	ERR_FAIL_COND_V(res!=0,ERR_CANT_CREATE);

	return _parse_json(state,p_path.basename()+".g3dj");


}
Beispiel #16
0
void ProjectManager::_files_dropped(StringArray p_files, int p_screen) {
	Set<String> folders_set;
	DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	for (int i = 0; i < p_files.size(); i++) {
		String file = p_files[i];
		folders_set.insert(da->dir_exists(file) ? file : file.get_base_dir());
	}
	memdelete(da);
	if (folders_set.size()>0) {
		StringArray folders;
		for (Set<String>::Element *E=folders_set.front();E;E=E->next()) {
			folders.append(E->get());
		}

		bool confirm = true;
		if (folders.size()==1) {
			DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
			if (dir->change_dir(folders[0])==OK) {
				dir->list_dir_begin();
				String file = dir->get_next();
				while(confirm && file!=String()) {
					if (!da->current_is_dir() && file.ends_with("engine.cfg")) {
						confirm = false;
					}
					file = dir->get_next();
				}
				dir->list_dir_end();
			}
			memdelete(dir);
		}
		if (confirm) {
			multi_scan_ask->get_ok()->disconnect("pressed", this, "_scan_multiple_folders");
			multi_scan_ask->get_ok()->connect("pressed", this, "_scan_multiple_folders", varray(folders));
			multi_scan_ask->set_text(vformat(TTR("You are about the scan %s folders for existing Godot projects. Do you confirm?"), folders.size()));
			multi_scan_ask->popup_centered_minsize();
		} else {
			_scan_multiple_folders(folders);
		}
	}
}
Beispiel #17
0
void PackedData::add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src) {

	bool exists = files.has(path);

	PackedFile pf;
	pf.pack=pkg_path;
	pf.offset=ofs;
	pf.size=size;
	for(int i=0;i<16;i++)
		pf.md5[i]=p_md5[i];
	pf.src = p_src;

	files[path]=pf;

	if (!exists) {
		//search for dir
		String p = path.replace_first("res://","");
		PackedDir *cd=root;

		if (p.find("/")!=-1) { //in a subdir

			Vector<String> ds=p.get_base_dir().split("/");

			for(int j=0;j<ds.size();j++) {

				if (!cd->subdirs.has(ds[j])) {

					PackedDir *pd = memnew( PackedDir );
					pd->name=ds[j];
					pd->parent=cd;
					cd->subdirs[pd->name]=pd;
					cd=pd;
				} else {
					cd=cd->subdirs[ds[j]];
				}
			}
		}
		cd->files.insert(path.get_file());
	}
}
Beispiel #18
0
bool GDScriptLanguage::validate(const String& p_script, int &r_line_error,int &r_col_error,String& r_test_error, const String& p_path,List<String> *r_functions) const {

	GDParser parser;

	Error err = parser.parse(p_script,p_path.get_base_dir(),true);
	if (err) {
		r_line_error=parser.get_error_line();
		r_col_error=parser.get_error_column();
		r_test_error=parser.get_error();
		return false;
	} else {

		const GDParser::Node *root = parser.get_parse_tree();
		ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false);

		const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root);
		Map<int,String> funcs;
		for(int i=0;i<cl->functions.size();i++) {

			funcs[cl->functions[i]->line]=cl->functions[i]->name;
		}

		for(int i=0;i<cl->static_functions.size();i++) {

			funcs[cl->static_functions[i]->line]=cl->static_functions[i]->name;
		}

		for (Map<int,String>::Element *E=funcs.front();E;E=E->next()) {

			r_functions->push_back(E->get()+":"+itos(E->key()));
		}


	}

	return true;
}
Beispiel #19
0
RES ResourceFormatLoaderShader::load(const String &p_path, const String& p_original_path, Error *r_error) {

	if (r_error)
		*r_error=ERR_FILE_CANT_OPEN;

	String fragment_code;
	String vertex_code;
	String light_code;

	int mode=-1;

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


	ERR_EXPLAIN("Unable to open shader file: "+p_path);
	ERR_FAIL_COND_V(err,RES());
	String base_path = p_path.get_base_dir();

	if (r_error)
		*r_error=ERR_FILE_CORRUPT;

	Ref<Shader> shader;//( memnew( Shader ) );

	int line=0;

	while(!f->eof_reached()) {

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

		if (mode<=0) {
			l = l.strip_edges();
			int comment = l.find(";");
			if (comment!=-1)
				l=l.substr(0,comment);
		}

		if (mode<1)
			vertex_code+="\n";
		if (mode<2)
			fragment_code+="\n";

		if (mode < 1 && l=="")
			continue;

		if (l.begins_with("[")) {
			l=l.strip_edges();
			if (l=="[params]") {
				if (mode>=0) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [params] section.");
					ERR_FAIL_V(RES());
				}
				mode=0;
			}  else if (l=="[vertex]") {
				if (mode>=1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [vertex] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			}  else if (l=="[fragment]") {
				if (mode>=2) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [fragment] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
				ERR_FAIL_V(RES());
			}
			continue;
		}

		if (mode==0) {

			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=="true") {
				value = true;
			} else if (right=="false") {
				value = false;
			} else if (right.is_valid_float()) {
				//is number
				value = right.to_double();
			} else if (right.is_valid_html_color()) {
				//is html color
				value = Color::html(right);
			} 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).strip_edges();


				if (type=="tex") {

					if (param=="") {

						value=RID();
					} else {

						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=="vec3") {

					if (param=="") {
						value=Vector3();
					} else {
						Vector<String> params = param.split(",");
						if (params.size()!=3) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for vec3(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Vector3 v;
						for(int i=0;i<3;i++)
							v[i]=params[i].to_double();
						value=v;
					}


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

					if (param=="") {
						value=Transform();
					} else {

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

						}

						Transform t;
						for(int i=0;i<9;i++)
							t.basis[i%3][i/3]=params[i].to_double();
						for(int i=0;i<3;i++)
							t.origin[i]=params[i-9].to_double();

						value=t;
					}

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

				}

			}

			String left= l.substr(0,eqpos);

//			shader->set_param(left,value);
		} else if (mode==1) {

			vertex_code+=l;

		} else if (mode==2) {

			fragment_code+=l;
		}
	}

	shader->set_code(vertex_code,fragment_code,light_code);

	f->close();
	memdelete(f);
	if (r_error)
		*r_error=OK;

	return shader;
}
Error EditorTextureImportPlugin::import2(const String& p_path, const Ref<ResourceImportMetadata>& p_from,EditorExportPlatform::ImageCompression p_compr, bool p_external){



	ERR_FAIL_COND_V(p_from->get_source_count()==0,ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from=p_from;

	Ref<ImageTexture> texture;
	Vector<Ref<AtlasTexture> > atlases;
	bool atlas = from->get_option("atlas");
	bool large = from->get_option("large");

	int flags=from->get_option("flags");
	int format=from->get_option("format");
	float quality=from->get_option("quality");

	uint32_t tex_flags=0;

	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_REPEAT)
		tex_flags|=Texture::FLAG_REPEAT;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_FILTER)
		tex_flags|=Texture::FLAG_FILTER;
	if (!(flags&EditorTextureImportPlugin::IMAGE_FLAG_NO_MIPMAPS))
		tex_flags|=Texture::FLAG_MIPMAPS;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_CONVERT_TO_LINEAR)
		tex_flags|=Texture::FLAG_CONVERT_TO_LINEAR;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_USE_ANISOTROPY)
		tex_flags|=Texture::FLAG_ANISOTROPIC_FILTER;

	print_line("path: "+p_path+" flags: "+itos(tex_flags));
	float shrink=1;
	if (from->has_option("shrink"))
		shrink=from->get_option("shrink");

	if (large) {
		ERR_FAIL_COND_V(from->get_source_count()!=1,ERR_INVALID_PARAMETER);

		String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0));


		int cell_size=from->get_option("large_cell_size");
		ERR_FAIL_COND_V(cell_size<128 || cell_size>16384,ERR_CANT_OPEN);

		EditorProgress pg("ltex","Import Large Texture",3);

		pg.step("Load Source Image",0);
		Image img;
		Error err = ImageLoader::load_image(src_path,&img);
		if (err) {
			return err;
		}

		pg.step("Slicing",1);

		Map<Vector2,Image> pieces;
		for(int i=0;i<img.get_width();i+=cell_size) {
			int w = MIN(img.get_width()-i,cell_size);
			for(int j=0;j<img.get_height();j+=cell_size) {
				int h = MIN(img.get_height()-j,cell_size);

				Image piece(w,h,0,img.get_format());
				piece.blit_rect(img,Rect2(i,j,w,h),Point2(0,0));
				if (!piece.is_invisible()) {
					pieces[Vector2(i,j)]=piece;
					//print_line("ADDING PIECE AT "+Vector2(i,j));
				}
			}
		}

		Ref<LargeTexture> existing;
		if (ResourceCache::has(p_path)) {
			existing = ResourceCache::get(p_path);
		}

		if (existing.is_valid()) {
			existing->clear();
		} else {
			existing = Ref<LargeTexture>(memnew( LargeTexture ));
		}

		existing->set_size(Size2(img.get_width(),img.get_height()));
		pg.step("Inserting",2);

		for (Map<Vector2,Image>::Element *E=pieces.front();E;E=E->next()) {

			Ref<ImageTexture> imgtex = Ref<ImageTexture>( memnew( ImageTexture ) );
			imgtex->create_from_image(E->get(),tex_flags);
			_process_texture_data(imgtex,format,quality,flags,p_compr,tex_flags,shrink);
			existing->add_piece(E->key(),imgtex);
		}

		if (!p_external) {
			from->set_editor(get_name());
			existing->set_path(p_path);
			existing->set_import_metadata(from);
		}
		pg.step("Saving",3);

		err = ResourceSaver::save(p_path,existing);
		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save large texture: "+p_path);
			return err;
		}

		return OK;


	} else if (atlas) {

		//prepare atlas!
		Vector< Image > sources;
		Vector< Image > tsources;
		bool alpha=false;
		bool crop = from->get_option("crop");

		EditorProgress ep("make_atlas","Build Atlas For: "+p_path.get_file(),from->get_source_count()+3);

		print_line("sources: "+itos(from->get_source_count()));

		for(int i=0;i<from->get_source_count();i++) {

			String path = EditorImportPlugin::expand_source_path(from->get_source_path(i));
			String md5 = FileAccess::get_md5(path);
			from->set_source_md5(i,FileAccess::get_md5(path));
			ep.step("Loading Image: "+path,i);
			print_line("source path: "+path+" md5 "+md5);
			Image src;
			Error err = ImageLoader::load_image(path,&src);
			if (err) {
				EditorNode::add_io_error("Couldn't load image: "+path);
				return err;
			}

			if (src.detect_alpha())
				alpha=true;

			tsources.push_back(src);
		}
		ep.step("Converting Images",sources.size());

		int base_index=0;


		Map<uint64_t,int> source_md5;
		Map<int,List<int> > source_map;

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

			Image src = tsources[i];

			if (alpha) {
				src.convert(Image::FORMAT_RGBA);
			} else {
				src.convert(Image::FORMAT_RGB);
			}

			DVector<uint8_t> data = src.get_data();
			MD5_CTX md5;
			DVector<uint8_t>::Read r=data.read();
			MD5Init(&md5);
			int len=data.size();
			for(int j=0;j<len;j++) {
				uint8_t b = r[j];
				b>>=2; //to aid in comparing
				MD5Update(&md5,(unsigned char*)&b,1);
			}
			MD5Final(&md5);
			uint64_t *cmp = (uint64_t*)md5.digest; //less bits, but still useful for this

			tsources[i]=Image(); //clear

			if (source_md5.has(*cmp)) {
				int sidx=source_md5[*cmp];
				source_map[sidx].push_back(i);
				print_line("REUSING "+from->get_source_path(i));

			} else {
				int sidx=sources.size();
				source_md5[*cmp]=sidx;
				sources.push_back(src);
				List<int> sm;
				sm.push_back(i);
				source_map[sidx]=sm;

			}


		}

		//texturepacker is not really good for optimizing, so..
		//will at some point likely replace with my own
		//first, will find the nearest to a square packing
		int border=1;

		Vector<Size2i> src_sizes;
		Vector<Rect2> crops;

		ep.step("Cropping Images",sources.size()+1);

		for(int j=0;j<sources.size();j++) {

			Size2i s;
			if (crop) {
				Rect2 crop = sources[j].get_used_rect();
				print_line("CROP: "+crop);
				s=crop.size;
				crops.push_back(crop);
			} else {

				s=Size2i(sources[j].get_width(),sources[j].get_height());
			}
			s+=Size2i(border*2,border*2);
			src_sizes.push_back(s); //add a line to constraint width
		}

		Vector<Point2i> dst_positions;
		Size2i dst_size;
		EditorAtlas::fit(src_sizes,dst_positions,dst_size);

		print_line("size that workeD: "+itos(dst_size.width)+","+itos(dst_size.height));

		ep.step("Blitting Images",sources.size()+2);

		bool blit_to_po2=tex_flags&Texture::FLAG_MIPMAPS;
		int atlas_w=dst_size.width;
		int atlas_h=dst_size.height;
		if (blit_to_po2) {
			atlas_w=nearest_power_of_2(dst_size.width);
			atlas_h=nearest_power_of_2(dst_size.height);
		}
		Image atlas;
		atlas.create(atlas_w,atlas_h,0,alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB);


		atlases.resize(from->get_source_count());

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

			int x=dst_positions[i].x;
			int y=dst_positions[i].y;

			Size2 sz = Size2(sources[i].get_width(),sources[i].get_height());

			Rect2 region;
			Rect2 margin;

			if (crop && sz!=crops[i].size) {
				Rect2 rect = crops[i];
				rect.size=sz-rect.size;
				region=Rect2(x+border,y+border,crops[i].size.width,crops[i].size.height);
				margin=rect;
				atlas.blit_rect(sources[i],crops[i],Point2(x+border,y+border));
			} else {
				region=Rect2(x+border,y+border,sz.x,sz.y);
				atlas.blit_rect(sources[i],Rect2(0,0,sources[i].get_width(),sources[i].get_height()),Point2(x+border,y+border));
			}

			ERR_CONTINUE( !source_map.has(i) );
			for (List<int>::Element *E=source_map[i].front();E;E=E->next()) {

				String apath = p_path.get_base_dir().plus_file(from->get_source_path(E->get()).get_file().basename()+".atex");

				Ref<AtlasTexture> at;

				if (ResourceCache::has(apath)) {
					at = Ref<AtlasTexture>( ResourceCache::get(apath)->cast_to<AtlasTexture>() );
				} else {

					at = Ref<AtlasTexture>( memnew( AtlasTexture ) );
				}
				at->set_region(region);
				at->set_margin(margin);
				at->set_path(apath);
				atlases[E->get()]=at;
				print_line("Atlas Tex: "+apath);
			}
		}
		if (ResourceCache::has(p_path)) {
			texture = Ref<ImageTexture> ( ResourceCache::get(p_path)->cast_to<ImageTexture>() );
		} else {
			texture = Ref<ImageTexture>( memnew( ImageTexture ) );
		}
		texture->create_from_image(atlas,tex_flags);

	} else {
Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {

	Error err;
	if (p_flags&ResourceSaver::FLAG_COMPRESS) {
		FileAccessCompressed *fac = memnew( FileAccessCompressed );
		fac->configure("RSCC");
		f=fac;
		err = fac->_open(p_path,FileAccess::WRITE);
		if (err)
			memdelete(f);

	} else {
		f=FileAccess::open(p_path,FileAccess::WRITE,&err);
	}


	ERR_FAIL_COND_V(err,err);
	FileAccessRef _fref(f);


	relative_paths=p_flags&ResourceSaver::FLAG_RELATIVE_PATHS;
	skip_editor=p_flags&ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
	bundle_resources=p_flags&ResourceSaver::FLAG_BUNDLE_RESOURCES;
	big_endian=p_flags&ResourceSaver::FLAG_SAVE_BIG_ENDIAN;
	no_extensions=p_flags&ResourceSaver::FLAG_NO_EXTENSION;

	local_path=p_path.get_base_dir();
	//bin_meta_idx = get_string_index("__bin_meta__"); //is often used, so create

	_find_resources(p_resource,true);

	if (!(p_flags&ResourceSaver::FLAG_COMPRESS)) {
		//save header compressed
		static const uint8_t header[4]={'R','S','R','C'};
		f->store_buffer(header,4);
	}

	if (big_endian) {
		f->store_32(1);
		f->set_endian_swap(true);
	} else
		f->store_32(0);

	f->store_32(0); //64 bits file, false for now
	f->store_32(VERSION_MAJOR);
	f->store_32(VERSION_MINOR);
	f->store_32(FORMAT_VERSION);

	//f->store_32(saved_resources.size()+external_resources.size()); // load steps -not needed
	save_unicode_string(p_resource->get_type());
	uint64_t md_at = f->get_pos();
	f->store_64(0); //offset to impoty metadata
	for(int i=0;i<14;i++)
		f->store_32(0); // reserved


	List<ResourceData> resources;


	{


		for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {


			ResourceData &rd = resources.push_back(ResourceData())->get();
			rd.type=E->get()->get_type();

			List<PropertyInfo> property_list;
			E->get()->get_property_list( &property_list );

			for(List<PropertyInfo>::Element *F=property_list.front();F;F=F->next()) {

				if (skip_editor && F->get().name.begins_with("__editor"))
					continue;
				if (F->get().usage&PROPERTY_USAGE_STORAGE || (bundle_resources && F->get().usage&PROPERTY_USAGE_BUNDLE)) {
					Property p;
					p.name_idx=get_string_index(F->get().name);
					p.value=E->get()->get(F->get().name);
					if (F->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero())
						continue;
					p.pi=F->get();										

					rd.properties.push_back(p);

				}
			}



		}
	}


	f->store_32(strings.size()); //string table size
	for(int i=0;i<strings.size();i++) {
		//print_bl("saving string: "+strings[i]);
		save_unicode_string(strings[i]);
	}

	// save external resource table
	f->store_32(external_resources.size()); //amount of external resources
	for(Set<RES>::Element *E=external_resources.front();E;E=E->next()) {

		save_unicode_string(E->get()->get_save_type());
		String path = E->get()->get_path();
		if (no_extensions)
			path=path.basename()+".*";
		save_unicode_string(path);
	}
	// save internal resource table
	f->store_32(saved_resources.size()); //amount of internal resources
	Vector<uint64_t> ofs_pos;
	for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {

		RES r = E->get();
		if (r->get_path()=="" || r->get_path().find("::")!=-1)
			save_unicode_string("local://"+itos(ofs_pos.size()));
		else
			save_unicode_string(r->get_path()); //actual external
		ofs_pos.push_back(f->get_pos());
		f->store_64(0); //offset in 64 bits
	}

	Vector<uint64_t> ofs_table;
//	int saved_idx=0;
	//now actually save the resources

	for(List<ResourceData>::Element *E=resources.front();E;E=E->next()) {

		ResourceData & rd = E->get();

		ofs_table.push_back(f->get_pos());
		save_unicode_string(rd.type);
		f->store_32(rd.properties.size());

		for (List<Property>::Element *F=rd.properties.front();F;F=F->next()) {

			Property &p=F->get();
			f->store_32(p.name_idx);
			write_variant(p.value,F->get().pi);
		}

	}

	for(int i=0;i<ofs_table.size();i++) {
		f->seek(ofs_pos[i]);
		f->store_64(ofs_table[i]);
	}

	f->seek_end();
	if (p_resource->get_import_metadata().is_valid()) {
		uint64_t md_pos = f->get_pos();
		Ref<ResourceImportMetadata> imd=p_resource->get_import_metadata();
		save_unicode_string(imd->get_editor());
		f->store_32(imd->get_source_count());
		for(int i=0;i<imd->get_source_count();i++) {
			save_unicode_string(imd->get_source_path(i));
			save_unicode_string(imd->get_source_md5(i));
		}
		List<String> options;
		imd->get_options(&options);
		f->store_32(options.size());
		for(List<String>::Element *E=options.front();E;E=E->next()) {
			save_unicode_string(E->get());
			write_variant(imd->get_option(E->get()));
		}

		f->seek(md_at);
		f->store_64(md_pos);
		f->seek_end();
	}


	f->store_buffer((const uint8_t*)"RSRC",4); //magic at end

	f->close();


	return OK;
}
Beispiel #22
0
Error EditorOBJImporter::_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();
			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 {
				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 {
				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 {
				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 {
				r_missing_deps->push_back(path);
			}
		} else if (f->eof_reached()) {
			break;
		}
	}

	return OK;
}
Beispiel #23
0
void ScriptCreateDialog::_path_changed(const String &p_path) {

	is_path_valid = false;
	is_new_script_created = true;
	String p = p_path;

	if (p == "") {
		_msg_path_valid(false, TTR("Path is empty"));
		_update_dialog();
		return;
	}

	p = ProjectSettings::get_singleton()->localize_path(p);
	if (!p.begins_with("res://")) {
		_msg_path_valid(false, TTR("Path is not local"));
		_update_dialog();
		return;
	}

	if (p.find("/") || p.find("\\")) {
		DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
		if (d->change_dir(p.get_base_dir()) != OK) {
			_msg_path_valid(false, TTR("Invalid base path"));
			memdelete(d);
			_update_dialog();
			return;
		}
		memdelete(d);
	}

	/* Does file already exist */

	DirAccess *f = DirAccess::create(DirAccess::ACCESS_RESOURCES);
	if (f->dir_exists(p)) {
		is_new_script_created = false;
		is_path_valid = false;
		_msg_path_valid(false, TTR("Directory of the same name exists"));
	} else if (f->file_exists(p)) {
		is_new_script_created = false;
		is_path_valid = true;
		_msg_path_valid(true, TTR("File exists, will be reused"));
	} else {
		path_error_label->set_text("");
	}
	memdelete(f);
	_update_dialog();

	/* Check file extension */

	String extension = p.get_extension();
	List<String> extensions;

	// get all possible extensions for script
	for (int l = 0; l < language_menu->get_item_count(); l++) {
		ScriptServer::get_language(l)->get_recognized_extensions(&extensions);
	}

	bool found = false;
	bool match = false;
	int index = 0;
	for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
		if (E->get().nocasecmp_to(extension) == 0) {
			//FIXME (?) - changing language this way doesn't update controls, needs rework
			//language_menu->select(index); // change Language option by extension
			found = true;
			if (E->get() == ScriptServer::get_language(language_menu->get_selected())->get_extension()) {
				match = true;
			}
			break;
		}
		index++;
	}

	if (!found) {
		_msg_path_valid(false, TTR("Invalid extension"));
		_update_dialog();
		return;
	}

	if (!match) {
		_msg_path_valid(false, TTR("Wrong extension chosen"));
		_update_dialog();
		return;
	}

	/* All checks passed */

	is_path_valid = true;
	_update_dialog();
}
Beispiel #24
0
void ScriptCreateDialog::_path_changed(const String& p_path) {

	path_valid=false;
	String p =p_path;

	if (p=="")	 {

		path_error_label->set_text("Path is Empty");
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		return;

	}

	p = Globals::get_singleton()->localize_path(p);
	if (!p.begins_with("res://")) {

		path_error_label->set_text("Path is not local");
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		return;
	}

	if (p.find("/") || p.find("\\")) {
		DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);

		if (d->change_dir(p.get_base_dir())!=OK) {

			path_error_label->set_text("Base Path Invalid");
			path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
			memdelete(d);
			return;

		}
		memdelete(d);
	}



	FileAccess *f = FileAccess::create(FileAccess::ACCESS_RESOURCES);

	if (f->file_exists(p)) {

		path_error_label->set_text("File Exists");
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		memdelete(f);
		return;
	}

	memdelete(f);

	String extension=p.extension();
	List<String> extensions;

	int l=language_menu->get_selected();
	ScriptServer::get_language( l )->get_recognized_extensions(&extensions);

	bool found=false;
	for(List<String>::Element *E=extensions.front();E;E=E->next()) {
		if (E->get().nocasecmp_to(extension)==0) {
			found=true;
			break;
		}
	}

	if (!found) {

		path_error_label->set_text("Invalid Extension");
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		return;
	}


	path_error_label->set_text("Path is Valid");
	path_error_label->add_color_override("font_color",Color(0,1.0,0.8,0.8));

	path_valid=true;

}
Error EditorSceneImportPlugin::import2(Node *scene, const String& p_dest_path, const Ref<ResourceImportMetadata>& p_from) {

	Error err=OK;
	Ref<ResourceImportMetadata> from=p_from;
	String src_path=EditorImportPlugin::expand_source_path(from->get_source_path(0));
	int animation_flags=p_from->get_option("animation_flags");
	int scene_flags = from->get_option("flags");

	EditorProgress progress("import","Import Scene",104);
	progress.step("Importing Scene..",2);


	bool merge = !bool(from->get_option("reimport"));
	from->set_source_md5(0,FileAccess::get_md5(src_path));
	from->set_editor(get_name());

	from->set_option("reimport",false);
	String target_res_path=p_dest_path.get_base_dir();

	Map<Ref<Mesh>,Ref<Shape> > collision_map;

	Ref<ResourceImportMetadata> imd = memnew(ResourceImportMetadata);

	Set< Ref<ImageTexture> > imagemap;

	scene=_fix_node(scene,scene,collision_map,scene_flags,imagemap);


	/// BEFORE ANYTHING, RUN SCRIPT

	progress.step("Running Custom Script..",2);

	String post_import_script_path = from->get_option("post_import_script");
	Ref<EditorScenePostImport>  post_import_script;

	if (post_import_script_path!="") {
		post_import_script_path = EditorImportPlugin::expand_source_path(post_import_script_path);
		Ref<Script> scr = ResourceLoader::load(post_import_script_path);
		if (!scr.is_valid()) {
			EditorNode::add_io_error("Couldn't load post-import script: '"+post_import_script_path);
		} else {

			post_import_script = Ref<EditorScenePostImport>( memnew( EditorScenePostImport ) );
			post_import_script->set_script(scr.get_ref_ptr());
			if (!post_import_script->get_script_instance()) {
				EditorNode::add_io_error("Invalid/Broken Script for Post-Import: '"+post_import_script_path);
				post_import_script.unref();
			}
		}
	}


	if (post_import_script.is_valid()) {
		err = post_import_script->post_import(scene);
		if (err) {
			EditorNode::add_io_error("Error running Post-Import script: '"+post_import_script_path);
			return err;
		}
	}

	/// IMPORT IMAGES


	int idx=0;

	int image_format = from->get_option("texture_format");
	int image_flags =  from->get_option("texture_flags");
	float image_quality = from->get_option("texture_quality");

	for (Set< Ref<ImageTexture> >::Element *E=imagemap.front();E;E=E->next()) {

		//texture could be converted to something more useful for 3D, that could load individual mipmaps and stuff
		//but not yet..

		Ref<ImageTexture> texture = E->get();

		ERR_CONTINUE(!texture.is_valid());

		String path = texture->get_path();
		String fname= path.get_file();
		String target_path = Globals::get_singleton()->localize_path(target_res_path.plus_file(fname));
		progress.step("Import Img: "+fname,3+(idx)*100/imagemap.size());

		idx++;

		if (path==target_path) {

			EditorNode::add_io_error("Can't import a file over itself: '"+target_path);
			continue;
		}

		if (!target_path.begins_with("res://")) {
			EditorNode::add_io_error("Couldn't localize path: '"+target_path+"' (already local)");
			continue;
		}


		{


			target_path=target_path.basename()+".tex";

			Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata );
			print_line("flags: "+itos(image_flags));
			imd->set_option("flags",image_flags);
			imd->set_option("format",image_format);
			imd->set_option("quality",image_quality);
			imd->set_option("atlas",false);
			imd->add_source(EditorImportPlugin::validate_source_path(path));


			if (FileAccess::exists(target_path)) {

				 Ref<ResourceImportMetadata> rimdex = ResourceLoader::load_import_metadata(target_path);
				 if (rimdex.is_valid()) {
					//make sure the options are the same, otherwise re-import
					List<String> opts;
					imd->get_options(&opts);
					bool differ=false;
					for (List<String>::Element *E=opts.front();E;E=E->next()) {
						if (!(rimdex->get_option(E->get())==imd->get_option(E->get()))) {
							differ=true;
							break;
						}
					}

					if (!differ) {
						texture->set_path(target_path);
						continue; //already imported
					}
				}
			}

			Error err = EditorTextureImportPlugin::get_singleton(EditorTextureImportPlugin::MODE_TEXTURE_3D)->import(target_path,imd);

		}
	}


	/// BEFORE SAVING - MERGE


	if (merge) {

		progress.step("Merging..",103);

		FileAccess *fa = FileAccess::create(FileAccess::ACCESS_FILESYSTEM);
		if (fa->file_exists(p_dest_path)) {

			//try to merge

			Ref<PackedScene> s = ResourceLoader::load(p_dest_path);
			if (s.is_valid()) {

				Node *existing = s->instance(true);

				if (existing) {

					_merge_scenes(scene,existing);

					memdelete(scene);
					scene=existing;
				}
			}

		}

		memdelete(fa);
	}


	progress.step("Saving..",104);

	Ref<PackedScene> packer = memnew( PackedScene );
	packer->pack(scene);
	packer->set_path(p_dest_path);
	packer->set_import_metadata(from);

	print_line("SAVING TO: "+p_dest_path);
	err = ResourceSaver::save(p_dest_path,packer);

	//EditorFileSystem::get_singleton()->update_resource(packer);

	memdelete(scene);
	/*
	scene->set_filename(p_dest_path);
	if (r_scene) {
		*r_scene=scene;
	} else {
		memdelete(scene);
	}

	String sp;
	if (p_post_import.is_valid() && !p_post_import->get_script().is_null()) {
		Ref<Script> scr = p_post_import->get_script();
		if (scr.is_valid())
			sp=scr->get_path();
	}

	String op=_getrelpath(p_path,p_dest_path);

	*/


	return err;

}
Beispiel #26
0
Error Font::create_from_fnt(const String& p_string) {
	//fnt format used by angelcode bmfont
	//http://www.angelcode.com/products/bmfont/

	FileAccess *f = FileAccess::open(p_string,FileAccess::READ);

	if (!f) {
		ERR_EXPLAIN("Can't open font: "+p_string);
		ERR_FAIL_V(ERR_FILE_NOT_FOUND);
	}

	clear();

	while(true) {

		String line=f->get_line();

		int delimiter=line.find(" ");
		String type=line.substr(0,delimiter);
		int pos = delimiter+1;
		Map<String,String> keys;

		while (pos < line.size() && line[pos]==' ')
			pos++;


		while(pos<line.size()) {

			int eq = line.find("=",pos);
			if (eq==-1)
				break;
			String key=line.substr(pos,eq-pos);
			int end=-1;
			String value;
			if (line[eq+1]=='"') {
				end=line.find("\"",eq+2);
				if (end==-1)
					break;
				value=line.substr(eq+2,end-1-eq-1);
				pos=end+1;
			} else {
				end=line.find(" ",eq+1);
				if (end==-1)
					end=line.size();

				value=line.substr(eq+1,end-eq);

				pos=end;

			}

			while (pos<line.size() && line[pos]==' ')
				pos++;


			keys[key]=value;

		}


		if (type=="info") {

			if (keys.has("face"))
				set_name(keys["face"]);
			//if (keys.has("size"))
			//	font->set_height(keys["size"].to_int());

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

			if (keys.has("lineHeight"))
				set_height(keys["lineHeight"].to_int());
			if (keys.has("base"))
				set_ascent(keys["base"].to_int());

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

			if (keys.has("file")) {

				String file = keys["file"];
				file=p_string.get_base_dir()+"/"+file;
				Ref<Texture> tex = ResourceLoader::load(file);
				if (tex.is_null()) {
					ERR_PRINT("Can't load font texture!");
				} else {
					add_texture(tex);
				}
			}
		} else if (type=="char") {

			CharType idx=0;
			if (keys.has("id"))
				idx=keys["id"].to_int();

			Rect2 rect;

			if (keys.has("x"))
				rect.pos.x=keys["x"].to_int();
			if (keys.has("y"))
				rect.pos.y=keys["y"].to_int();
			if (keys.has("width"))
				rect.size.width=keys["width"].to_int();
			if (keys.has("height"))
				rect.size.height=keys["height"].to_int();

			Point2 ofs;

			if (keys.has("xoffset"))
				ofs.x=keys["xoffset"].to_int();
			if (keys.has("yoffset"))
				ofs.y=keys["yoffset"].to_int();

			int texture=0;
			if (keys.has("page"))
				texture=keys["page"].to_int();
			int advance=-1;
			if (keys.has("xadvance"))
				advance=keys["xadvance"].to_int();

			add_char(idx,texture,rect,ofs,advance);

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

			CharType first=0,second=0;
			int k=0;

			if (keys.has("first"))
				first=keys["first"].to_int();
			if (keys.has("second"))
				second=keys["second"].to_int();
			if (keys.has("amount"))
				k=keys["amount"].to_int();

			add_kerning_pair(first,second,-k);

		}

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



	memdelete(f);

	return OK;
}
Beispiel #27
0
Error EditorExportPlatformJavaScript::export_project(const String& p_path,bool p_debug,const String& p_password) {


	String src_template;

	EditorProgress ep("export","Exporting for javascript",104);

	String template_path = EditorSettings::get_singleton()->get_settings_path()+"/templates/";

	if (p_debug) {

		src_template=custom_debug_package!=""?custom_debug_package:template_path+"javascript_debug.zip";
	} else {

		src_template=custom_release_package!=""?custom_release_package:template_path+"javascript_release.zip";

	}


	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Exporting to HTML5",0);

	ep.step("Finding Files..",1);

	FileAccess *f=FileAccess::open(p_path.get_base_dir()+"/data.pck",FileAccess::WRITE);
	if (!f) {
		EditorNode::add_io_error("Could not create file for writing:\n"+p_path.basename()+"_files.js");
		return ERR_FILE_CANT_WRITE;
	}
	Error err = save_pack(f);
	size_t len = f->get_len();
	memdelete(f);
	if (err)
		return err;


	unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template HTML5 to export:\n"+src_template);
		return ERR_FILE_NOT_FOUND;
	}

	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);


	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		if (file=="godot.html") {

			_fix_html(data,p_path.get_file().basename(),1<<(max_memory+5));
			file=p_path.get_file();
		}
		if (file=="filesystem.js") {

			_fix_files(data,len);
			file=p_path.get_file().basename()+"_filesystem.js";
		}
		if (file=="godot.js") {

			//_fix_godot(data);
			file=p_path.get_file().basename()+".js";
		}

		String dst = p_path.get_base_dir().plus_file(file);
		FileAccess *f=FileAccess::open(dst,FileAccess::WRITE);
		if (!f) {
			EditorNode::add_io_error("Could not create file for writing:\n"+dst);
			unzClose(pkg);
			return ERR_FILE_CANT_WRITE;
		}
		f->store_buffer(data.ptr(),data.size());
		memdelete(f);


		ret = unzGoToNextFile(pkg);
	}



	return OK;

}
Beispiel #28
0
Error GDCompiler::_parse_class(GDScript *p_script,GDScript *p_owner,const GDParser::ClassNode *p_class) {


	p_script->native=Ref<GDNativeClass>();
	p_script->base=Ref<GDScript>();
	p_script->_base=NULL;
	p_script->members.clear();
	p_script->constants.clear();
	p_script->member_functions.clear();
	p_script->member_indices.clear();
	p_script->member_info.clear();
	p_script->initializer=NULL;
	p_script->subclasses.clear();
	p_script->_owner=p_owner;
	p_script->tool=p_class->tool;
	p_script->name=p_class->name;


	int index_from=0;

	if (p_class->extends_used) {
		//do inheritance
		String path = p_class->extends_file;

		Ref<GDScript> script;
		Ref<GDNativeClass> native;

		if (path!="") {
			//path (and optionally subclasses)

			if (path.is_rel_path()) {

				String base = p_script->get_path();
				if (base=="" || base.is_rel_path()) {
					_set_error("Could not resolve relative path for parent class: "+path,p_class);
					return ERR_FILE_NOT_FOUND;
				}
				path=base.get_base_dir().plus_file(path);
			}
			script = ResourceLoader::load(path);
			if (script.is_null()) {
				_set_error("Could not load base class: "+path,p_class);
				return ERR_FILE_NOT_FOUND;
			}
			if (!script->valid) {

				_set_error("Script not fully loaded (cyclic preload?): "+path,p_class);
				return ERR_BUSY;
			}
			//print_line("EXTENDS PATH: "+path+" script is "+itos(script.is_valid())+" indices is "+itos(script->member_indices.size())+" valid? "+itos(script->valid));

			if (p_class->extends_class.size()) {

				for(int i=0;i<p_class->extends_class.size();i++) {

					String sub = p_class->extends_class[i];
					if (script->subclasses.has(sub)) {

						script=script->subclasses[sub];
					} else {

						_set_error("Could not find subclass: "+sub,p_class);
						return ERR_FILE_NOT_FOUND;
					}
				}
			}

		} else {

			ERR_FAIL_COND_V(p_class->extends_class.size()==0,ERR_BUG);
			//look around for the subclasses

			String base=p_class->extends_class[0];
			GDScript *p = p_owner;
			Ref<GDScript> base_class;

			while(p) {

				if (p->subclasses.has(base)) {

					base_class=p->subclasses[base];
					break;
				}
				p=p->_owner;
			}

			if (base_class.is_valid()) {

				for(int i=1;i<p_class->extends_class.size();i++) {

					String subclass=p_class->extends_class[i];

					if (base_class->subclasses.has(subclass)) {

						base_class=base_class->subclasses[subclass];
					} else {

						_set_error("Could not find subclass: "+subclass,p_class);
						return ERR_FILE_NOT_FOUND;
					}
				}

				script=base_class;


			} else {

				if (p_class->extends_class.size()>1) {

					_set_error("Invalid inheritance (unknown class+subclasses)",p_class);
					return ERR_FILE_NOT_FOUND;

				}
				//if not found, try engine classes
				if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) {

					_set_error("Unknown class: '"+base+"'",p_class);
					return ERR_FILE_NOT_FOUND;
				}

				int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base];
				native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx];
				if (!native.is_valid()) {

					_set_error("Global not a class: '"+base+"'",p_class);

					return ERR_FILE_NOT_FOUND;
				}
			}


		}

		if (script.is_valid()) {

			p_script->base=script;
			p_script->_base=p_script->base.ptr();
			p_script->member_indices=script->member_indices;

		} else if (native.is_valid()) {

			p_script->native=native;
		} else {

			_set_error("Could not determine inheritance",p_class);
			return ERR_FILE_NOT_FOUND;
		}


	}


	//print_line("Script: "+p_script->get_path()+" indices: "+itos(p_script->member_indices.size()));


	for(int i=0;i<p_class->variables.size();i++) {

		StringName name = p_class->variables[i].identifier;
		if (p_script->member_indices.has(name)) {
			_set_error("Member '"+name+"' already exists (in current or parent class)",p_class);
			return ERR_ALREADY_EXISTS;
		}

		if (p_class->variables[i]._export.type!=Variant::NIL) {

			p_script->member_info[name]=p_class->variables[i]._export;
#ifdef TOOLS_ENABLED
			if (p_class->variables[i].default_value.get_type()!=Variant::NIL) {

				p_script->member_default_values[name]=p_class->variables[i].default_value;
			}
#endif
		}

		int new_idx = p_script->member_indices.size();
		p_script->member_indices[name]=new_idx;
		p_script->members.insert(name);

	}

	for(int i=0;i<p_class->constant_expressions.size();i++) {

		StringName name = p_class->constant_expressions[i].identifier;
		ERR_CONTINUE( p_class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT );

		GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode*>(p_class->constant_expressions[i].expression);

		p_script->constants.insert(name,constant->value);
		//p_script->constants[constant->value].make_const();
	}


	//parse sub-classes

	for(int i=0;i<p_class->subclasses.size();i++) {
		StringName name = p_class->subclasses[i]->name;

		Ref<GDScript> subclass = memnew( GDScript );

		Error err = _parse_class(subclass.ptr(),p_script,p_class->subclasses[i]);
		if (err)
			return err;

		p_script->constants.insert(name,subclass); //once parsed, goes to the list of constants
		p_script->subclasses.insert(name,subclass);

	}


	//parse methods

	bool has_initializer=false;
	for(int i=0;i<p_class->functions.size();i++) {

		if (!has_initializer && p_class->functions[i]->name=="_init")
			has_initializer=true;
		Error err = _parse_function(p_script,p_class,p_class->functions[i]);
		if (err)
			return err;
	}

	//parse static methods

	for(int i=0;i<p_class->static_functions.size();i++) {

		Error err = _parse_function(p_script,p_class,p_class->static_functions[i]);
		if (err)
			return err;
	}


	if (!has_initializer) {
		//create a constructor
		Error err = _parse_function(p_script,p_class,NULL);
		if (err)
			return err;
	}

	return OK;
}
Beispiel #29
0
RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_original_path, Error *r_error) {
    if (r_error)
        *r_error=ERR_CANT_OPEN;

    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;
    if (r_error)
        *r_error=ERR_FILE_CORRUPT;

    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);

    if (r_error)
        *r_error=OK;

    return theme;
}
Beispiel #30
0
void ScriptCreateDialog::_path_changed(const String& p_path) {

	path_valid=false;
	String p =p_path;

	if (p=="")	 {

		path_error_label->set_text(TTR("Path is empty"));
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		return;

	}

	p = Globals::get_singleton()->localize_path(p);
	if (!p.begins_with("res://")) {

		path_error_label->set_text(TTR("Path is not local"));
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		return;
	}

	if (p.find("/") || p.find("\\")) {
		DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);

		if (d->change_dir(p.get_base_dir())!=OK) {

			path_error_label->set_text(TTR("Invalid base path"));
			path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
			memdelete(d);
			return;

		}
		memdelete(d);
	}

	FileAccess *f = FileAccess::create(FileAccess::ACCESS_RESOURCES);
	create_new=!f->file_exists(p);
	memdelete(f);

	String extension=p.extension();
	List<String> extensions;

	// get all possible extensions for script
	for (int l=0;l<language_menu->get_item_count();l++) {
		ScriptServer::get_language( l )->get_recognized_extensions(&extensions);
	}

	bool found=false;
	int index=0;
	for(List<String>::Element *E=extensions.front();E;E=E->next()) {
		if (E->get().nocasecmp_to(extension)==0) {
			language_menu->select(index); // change Language option by extension
			found=true;
			break;
		}
		index++;
	}

	if (!found) {
		path_error_label->set_text(TTR("Invalid extension"));
		path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
		return;
	}

	_update_controls();

	path_error_label->add_color_override("font_color",Color(0,1.0,0.8,0.8));

	path_valid=true;

}