diff options
Diffstat (limited to 'core/io')
60 files changed, 4557 insertions, 5316 deletions
diff --git a/core/io/compression.cpp b/core/io/compression.cpp index cf29cb921..4ac2fd3bf 100644 --- a/core/io/compression.cpp +++ b/core/io/compression.cpp @@ -26,25 +26,25 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "zlib.h" -#include "os/copymem.h" #include "compression.h" +#include "os/copymem.h" +#include "zlib.h" #include "fastlz.h" #include "zip_io.h" -int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode) { +int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) { - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - if (p_src_size<16) { + if (p_src_size < 16) { uint8_t src[16]; - zeromem(&src[p_src_size],16-p_src_size); - copymem(src,p_src,p_src_size); - return fastlz_compress(src,16,p_dst); + zeromem(&src[p_src_size], 16 - p_src_size); + copymem(src, p_src, p_src_size); + return fastlz_compress(src, 16, p_dst); } else { - return fastlz_compress(p_src,p_src_size,p_dst); + return fastlz_compress(p_src, p_src_size, p_dst); } } break; @@ -54,16 +54,16 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION); - if (err!=Z_OK) - return -1; + int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION); + if (err != Z_OK) + return -1; - strm.avail_in=p_src_size; - int aout = deflateBound(&strm,p_src_size); - strm.avail_out=aout; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; - deflate(&strm,Z_FINISH); + strm.avail_in = p_src_size; + int aout = deflateBound(&strm, p_src_size); + strm.avail_out = aout; + strm.next_in = (Bytef *)p_src; + strm.next_out = p_dst; + deflate(&strm, Z_FINISH); aout = aout - strm.avail_out; deflateEnd(&strm); return aout; @@ -74,15 +74,14 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M ERR_FAIL_V(-1); } -int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){ +int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) { - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - - int ss = p_src_size+p_src_size*6/100; - if (ss<66) - ss=66; + int ss = p_src_size + p_src_size * 6 / 100; + if (ss < 66) + ss = 66; return ss; } break; @@ -92,32 +91,29 @@ int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){ strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION); - if (err!=Z_OK) - return -1; - int aout = deflateBound(&strm,p_src_size); + int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION); + if (err != Z_OK) + return -1; + int aout = deflateBound(&strm, p_src_size); deflateEnd(&strm); return aout; } break; } ERR_FAIL_V(-1); - } +void Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) { - -void Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode){ - - switch(p_mode) { + switch (p_mode) { case MODE_FASTLZ: { - if (p_dst_max_size<16) { + if (p_dst_max_size < 16) { uint8_t dst[16]; - fastlz_decompress(p_src,p_src_size,dst,16); - copymem(p_dst,dst,p_dst_max_size); + fastlz_decompress(p_src, p_src_size, dst, 16); + copymem(p_dst, dst, p_dst_max_size); } else { - fastlz_decompress(p_src,p_src_size,p_dst,p_dst_max_size); + fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size); } return; } break; @@ -127,19 +123,19 @@ void Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t * strm.zalloc = zipio_alloc; strm.zfree = zipio_free; strm.opaque = Z_NULL; - strm.avail_in= 0; - strm.next_in=Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; int err = inflateInit(&strm); - ERR_FAIL_COND(err!=Z_OK); + ERR_FAIL_COND(err != Z_OK); - strm.avail_in=p_src_size; - strm.avail_out=p_dst_max_size; - strm.next_in=(Bytef*)p_src; - strm.next_out=p_dst; + strm.avail_in = p_src_size; + strm.avail_out = p_dst_max_size; + strm.next_in = (Bytef *)p_src; + strm.next_out = p_dst; - err = inflate(&strm,Z_FINISH); + err = inflate(&strm, Z_FINISH); inflateEnd(&strm); - ERR_FAIL_COND(err!=Z_STREAM_END); + ERR_FAIL_COND(err != Z_STREAM_END); return; } break; } diff --git a/core/io/compression.h b/core/io/compression.h index dda127055..c2b498fbb 100644 --- a/core/io/compression.h +++ b/core/io/compression.h @@ -31,23 +31,18 @@ #include "typedefs.h" -class Compression -{ +class Compression { public: - enum Mode { MODE_FASTLZ, MODE_DEFLATE }; - - static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ); - static int get_max_compressed_buffer_size(int p_src_size,Mode p_mode=MODE_FASTLZ); - static void decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ); + static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ); + static int get_max_compressed_buffer_size(int p_src_size, Mode p_mode = MODE_FASTLZ); + static void decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ); Compression(); }; - - #endif // COMPRESSION_H diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp index 1cf600a0c..2c2352616 100644 --- a/core/io/config_file.cpp +++ b/core/io/config_file.cpp @@ -27,8 +27,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "config_file.h" -#include "os/keyboard.h" #include "os/file_access.h" +#include "os/keyboard.h" #include "variant_parser.h" StringArray ConfigFile::_get_sections() const { @@ -37,35 +37,33 @@ StringArray ConfigFile::_get_sections() const { get_sections(&s); StringArray arr; arr.resize(s.size()); - int idx=0; - for(const List<String>::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; } -StringArray ConfigFile::_get_section_keys(const String& p_section) const{ +StringArray ConfigFile::_get_section_keys(const String &p_section) const { List<String> s; - get_section_keys(p_section,&s); + get_section_keys(p_section, &s); StringArray arr; arr.resize(s.size()); - int idx=0; - for(const List<String>::Element *E=s.front();E;E=E->next()) { + int idx = 0; + for (const List<String>::Element *E = s.front(); E; E = E->next()) { - arr.set(idx++,E->get()); + arr.set(idx++, E->get()); } return arr; - } +void ConfigFile::set_value(const String &p_section, const String &p_key, const Variant &p_value) { -void ConfigFile::set_value(const String& p_section, const String& p_key, const Variant& p_value){ - - if (p_value.get_type()==Variant::NIL) { + if (p_value.get_type() == Variant::NIL) { //erase if (!values.has(p_section)) return; // ? @@ -76,55 +74,49 @@ void ConfigFile::set_value(const String& p_section, const String& p_key, const V } else { if (!values.has(p_section)) { - values[p_section]=Map<String, Variant>(); + values[p_section] = Map<String, Variant>(); } - values[p_section][p_key]=p_value; - + values[p_section][p_key] = p_value; } - } -Variant ConfigFile::get_value(const String& p_section, const String& p_key, Variant p_default) const { +Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const { - ERR_FAIL_COND_V(!values.has(p_section),p_default); - ERR_FAIL_COND_V(!values[p_section].has(p_key),p_default); + ERR_FAIL_COND_V(!values.has(p_section), p_default); + ERR_FAIL_COND_V(!values[p_section].has(p_key), p_default); return values[p_section][p_key]; - } -bool ConfigFile::has_section(const String& p_section) const { +bool ConfigFile::has_section(const String &p_section) const { return values.has(p_section); } -bool ConfigFile::has_section_key(const String& p_section,const String& p_key) const { +bool ConfigFile::has_section_key(const String &p_section, const String &p_key) const { if (!values.has(p_section)) return false; return values[p_section].has(p_key); } -void ConfigFile::get_sections(List<String> *r_sections) const{ +void ConfigFile::get_sections(List<String> *r_sections) const { - for(const Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) { + for (const Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) { r_sections->push_back(E->key()); } } -void ConfigFile::get_section_keys(const String& p_section,List<String> *r_keys) const{ +void ConfigFile::get_section_keys(const String &p_section, List<String> *r_keys) const { ERR_FAIL_COND(!values.has(p_section)); - for(const Map<String, Variant> ::Element *E=values[p_section].front();E;E=E->next()) { + for (const Map<String, Variant>::Element *E = values[p_section].front(); E; E = E->next()) { r_keys->push_back(E->key()); } - } - - -Error ConfigFile::save(const String& p_path){ +Error ConfigFile::save(const String &p_path) { Error err; - FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err); + FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { if (file) @@ -132,18 +124,17 @@ Error ConfigFile::save(const String& p_path){ return err; } + for (Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) { - for(Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) { - - if (E!=values.front()) + if (E != values.front()) file->store_string("\n"); - file->store_string("["+E->key()+"]\n\n"); + file->store_string("[" + E->key() + "]\n\n"); - for(Map<String, Variant>::Element *F=E->get().front();F;F=F->next()) { + for (Map<String, Variant>::Element *F = E->get().front(); F; F = F->next()) { String vstr; - VariantWriter::write_to_string(F->get(),vstr); - file->store_string(F->key()+"="+vstr+"\n"); + VariantWriter::write_to_string(F->get(), vstr); + file->store_string(F->key() + "=" + vstr + "\n"); } } @@ -152,48 +143,46 @@ Error ConfigFile::save(const String& p_path){ return OK; } - -Error ConfigFile::load(const String& p_path) { +Error ConfigFile::load(const String &p_path) { Error err; - FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return ERR_CANT_OPEN; VariantParser::StreamFile stream; - stream.f=f; + stream.f = f; String assign; Variant value; VariantParser::Tag next_tag; - int lines=0; + int lines = 0; String error_text; String section; - while(true) { + while (true) { - assign=Variant(); + assign = Variant(); next_tag.fields.clear(); - next_tag.name=String(); + next_tag.name = String(); - err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true); - if (err==ERR_FILE_EOF) { + err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true); + if (err == ERR_FILE_EOF) { memdelete(f); return OK; - } - else if (err!=OK) { - ERR_PRINTS("ConfgFile::load - "+p_path+":"+itos(lines)+" error: "+error_text); + } else if (err != OK) { + ERR_PRINTS("ConfgFile::load - " + p_path + ":" + itos(lines) + " error: " + error_text); memdelete(f); return err; } - if (assign!=String()) { - set_value(section,assign,value); - } else if (next_tag.name!=String()) { - section=next_tag.name; + if (assign != String()) { + set_value(section, assign, value); + } else if (next_tag.name != String()) { + section = next_tag.name; } } @@ -202,25 +191,20 @@ Error ConfigFile::load(const String& p_path) { return OK; } +void ConfigFile::_bind_methods() { + ObjectTypeDB::bind_method(_MD("set_value", "section", "key", "value"), &ConfigFile::set_value); + ObjectTypeDB::bind_method(_MD("get_value:Variant", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant())); -void ConfigFile::_bind_methods(){ + ObjectTypeDB::bind_method(_MD("has_section", "section"), &ConfigFile::has_section); + ObjectTypeDB::bind_method(_MD("has_section_key", "section", "key"), &ConfigFile::has_section_key); - ObjectTypeDB::bind_method(_MD("set_value","section","key","value"),&ConfigFile::set_value); - ObjectTypeDB::bind_method(_MD("get_value:Variant","section","key","default"),&ConfigFile::get_value,DEFVAL(Variant())); - - ObjectTypeDB::bind_method(_MD("has_section","section"),&ConfigFile::has_section); - ObjectTypeDB::bind_method(_MD("has_section_key","section","key"),&ConfigFile::has_section_key); - - ObjectTypeDB::bind_method(_MD("get_sections"),&ConfigFile::_get_sections); - ObjectTypeDB::bind_method(_MD("get_section_keys","section"),&ConfigFile::_get_section_keys); - - ObjectTypeDB::bind_method(_MD("load:Error","path"),&ConfigFile::load); - ObjectTypeDB::bind_method(_MD("save:Error","path"),&ConfigFile::save); + ObjectTypeDB::bind_method(_MD("get_sections"), &ConfigFile::_get_sections); + ObjectTypeDB::bind_method(_MD("get_section_keys", "section"), &ConfigFile::_get_section_keys); + ObjectTypeDB::bind_method(_MD("load:Error", "path"), &ConfigFile::load); + ObjectTypeDB::bind_method(_MD("save:Error", "path"), &ConfigFile::save); } - -ConfigFile::ConfigFile() -{ +ConfigFile::ConfigFile() { } diff --git a/core/io/config_file.h b/core/io/config_file.h index 6481f0522..882bb572d 100644 --- a/core/io/config_file.h +++ b/core/io/config_file.h @@ -31,31 +31,30 @@ #include "reference.h" - class ConfigFile : public Reference { - OBJ_TYPE(ConfigFile,Reference); + OBJ_TYPE(ConfigFile, Reference); - Map< String, Map<String, Variant> > values; + Map<String, Map<String, Variant> > values; StringArray _get_sections() const; - StringArray _get_section_keys(const String& p_section) const; -protected: + StringArray _get_section_keys(const String &p_section) const; +protected: static void _bind_methods(); -public: - void set_value(const String& p_section, const String& p_key, const Variant& p_value); - Variant get_value(const String& p_section, const String& p_key, Variant p_default=Variant()) const; +public: + void set_value(const String &p_section, const String &p_key, const Variant &p_value); + Variant get_value(const String &p_section, const String &p_key, Variant p_default = Variant()) const; - bool has_section(const String& p_section) const; - bool has_section_key(const String& p_section,const String& p_key) const; + bool has_section(const String &p_section) const; + bool has_section_key(const String &p_section, const String &p_key) const; void get_sections(List<String> *r_sections) const; - void get_section_keys(const String& p_section,List<String> *r_keys) const; + void get_section_keys(const String &p_section, List<String> *r_keys) const; - Error save(const String& p_path); - Error load(const String& p_path); + Error save(const String &p_path); + Error load(const String &p_path); ConfigFile(); }; diff --git a/core/io/export_data.cpp b/core/io/export_data.cpp index 2495288a7..29018c7c6 100644 --- a/core/io/export_data.cpp +++ b/core/io/export_data.cpp @@ -1,2 +1 @@ #include "export_data.h" - diff --git a/core/io/export_data.h b/core/io/export_data.h index 1e1941bad..dc2584984 100644 --- a/core/io/export_data.h +++ b/core/io/export_data.h @@ -1,9 +1,9 @@ #ifndef EXPORT_DATA_H #define EXPORT_DATA_H +#include "map.h" #include "variant.h" #include "vector.h" -#include "map.h" struct ExportData { struct Dependency { @@ -11,7 +11,7 @@ struct ExportData { String type; }; - Map<int,Dependency> dependencies; + Map<int, Dependency> dependencies; struct PropertyData { String name; @@ -23,12 +23,10 @@ struct ExportData { String type; int index; List<PropertyData> properties; - }; Vector<ResourceData> resources; - struct NodeData { bool text_data; @@ -41,19 +39,20 @@ struct ExportData { int parent_int; bool instance_is_placeholder; - //text info NodePath parent; NodePath owner; String instance_placeholder; - - Vector<String> groups; List<PropertyData> properties; - - NodeData() { parent_int=0; owner_int=0; text_data=true; instanced=false;} + NodeData() { + parent_int = 0; + owner_int = 0; + text_data = true; + instanced = false; + } }; Vector<NodeData> nodes; @@ -72,7 +71,7 @@ struct ExportData { Array binds; int flags; - Connection() { text_data=true; } + Connection() { text_data = true; } }; Vector<Connection> connections; @@ -80,8 +79,6 @@ struct ExportData { Array node_paths; //for integer packed data Variant base_scene; - - }; #endif // EXPORT_DATA_H diff --git a/core/io/file_access_buffered.cpp b/core/io/file_access_buffered.cpp index 347edc740..1a0423a05 100644 --- a/core/io/file_access_buffered.cpp +++ b/core/io/file_access_buffered.cpp @@ -92,7 +92,7 @@ bool FileAccessBuffered::eof_reached() const { uint8_t FileAccessBuffered::get_8() const { - ERR_FAIL_COND_V(!file.open,0); + ERR_FAIL_COND_V(!file.open, 0); uint8_t byte = 0; if (cache_data_left() >= 1) { @@ -105,7 +105,7 @@ uint8_t FileAccessBuffered::get_8() const { return byte; }; -int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { +int FileAccessBuffered::get_buffer(uint8_t *p_dest, int p_elements) const { ERR_FAIL_COND_V(!file.open, -1); @@ -135,7 +135,6 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { return total_read; }; - int to_read = p_elements; int total_read = 0; while (to_read > 0) { @@ -154,7 +153,7 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const { int r = MIN(left, to_read); //DVector<uint8_t>::Read read = cache.buffer.read(); //memcpy(p_dest+total_read, &read.ptr()[file.offset - cache.offset], r); - memcpy(p_dest+total_read, cache.buffer.ptr() + (file.offset - cache.offset), r); + memcpy(p_dest + total_read, cache.buffer.ptr() + (file.offset - cache.offset), r); file.offset += r; total_read += r; @@ -179,6 +178,5 @@ FileAccessBuffered::FileAccessBuffered() { cache_size = DEFAULT_CACHE_SIZE; }; -FileAccessBuffered::~FileAccessBuffered(){ - +FileAccessBuffered::~FileAccessBuffered() { } diff --git a/core/io/file_access_buffered.h b/core/io/file_access_buffered.h index be8ea714b..964152af5 100644 --- a/core/io/file_access_buffered.h +++ b/core/io/file_access_buffered.h @@ -42,14 +42,12 @@ public: }; private: - int cache_size; int cache_data_left() const; mutable Error last_error; protected: - Error set_error(Error p_error) const; mutable struct File { @@ -67,23 +65,22 @@ protected: int offset; } cache; - virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const =0; + virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const = 0; void set_cache_size(int p_size); int get_cache_size(); public: - virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual bool eof_reached() const; virtual uint8_t get_8() const; - virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes + virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes virtual bool is_open() const; @@ -94,4 +91,3 @@ public: }; #endif - diff --git a/core/io/file_access_buffered_fa.h b/core/io/file_access_buffered_fa.h index 8a15584b1..a6638e08a 100644 --- a/core/io/file_access_buffered_fa.h +++ b/core/io/file_access_buffered_fa.h @@ -31,16 +31,16 @@ #include "core/io/file_access_buffered.h" -template<class T> +template <class T> class FileAccessBufferedFA : public FileAccessBuffered { T f; int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const { - ERR_FAIL_COND_V( !f.is_open(), -1 ); + ERR_FAIL_COND_V(!f.is_open(), -1); - ((T*)&f)->seek(p_offset); + ((T *)&f)->seek(p_offset); if (p_dest) { @@ -63,9 +63,9 @@ class FileAccessBufferedFA : public FileAccessBuffered { }; }; - static FileAccess* create() { + static FileAccess *create() { - return memnew( FileAccessBufferedFA<T>() ); + return memnew(FileAccessBufferedFA<T>()); }; protected: @@ -75,29 +75,27 @@ protected: }; public: - - void store_8(uint8_t p_dest) { f.store_8(p_dest); }; - void store_buffer(const uint8_t *p_src,int p_length) { + void store_buffer(const uint8_t *p_src, int p_length) { f.store_buffer(p_src, p_length); }; - bool file_exists(const String& p_name) { + bool file_exists(const String &p_name) { return f.file_exists(p_name); }; - Error _open(const String& p_path, int p_mode_flags) { + Error _open(const String &p_path, int p_mode_flags) { close(); Error ret = f._open(p_path, p_mode_flags); - if (ret !=OK) + if (ret != OK) return ret; //ERR_FAIL_COND_V( ret != OK, ret ); @@ -127,21 +125,19 @@ public: set_error(OK); }; -// static void make_default() { + // static void make_default() { - //FileAccess::create_func = FileAccessBufferedFA<T>::create; -// }; + //FileAccess::create_func = FileAccessBufferedFA<T>::create; + // }; - virtual uint64_t _get_modified_time(const String& p_file) { + virtual uint64_t _get_modified_time(const String &p_file) { return f._get_modified_time(p_file); } - FileAccessBufferedFA() { - + FileAccessBufferedFA(){ }; }; - #endif // FILE_ACCESS_BUFFERED_FA_H diff --git a/core/io/file_access_compressed.cpp b/core/io/file_access_compressed.cpp index 3bcfade52..d8ae3e6ff 100644 --- a/core/io/file_access_compressed.cpp +++ b/core/io/file_access_compressed.cpp @@ -28,244 +28,223 @@ /*************************************************************************/ #include "file_access_compressed.h" #include "print_string.h" -void FileAccessCompressed::configure(const String& p_magic, Compression::Mode p_mode, int p_block_size) { +void FileAccessCompressed::configure(const String &p_magic, Compression::Mode p_mode, int p_block_size) { - magic=p_magic.ascii().get_data(); - if (magic.length()>4) - magic=magic.substr(0,4); + magic = p_magic.ascii().get_data(); + if (magic.length() > 4) + magic = magic.substr(0, 4); else { - while(magic.length()<4) - magic+=" "; + while (magic.length() < 4) + magic += " "; } - cmode=p_mode; - block_size=p_block_size; - -} - - -#define WRITE_FIT(m_bytes) \ -{\ -if (write_pos+(m_bytes) > write_max) {\ - write_max=write_pos+(m_bytes);\ -}\ -if (write_max > write_buffer_size) {\ - write_buffer_size = nearest_power_of_2( write_max );\ - buffer.resize(write_buffer_size);\ - write_ptr=buffer.ptr();\ -}\ + cmode = p_mode; + block_size = p_block_size; } +#define WRITE_FIT(m_bytes) \ + { \ + if (write_pos + (m_bytes) > write_max) { \ + write_max = write_pos + (m_bytes); \ + } \ + if (write_max > write_buffer_size) { \ + write_buffer_size = nearest_power_of_2(write_max); \ + buffer.resize(write_buffer_size); \ + write_ptr = buffer.ptr(); \ + } \ + } Error FileAccessCompressed::open_after_magic(FileAccess *p_base) { - - f=p_base; - cmode=(Compression::Mode)f->get_32(); - block_size=f->get_32(); - read_total=f->get_32(); - int bc = (read_total/block_size)+1; - int acc_ofs=f->get_pos()+bc*4; - int max_bs=0; - for(int i=0;i<bc;i++) { + f = p_base; + cmode = (Compression::Mode)f->get_32(); + block_size = f->get_32(); + read_total = f->get_32(); + int bc = (read_total / block_size) + 1; + int acc_ofs = f->get_pos() + bc * 4; + int max_bs = 0; + for (int i = 0; i < bc; i++) { ReadBlock rb; - rb.offset=acc_ofs; - rb.csize=f->get_32(); - acc_ofs+=rb.csize; - max_bs=MAX(max_bs,rb.csize); + rb.offset = acc_ofs; + rb.csize = f->get_32(); + acc_ofs += rb.csize; + max_bs = MAX(max_bs, rb.csize); read_blocks.push_back(rb); - - } comp_buffer.resize(max_bs); buffer.resize(block_size); - read_ptr=buffer.ptr(); - f->get_buffer(comp_buffer.ptr(),read_blocks[0].csize); - at_end=false; - read_eof=false; - read_block_count=bc; - read_block_size=read_blocks.size()==1?read_total:block_size; + read_ptr = buffer.ptr(); + f->get_buffer(comp_buffer.ptr(), read_blocks[0].csize); + at_end = false; + read_eof = false; + read_block_count = bc; + read_block_size = read_blocks.size() == 1 ? read_total : block_size; - Compression::decompress(buffer.ptr(),read_block_size,comp_buffer.ptr(),read_blocks[0].csize,cmode); - read_block=0; - read_pos=0; + Compression::decompress(buffer.ptr(), read_block_size, comp_buffer.ptr(), read_blocks[0].csize, cmode); + read_block = 0; + read_pos = 0; return OK; - } -Error FileAccessCompressed::_open(const String& p_path, int p_mode_flags){ +Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags==READ_WRITE,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(p_mode_flags == READ_WRITE, ERR_UNAVAILABLE); if (f) close(); - Error err; - f = FileAccess::open(p_path,p_mode_flags,&err); - if (err!=OK) { + f = FileAccess::open(p_path, p_mode_flags, &err); + if (err != OK) { //not openable - f=NULL; + f = NULL; return err; } - if (p_mode_flags&WRITE) { + if (p_mode_flags & WRITE) { buffer.clear(); - writing=true; - write_pos=0; - write_buffer_size=256; + writing = true; + write_pos = 0; + write_buffer_size = 256; buffer.resize(256); - write_max=0; - write_ptr=buffer.ptr(); - - + write_max = 0; + write_ptr = buffer.ptr(); //don't store anything else unless it's done saving! } else { char rmagic[5]; - f->get_buffer((uint8_t*)rmagic,4); - rmagic[4]=0; - if (magic!=rmagic) { + f->get_buffer((uint8_t *)rmagic, 4); + rmagic[4] = 0; + if (magic != rmagic) { memdelete(f); - f=NULL; + f = NULL; return ERR_FILE_UNRECOGNIZED; } open_after_magic(f); - } return OK; - } -void FileAccessCompressed::close(){ +void FileAccessCompressed::close() { if (!f) return; - if (writing) { //save block table and all compressed blocks CharString mgc = magic.utf8(); - f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //write header 4 + f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //write header 4 f->store_32(cmode); //write compression mode 4 f->store_32(block_size); //write block size 4 f->store_32(write_max); //max amount of data written 4 - int bc=(write_max/block_size)+1; + int bc = (write_max / block_size) + 1; - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { f->store_32(0); //compressed sizes, will update later } - Vector<int> block_sizes; - for(int i=0;i<bc;i++) { + for (int i = 0; i < bc; i++) { - int bl = i==(bc-1) ? write_max % block_size : block_size; - uint8_t *bp = &write_ptr[i*block_size]; + int bl = i == (bc - 1) ? write_max % block_size : block_size; + uint8_t *bp = &write_ptr[i * block_size]; Vector<uint8_t> cblock; - cblock.resize(Compression::get_max_compressed_buffer_size(bl,cmode)); - int s = Compression::compress(cblock.ptr(),bp,bl,cmode); + cblock.resize(Compression::get_max_compressed_buffer_size(bl, cmode)); + int s = Compression::compress(cblock.ptr(), bp, bl, cmode); - f->store_buffer(cblock.ptr(),s); + f->store_buffer(cblock.ptr(), s); block_sizes.push_back(s); } f->seek(16); //ok write block sizes - for(int i=0;i<bc;i++) + for (int i = 0; i < bc; i++) f->store_32(block_sizes[i]); f->seek_end(); - f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //magic at the end too + f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //magic at the end too buffer.clear(); } else { - comp_buffer.clear(); buffer.clear(); read_blocks.clear(); } memdelete(f); - f=NULL; - + f = NULL; } -bool FileAccessCompressed::is_open() const{ +bool FileAccessCompressed::is_open() const { - return f!=NULL; + return f != NULL; } -void FileAccessCompressed::seek(size_t p_position){ +void FileAccessCompressed::seek(size_t p_position) { ERR_FAIL_COND(!f); if (writing) { - ERR_FAIL_COND(p_position>write_max); + ERR_FAIL_COND(p_position > write_max); - write_pos=p_position; + write_pos = p_position; } else { - ERR_FAIL_COND(p_position>read_total); - if (p_position==read_total) { - at_end=true; + ERR_FAIL_COND(p_position > read_total); + if (p_position == read_total) { + at_end = true; } else { - int block_idx = p_position/block_size; - if (block_idx!=read_block) { + int block_idx = p_position / block_size; + if (block_idx != read_block) { - read_block=block_idx; + read_block = block_idx; f->seek(read_blocks[read_block].offset); - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; } - read_pos=p_position%block_size; + read_pos = p_position % block_size; } } } - -void FileAccessCompressed::seek_end(int64_t p_position){ +void FileAccessCompressed::seek_end(int64_t p_position) { ERR_FAIL_COND(!f); if (writing) { - seek(write_max+p_position); + seek(write_max + p_position); } else { - seek(read_total+p_position); - + seek(read_total + p_position); } - - } -size_t FileAccessCompressed::get_pos() const{ +size_t FileAccessCompressed::get_pos() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); if (writing) { return write_pos; } else { - return read_block*block_size+read_pos; + return read_block * block_size + read_pos; } - } -size_t FileAccessCompressed::get_len() const{ +size_t FileAccessCompressed::get_len() const { - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(!f, 0); if (writing) { return write_max; @@ -274,9 +253,9 @@ size_t FileAccessCompressed::get_len() const{ } } -bool FileAccessCompressed::eof_reached() const{ +bool FileAccessCompressed::eof_reached() const { - ERR_FAIL_COND_V(!f,false); + ERR_FAIL_COND_V(!f, false); if (writing) { return false; } else { @@ -284,106 +263,99 @@ bool FileAccessCompressed::eof_reached() const{ } } -uint8_t FileAccessCompressed::get_8() const{ +uint8_t FileAccessCompressed::get_8() const { - ERR_FAIL_COND_V(writing,0); - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(writing, 0); + ERR_FAIL_COND_V(!f, 0); if (at_end) { - read_eof=true; + read_eof = true; return 0; } uint8_t ret = read_ptr[read_pos]; read_pos++; - if (read_pos>=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_block<read_block_count) { + if (read_block < read_block_count) { //read another block of compressed data - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; - read_pos=0; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; + read_pos = 0; } else { read_block--; - at_end=true; - ret =0; + at_end = true; + ret = 0; } } return ret; - } -int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const { - ERR_FAIL_COND_V(writing,0); - ERR_FAIL_COND_V(!f,0); + ERR_FAIL_COND_V(writing, 0); + ERR_FAIL_COND_V(!f, 0); if (at_end) { - read_eof=true; + read_eof = true; return 0; } + for (int i = 0; i < p_length; i++) { - for(int i=0;i<p_length;i++) { - - - p_dst[i]=read_ptr[read_pos]; + p_dst[i] = read_ptr[read_pos]; read_pos++; - if (read_pos>=read_block_size) { + if (read_pos >= read_block_size) { read_block++; - if (read_block<read_block_count) { + if (read_block < read_block_count) { //read another block of compressed data - f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize); - Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode); - read_block_size=read_block==read_block_count-1?read_total%block_size:block_size; - read_pos=0; + f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize); + Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode); + read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size; + read_pos = 0; } else { read_block--; - at_end=true; - if (i<p_length-1) - read_eof=true; + at_end = true; + if (i < p_length - 1) + read_eof = true; return i; - } } - } return p_length; - } -Error FileAccessCompressed::get_error() const{ +Error FileAccessCompressed::get_error() const { - return read_eof?ERR_FILE_EOF:OK; + return read_eof ? ERR_FILE_EOF : OK; } -void FileAccessCompressed::store_8(uint8_t p_dest){ +void FileAccessCompressed::store_8(uint8_t p_dest) { ERR_FAIL_COND(!f); ERR_FAIL_COND(!writing); WRITE_FIT(1); - write_ptr[write_pos++]=p_dest; - + write_ptr[write_pos++] = p_dest; } -bool FileAccessCompressed::file_exists(const String& p_name){ +bool FileAccessCompressed::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name,FileAccess::READ); + FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); if (!fa) return false; memdelete(fa); return true; } -uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) { +uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) { if (f) return f->get_modified_time(p_file); @@ -393,29 +365,27 @@ uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) { FileAccessCompressed::FileAccessCompressed() { - f=NULL; - magic="GCMP"; - block_size=16384; - cmode=Compression::MODE_DEFLATE; - writing=false; - write_ptr=0; - write_buffer_size=0; - write_max=0; - block_size=0; - read_eof=false; - at_end=false; - read_total=0; - read_ptr=NULL; - read_block=0; - read_block_count=0; - read_block_size=0; - read_pos=0; - + f = NULL; + magic = "GCMP"; + block_size = 16384; + cmode = Compression::MODE_DEFLATE; + writing = false; + write_ptr = 0; + write_buffer_size = 0; + write_max = 0; + block_size = 0; + read_eof = false; + at_end = false; + read_total = 0; + read_ptr = NULL; + read_block = 0; + read_block_count = 0; + read_block_size = 0; + read_pos = 0; } -FileAccessCompressed::~FileAccessCompressed(){ +FileAccessCompressed::~FileAccessCompressed() { if (f) close(); - } diff --git a/core/io/file_access_compressed.h b/core/io/file_access_compressed.h index 70034120f..ea45c110d 100644 --- a/core/io/file_access_compressed.h +++ b/core/io/file_access_compressed.h @@ -37,7 +37,7 @@ class FileAccessCompressed : public FileAccess { Compression::Mode cmode; bool writing; int write_pos; - uint8_t*write_ptr; + uint8_t *write_ptr; int write_buffer_size; int write_max; int block_size; @@ -58,24 +58,21 @@ class FileAccessCompressed : public FileAccess { Vector<ReadBlock> read_blocks; int read_total; - - - String magic; mutable Vector<uint8_t> buffer; FileAccess *f; -public: - void configure(const String& p_magic, Compression::Mode p_mode=Compression::MODE_FASTLZ, int p_block_size=4096); +public: + void configure(const String &p_magic, Compression::Mode p_mode = Compression::MODE_FASTLZ, int p_block_size = 4096); Error open_after_magic(FileAccess *p_base); - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -88,14 +85,12 @@ public: virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_name); ///< return true if a file exists - - virtual uint64_t _get_modified_time(const String& p_file); + virtual bool file_exists(const String &p_name); ///< return true if a file exists + virtual uint64_t _get_modified_time(const String &p_file); FileAccessCompressed(); virtual ~FileAccessCompressed(); - }; #endif // FILE_ACCESS_COMPRESSED_H diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp index 039458237..03700cad4 100644 --- a/core/io/file_access_encrypted.cpp +++ b/core/io/file_access_encrypted.cpp @@ -36,55 +36,55 @@ #include "core/variant.h" #include <stdio.h> -Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode) { +Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode) { //print_line("open and parse!"); - ERR_FAIL_COND_V(file!=NULL,ERR_ALREADY_IN_USE); - ERR_FAIL_COND_V(p_key.size()!=32,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(file != NULL, ERR_ALREADY_IN_USE); + ERR_FAIL_COND_V(p_key.size() != 32, ERR_INVALID_PARAMETER); - pos=0; - eofed=false; + pos = 0; + eofed = false; - if (p_mode==MODE_WRITE_AES256) { + if (p_mode == MODE_WRITE_AES256) { data.clear(); - writing=true; - file=p_base; - mode=p_mode; - key=p_key; + writing = true; + file = p_base; + mode = p_mode; + key = p_key; - } else if (p_mode==MODE_READ) { + } else if (p_mode == MODE_READ) { - writing=false; - key=p_key; + writing = false; + key = p_key; uint32_t magic = p_base->get_32(); - print_line("MAGIC: "+itos(magic)); - ERR_FAIL_COND_V(magic!=COMP_MAGIC,ERR_FILE_UNRECOGNIZED); - mode=Mode(p_base->get_32()); - ERR_FAIL_INDEX_V(mode,MODE_MAX,ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(mode==0,ERR_FILE_CORRUPT); - print_line("MODE: "+itos(mode)); + print_line("MAGIC: " + itos(magic)); + ERR_FAIL_COND_V(magic != COMP_MAGIC, ERR_FILE_UNRECOGNIZED); + mode = Mode(p_base->get_32()); + ERR_FAIL_INDEX_V(mode, MODE_MAX, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(mode == 0, ERR_FILE_CORRUPT); + print_line("MODE: " + itos(mode)); unsigned char md5d[16]; - p_base->get_buffer(md5d,16); - length=p_base->get_64(); - base=p_base->get_pos(); - ERR_FAIL_COND_V(p_base->get_len() < base+length, ERR_FILE_CORRUPT ); + p_base->get_buffer(md5d, 16); + length = p_base->get_64(); + base = p_base->get_pos(); + ERR_FAIL_COND_V(p_base->get_len() < base + length, ERR_FILE_CORRUPT); int ds = length; if (ds % 16) { - ds+=16-(ds % 16); + ds += 16 - (ds % 16); } data.resize(ds); - int blen = p_base->get_buffer(data.ptr(),ds); - ERR_FAIL_COND_V(blen!=ds,ERR_FILE_CORRUPT); + int blen = p_base->get_buffer(data.ptr(), ds); + ERR_FAIL_COND_V(blen != ds, ERR_FILE_CORRUPT); aes256_context ctx; - aes256_init(&ctx,key.ptr()); + aes256_init(&ctx, key.ptr()); - for(size_t i=0;i<ds;i+=16) { + for (size_t i = 0; i < ds; i += 16) { - aes256_decrypt_ecb(&ctx,&data[i]); + aes256_decrypt_ecb(&ctx, &data[i]); } aes256_done(&ctx); @@ -93,37 +93,32 @@ Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_ MD5_CTX md5; MD5Init(&md5); - MD5Update(&md5,data.ptr(),data.size()); + MD5Update(&md5, data.ptr(), data.size()); MD5Final(&md5); + ERR_FAIL_COND_V(String::md5(md5.digest) != String::md5(md5d), ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(String::md5(md5.digest)!=String::md5(md5d),ERR_FILE_CORRUPT) ; - - - file=p_base; + file = p_base; } return OK; } -Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode){ - +Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode) { String cs = p_key.md5_text(); - ERR_FAIL_COND_V(cs.length()!=32,ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(cs.length() != 32, ERR_INVALID_PARAMETER); Vector<uint8_t> key; key.resize(32); - for(int i=0;i<32;i++) { + for (int i = 0; i < 32; i++) { - key[i]=cs[i]; + key[i] = cs[i]; } - return open_and_parse(p_base,key,p_mode); + return open_and_parse(p_base, key, p_mode); } - - -Error FileAccessEncrypted::_open(const String& p_path, int p_mode_flags) { +Error FileAccessEncrypted::_open(const String &p_path, int p_mode_flags) { return OK; } @@ -137,26 +132,26 @@ void FileAccessEncrypted::close() { Vector<uint8_t> compressed; size_t len = data.size(); if (len % 16) { - len+=16-(len % 16); + len += 16 - (len % 16); } MD5_CTX md5; MD5Init(&md5); - MD5Update(&md5,data.ptr(),data.size()); + MD5Update(&md5, data.ptr(), data.size()); MD5Final(&md5); compressed.resize(len); - zeromem( compressed.ptr(), len ); - for(int i=0;i<data.size();i++) { - compressed[i]=data[i]; + zeromem(compressed.ptr(), len); + for (int i = 0; i < data.size(); i++) { + compressed[i] = data[i]; } aes256_context ctx; - aes256_init(&ctx,key.ptr()); + aes256_init(&ctx, key.ptr()); - for(size_t i=0;i<len;i+=16) { + for (size_t i = 0; i < len; i += 16) { - aes256_encrypt_ecb(&ctx,&compressed[i]); + aes256_encrypt_ecb(&ctx, &compressed[i]); } aes256_done(&ctx); @@ -164,14 +159,13 @@ void FileAccessEncrypted::close() { file->store_32(COMP_MAGIC); file->store_32(mode); - - file->store_buffer(md5.digest,16); + file->store_buffer(md5.digest, 16); file->store_64(data.size()); - file->store_buffer(compressed.ptr(),compressed.size()); + file->store_buffer(compressed.ptr(), compressed.size()); file->close(); memdelete(file); - file=NULL; + file = NULL; data.clear(); } else { @@ -179,143 +173,133 @@ void FileAccessEncrypted::close() { file->close(); memdelete(file); data.clear(); - file=NULL; + file = NULL; } - - - } -bool FileAccessEncrypted::is_open() const{ +bool FileAccessEncrypted::is_open() const { - return file!=NULL; + return file != NULL; } -void FileAccessEncrypted::seek(size_t p_position){ +void FileAccessEncrypted::seek(size_t p_position) { if (p_position > (size_t)data.size()) - p_position=data.size(); - - pos=p_position; - eofed=false; + p_position = data.size(); + pos = p_position; + eofed = false; } +void FileAccessEncrypted::seek_end(int64_t p_position) { -void FileAccessEncrypted::seek_end(int64_t p_position){ - - seek( data.size() + p_position ); + seek(data.size() + p_position); } -size_t FileAccessEncrypted::get_pos() const{ +size_t FileAccessEncrypted::get_pos() const { return pos; } -size_t FileAccessEncrypted::get_len() const{ +size_t FileAccessEncrypted::get_len() const { return data.size(); } -bool FileAccessEncrypted::eof_reached() const{ +bool FileAccessEncrypted::eof_reached() const { return eofed; } -uint8_t FileAccessEncrypted::get_8() const{ +uint8_t FileAccessEncrypted::get_8() const { - ERR_FAIL_COND_V(writing,0); - if (pos>=data.size()) { - eofed=true; + ERR_FAIL_COND_V(writing, 0); + if (pos >= data.size()) { + eofed = true; return 0; } uint8_t b = data[pos]; pos++; return b; - } -int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const { - ERR_FAIL_COND_V(writing,0); + ERR_FAIL_COND_V(writing, 0); - int to_copy=MIN(p_length,data.size()-pos); - for(int i=0;i<to_copy;i++) { + int to_copy = MIN(p_length, data.size() - pos); + for (int i = 0; i < to_copy; i++) { - p_dst[i]=data[pos++]; + p_dst[i] = data[pos++]; } - if (to_copy<p_length) { - eofed=true; + if (to_copy < p_length) { + eofed = true; } - return to_copy; } -Error FileAccessEncrypted::get_error() const{ +Error FileAccessEncrypted::get_error() const { - return eofed?ERR_FILE_EOF:OK; + return eofed ? ERR_FILE_EOF : OK; } -void FileAccessEncrypted::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessEncrypted::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL_COND(!writing); - if (pos<data.size()) { + if (pos < data.size()) { - for(int i=0;i<p_length;i++) { + for (int i = 0; i < p_length; i++) { store_8(p_src[i]); } - } else if (pos==data.size()) { + } else if (pos == data.size()) { - data.resize(pos+p_length); - for(int i=0;i<p_length;i++) { + data.resize(pos + p_length); + for (int i = 0; i < p_length; i++) { - data[pos+i]=p_src[i]; + data[pos + i] = p_src[i]; } - pos+=p_length; + pos += p_length; } } - -void FileAccessEncrypted::store_8(uint8_t p_dest){ +void FileAccessEncrypted::store_8(uint8_t p_dest) { ERR_FAIL_COND(!writing); - if (pos<data.size()) { - data[pos]=p_dest; + if (pos < data.size()) { + data[pos] = p_dest; pos++; - } else if (pos==data.size()){ + } else if (pos == data.size()) { data.push_back(p_dest); pos++; } } -bool FileAccessEncrypted::file_exists(const String& p_name){ +bool FileAccessEncrypted::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name,FileAccess::READ); + FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); if (!fa) return false; memdelete(fa); return true; } -uint64_t FileAccessEncrypted::_get_modified_time(const String& p_file){ - +uint64_t FileAccessEncrypted::_get_modified_time(const String &p_file) { return 0; } FileAccessEncrypted::FileAccessEncrypted() { - file=NULL; - pos=0; - eofed=false; - mode=MODE_MAX; - writing=false; + file = NULL; + pos = 0; + eofed = false; + mode = MODE_MAX; + writing = false; } - FileAccessEncrypted::~FileAccessEncrypted() { if (file) diff --git a/core/io/file_access_encrypted.h b/core/io/file_access_encrypted.h index 51ed9a867..ac4d2bd1c 100644 --- a/core/io/file_access_encrypted.h +++ b/core/io/file_access_encrypted.h @@ -29,12 +29,10 @@ #ifndef FILE_ACCESS_ENCRYPTED_H #define FILE_ACCESS_ENCRYPTED_H - #include "os/file_access.h" class FileAccessEncrypted : public FileAccess { public: - enum Mode { MODE_READ, MODE_WRITE_AES256, @@ -42,8 +40,6 @@ public: }; private: - - Mode mode; Vector<uint8_t> key; bool writing; @@ -54,21 +50,16 @@ private: mutable size_t pos; mutable bool eofed; - public: + Error open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode); + Error open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode); - - - - Error open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode); - Error open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode); - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -80,11 +71,11 @@ public: virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes + virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes - virtual bool file_exists(const String& p_name); ///< return true if a file exists + virtual bool file_exists(const String &p_name); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file); + virtual uint64_t _get_modified_time(const String &p_file); FileAccessEncrypted(); ~FileAccessEncrypted(); diff --git a/core/io/file_access_memory.cpp b/core/io/file_access_memory.cpp index e1f6831f7..470910077 100644 --- a/core/io/file_access_memory.cpp +++ b/core/io/file_access_memory.cpp @@ -28,12 +28,12 @@ /*************************************************************************/ #include "file_access_memory.h" -#include "os/dir_access.h" -#include "os/copymem.h" #include "globals.h" #include "map.h" +#include "os/copymem.h" +#include "os/dir_access.h" -static Map<String, Vector<uint8_t> >* files = NULL; +static Map<String, Vector<uint8_t> > *files = NULL; void FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) { @@ -59,37 +59,35 @@ void FileAccessMemory::cleanup() { memdelete(files); } - -FileAccess* FileAccessMemory::create() { +FileAccess *FileAccessMemory::create() { return memnew(FileAccessMemory); } -bool FileAccessMemory::file_exists(const String& p_name) { +bool FileAccessMemory::file_exists(const String &p_name) { String name = fix_path(p_name); -// name = DirAccess::normalize_path(name); + // name = DirAccess::normalize_path(name); return files && (files->find(name) != NULL); } +Error FileAccessMemory::open_custom(const uint8_t *p_data, int p_len) { -Error FileAccessMemory::open_custom(const uint8_t* p_data, int p_len) { - - data=(uint8_t*)p_data; - length=p_len; - pos=0; + data = (uint8_t *)p_data; + length = p_len; + pos = 0; return OK; } -Error FileAccessMemory::_open(const String& p_path, int p_mode_flags) { +Error FileAccessMemory::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND); String name = fix_path(p_path); -// name = DirAccess::normalize_path(name); + // name = DirAccess::normalize_path(name); - Map<String, Vector<uint8_t> >::Element* E = files->find(name); + Map<String, Vector<uint8_t> >::Element *E = files->find(name); ERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND); data = &(E->get()[0]); @@ -149,7 +147,7 @@ uint8_t FileAccessMemory::get_8() const { return ret; } -int FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessMemory::get_buffer(uint8_t *p_dst, int p_length) const { ERR_FAIL_COND_V(!data, -1); @@ -178,7 +176,7 @@ void FileAccessMemory::store_8(uint8_t p_byte) { data[pos++] = p_byte; } -void FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessMemory::store_buffer(const uint8_t *p_src, int p_length) { int left = length - pos; int write = MIN(p_length, left); diff --git a/core/io/file_access_memory.h b/core/io/file_access_memory.h index c6dda0797..687e3e9be 100644 --- a/core/io/file_access_memory.h +++ b/core/io/file_access_memory.h @@ -33,19 +33,18 @@ class FileAccessMemory : public FileAccess { - uint8_t* data; + uint8_t *data; int length; mutable int pos; - static FileAccess* create(); + static FileAccess *create(); public: - static void register_file(String p_name, Vector<uint8_t> p_data); static void cleanup(); - virtual Error open_custom(const uint8_t* p_data, int p_len); ///< open a file - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error open_custom(const uint8_t *p_data, int p_len); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open @@ -58,18 +57,16 @@ public: virtual uint8_t get_8() const; ///< get a byte - virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes + virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes - - virtual bool file_exists(const String& p_name); ///< return true if a file exists - - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } + virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes + virtual bool file_exists(const String &p_name); ///< return true if a file exists + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } FileAccessMemory(); }; diff --git a/core/io/file_access_network.cpp b/core/io/file_access_network.cpp index 3516ad880..1b7a052de 100644 --- a/core/io/file_access_network.cpp +++ b/core/io/file_access_network.cpp @@ -27,19 +27,16 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "file_access_network.h" -#include "marshalls.h" #include "globals.h" -#include "os/os.h" #include "io/ip.h" - - +#include "marshalls.h" +#include "os/os.h" //#define DEBUG_PRINT(m_p) print_line(m_p) //#define DEBUG_TIME(m_what) printf("MS: %s - %lli\n",m_what,OS::get_singleton()->get_ticks_usec()); #define DEBUG_PRINT(m_p) #define DEBUG_TIME(m_what) - void FileAccessNetworkClient::lock_mutex() { mutex->lock(); @@ -50,59 +47,55 @@ void FileAccessNetworkClient::unlock_mutex() { lockcount--; mutex->unlock(); - } void FileAccessNetworkClient::put_32(int p_32) { uint8_t buf[4]; - encode_uint32(p_32,buf); - client->put_data(buf,4); - DEBUG_PRINT("put32: "+itos(p_32)); + encode_uint32(p_32, buf); + client->put_data(buf, 4); + DEBUG_PRINT("put32: " + itos(p_32)); } void FileAccessNetworkClient::put_64(int64_t p_64) { uint8_t buf[8]; - encode_uint64(p_64,buf); - client->put_data(buf,8); - DEBUG_PRINT("put64: "+itos(p_64)); - + encode_uint64(p_64, buf); + client->put_data(buf, 8); + DEBUG_PRINT("put64: " + itos(p_64)); } int FileAccessNetworkClient::get_32() { uint8_t buf[4]; - client->get_data(buf,4); + client->get_data(buf, 4); return decode_uint32(buf); - } int64_t FileAccessNetworkClient::get_64() { uint8_t buf[8]; - client->get_data(buf,8); + client->get_data(buf, 8); return decode_uint64(buf); - } void FileAccessNetworkClient::_thread_func() { client->set_nodelay(true); - while(!quit) { + while (!quit) { - DEBUG_PRINT("SEM WAIT - "+itos(sem->get())); + DEBUG_PRINT("SEM WAIT - " + itos(sem->get())); Error err = sem->wait(); DEBUG_TIME("sem_unlock"); //DEBUG_PRINT("semwait returned "+itos(werr)); - DEBUG_PRINT("MUTEX LOCK "+itos(lockcount)); + DEBUG_PRINT("MUTEX LOCK " + itos(lockcount)); DEBUG_PRINT("POPO"); DEBUG_PRINT("PEPE"); lock_mutex(); DEBUG_PRINT("MUTEX PASS"); blockrequest_mutex->lock(); - while(block_requests.size()) { + while (block_requests.size()) { put_32(block_requests.front()->get().id); put_32(FileAccessNetwork::COMMAND_READ_BLOCK); put_64(block_requests.front()->get().offset); @@ -117,35 +110,32 @@ void FileAccessNetworkClient::_thread_func() { int id = get_32(); int response = get_32(); - DEBUG_PRINT("GET RESPONSE: "+itos(response)); + DEBUG_PRINT("GET RESPONSE: " + itos(response)); - FileAccessNetwork *fa=NULL; + FileAccessNetwork *fa = NULL; - if (response!=FileAccessNetwork::RESPONSE_DATA) { + if (response != FileAccessNetwork::RESPONSE_DATA) { ERR_FAIL_COND(!accesses.has(id)); } if (accesses.has(id)) - fa=accesses[id]; + fa = accesses[id]; - - switch(response) { + switch (response) { case FileAccessNetwork::RESPONSE_OPEN: { - DEBUG_TIME("sem_open"); int status = get_32(); - if (status!=OK) { - fa->_respond(0,Error(status)); + if (status != OK) { + fa->_respond(0, Error(status)); } else { uint64_t len = get_64(); - fa->_respond(len,Error(status)); + fa->_respond(len, Error(status)); } fa->sem->post(); - } break; case FileAccessNetwork::RESPONSE_DATA: { @@ -154,104 +144,95 @@ void FileAccessNetworkClient::_thread_func() { Vector<uint8_t> block; block.resize(len); - client->get_data(block.ptr(),len); + client->get_data(block.ptr(), len); if (fa) //may have been queued - fa->_set_block(offset,block); + fa->_set_block(offset, block); } break; case FileAccessNetwork::RESPONSE_FILE_EXISTS: { - int status = get_32(); - fa->exists_modtime=status!=0; + fa->exists_modtime = status != 0; fa->sem->post(); - - } break; case FileAccessNetwork::RESPONSE_GET_MODTIME: { - uint64_t status = get_64(); - fa->exists_modtime=status; + fa->exists_modtime = status; fa->sem->post(); } break; - } - unlock_mutex(); } - } void FileAccessNetworkClient::_thread_func(void *s) { - FileAccessNetworkClient *self =(FileAccessNetworkClient*)s; + FileAccessNetworkClient *self = (FileAccessNetworkClient *)s; self->_thread_func(); - } -Error FileAccessNetworkClient::connect(const String& p_host,int p_port,const String& p_password) { +Error FileAccessNetworkClient::connect(const String &p_host, int p_port, const String &p_password) { IP_Address ip; if (p_host.is_valid_ip_address()) { - ip=p_host; + ip = p_host; } else { - ip=IP::get_singleton()->resolve_hostname(p_host); + ip = IP::get_singleton()->resolve_hostname(p_host); } - DEBUG_PRINT("IP: "+String(ip)+" port "+itos(p_port)); - Error err = client->connect(ip,p_port); - ERR_FAIL_COND_V(err,err); - while(client->get_status()==StreamPeerTCP::STATUS_CONNECTING) { -//DEBUG_PRINT("trying to connect...."); + DEBUG_PRINT("IP: " + String(ip) + " port " + itos(p_port)); + Error err = client->connect(ip, p_port); + ERR_FAIL_COND_V(err, err); + while (client->get_status() == StreamPeerTCP::STATUS_CONNECTING) { + //DEBUG_PRINT("trying to connect...."); OS::get_singleton()->delay_usec(1000); } - if (client->get_status()!=StreamPeerTCP::STATUS_CONNECTED) { + if (client->get_status() != StreamPeerTCP::STATUS_CONNECTED) { return ERR_CANT_CONNECT; } CharString cs = p_password.utf8(); put_32(cs.length()); - client->put_data((const uint8_t*)cs.ptr(),cs.length()); + client->put_data((const uint8_t *)cs.ptr(), cs.length()); int e = get_32(); - if (e!=OK) { + if (e != OK) { return ERR_INVALID_PARAMETER; } - thread = Thread::create(_thread_func,this); + thread = Thread::create(_thread_func, this); return OK; } -FileAccessNetworkClient *FileAccessNetworkClient::singleton=NULL; - +FileAccessNetworkClient *FileAccessNetworkClient::singleton = NULL; FileAccessNetworkClient::FileAccessNetworkClient() { - thread=NULL; + thread = NULL; mutex = Mutex::create(); blockrequest_mutex = Mutex::create(); - quit=false; - singleton=this; - last_id=0; - client = Ref<StreamPeerTCP>( StreamPeerTCP::create_ref() ); - sem=Semaphore::create(); - lockcount=0; + quit = false; + singleton = this; + last_id = 0; + client = Ref<StreamPeerTCP>(StreamPeerTCP::create_ref()); + sem = Semaphore::create(); + lockcount = 0; } FileAccessNetworkClient::~FileAccessNetworkClient() { if (thread) { - quit=true; + quit = true; sem->post(); Thread::wait_to_finish(thread); memdelete(thread); @@ -260,72 +241,64 @@ FileAccessNetworkClient::~FileAccessNetworkClient() { memdelete(blockrequest_mutex); memdelete(mutex); memdelete(sem); - - } -void FileAccessNetwork::_set_block(size_t p_offset,const Vector<uint8_t>& p_block) { +void FileAccessNetwork::_set_block(size_t p_offset, const Vector<uint8_t> &p_block) { - - int page = p_offset/page_size; - ERR_FAIL_INDEX(page,pages.size()); - if (page<pages.size()-1) { - ERR_FAIL_COND(p_block.size()!=page_size); + int page = p_offset / page_size; + ERR_FAIL_INDEX(page, pages.size()); + if (page < pages.size() - 1) { + ERR_FAIL_COND(p_block.size() != page_size); } else { - ERR_FAIL_COND( (p_block.size() != (total_size%page_size))); + ERR_FAIL_COND((p_block.size() != (total_size % page_size))); } buffer_mutex->lock(); - pages[page].buffer=p_block; - pages[page].queued=false; + pages[page].buffer = p_block; + pages[page].queued = false; buffer_mutex->unlock(); - if (waiting_on_page==page) { - waiting_on_page=-1; + if (waiting_on_page == page) { + waiting_on_page = -1; page_sem->post(); } } +void FileAccessNetwork::_respond(size_t p_len, Error p_status) { -void FileAccessNetwork::_respond(size_t p_len,Error p_status) { - - DEBUG_PRINT("GOT RESPONSE - len: "+itos(p_len)+" status: "+itos(p_status)); - response=p_status; - if (response!=OK) + DEBUG_PRINT("GOT RESPONSE - len: " + itos(p_len) + " status: " + itos(p_status)); + response = p_status; + if (response != OK) return; - opened=true; - total_size=p_len; - int pc = ((total_size-1)/page_size)+1; + opened = true; + total_size = p_len; + int pc = ((total_size - 1) / page_size) + 1; pages.resize(pc); - - - - } -Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) { +Error FileAccessNetwork::_open(const String &p_path, int p_mode_flags) { - ERR_FAIL_COND_V(p_mode_flags!=READ,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(p_mode_flags != READ, ERR_UNAVAILABLE); if (opened) close(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - DEBUG_PRINT("open: "+p_path); + DEBUG_PRINT("open: " + p_path); DEBUG_TIME("open_begin"); nc->lock_mutex(); nc->put_32(id); - nc->accesses[id]=this; + nc->accesses[id] = this; nc->put_32(COMMAND_OPEN_FILE); - CharString cs =p_path.utf8(); + CharString cs = p_path.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); - pos=0; - eof_flag=false; - last_page=-1; - last_page_buff=NULL; + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); + pos = 0; + eof_flag = false; + last_page = -1; + last_page_buff = NULL; -// buffers.clear(); + // buffers.clear(); nc->unlock_mutex(); DEBUG_PRINT("OPEN POST"); DEBUG_TIME("open_post"); @@ -338,7 +311,7 @@ Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) { return response; } -void FileAccessNetwork::close(){ +void FileAccessNetwork::close() { if (!opened) return; @@ -350,110 +323,103 @@ void FileAccessNetwork::close(){ nc->put_32(id); nc->put_32(COMMAND_CLOSE); pages.clear(); - opened=false; + opened = false; nc->unlock_mutex(); - - } -bool FileAccessNetwork::is_open() const{ +bool FileAccessNetwork::is_open() const { return opened; } -void FileAccessNetwork::seek(size_t p_position){ +void FileAccessNetwork::seek(size_t p_position) { ERR_FAIL_COND(!opened); - eof_flag=p_position>total_size; + eof_flag = p_position > total_size; - if (p_position>=total_size) { - p_position=total_size; + if (p_position >= total_size) { + p_position = total_size; } - pos=p_position; + pos = p_position; } -void FileAccessNetwork::seek_end(int64_t p_position){ - - seek(total_size+p_position); +void FileAccessNetwork::seek_end(int64_t p_position) { + seek(total_size + p_position); } -size_t FileAccessNetwork::get_pos() const{ +size_t FileAccessNetwork::get_pos() const { - ERR_FAIL_COND_V(!opened,0); + ERR_FAIL_COND_V(!opened, 0); return pos; } -size_t FileAccessNetwork::get_len() const{ +size_t FileAccessNetwork::get_len() const { - ERR_FAIL_COND_V(!opened,0); + ERR_FAIL_COND_V(!opened, 0); return total_size; } -bool FileAccessNetwork::eof_reached() const{ +bool FileAccessNetwork::eof_reached() const { - ERR_FAIL_COND_V(!opened,false); + ERR_FAIL_COND_V(!opened, false); return eof_flag; } -uint8_t FileAccessNetwork::get_8() const{ +uint8_t FileAccessNetwork::get_8() const { uint8_t v; - get_buffer(&v,1); + get_buffer(&v, 1); return v; - } - void FileAccessNetwork::_queue_page(int p_page) const { - if (p_page>=pages.size()) + if (p_page >= pages.size()) return; if (pages[p_page].buffer.empty() && !pages[p_page].queued) { - FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->blockrequest_mutex->lock(); FileAccessNetworkClient::BlockRequest br; - br.id=id; - br.offset=size_t(p_page)*page_size; - br.size=page_size; + br.id = id; + br.offset = size_t(p_page) * page_size; + br.size = page_size; nc->block_requests.push_back(br); - pages[p_page].queued=true; + pages[p_page].queued = true; nc->blockrequest_mutex->unlock(); DEBUG_PRINT("QUEUE PAGE POST"); nc->sem->post(); - DEBUG_PRINT("queued "+itos(p_page)); + DEBUG_PRINT("queued " + itos(p_page)); } - } -int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{ +int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const { //bool eof=false; - if (pos+p_length>total_size) { - eof_flag=true; + if (pos + p_length > total_size) { + eof_flag = true; } - if (pos+p_length>=total_size) { - p_length=total_size-pos; + if (pos + p_length >= total_size) { + p_length = total_size - pos; } -// FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; + // FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; - uint8_t *buff=last_page_buff; + uint8_t *buff = last_page_buff; - for(int i=0;i<p_length;i++) { + for (int i = 0; i < p_length; i++) { - int page=pos/page_size; + int page = pos / page_size; - if (page!=last_page) { + if (page != last_page) { buffer_mutex->lock(); if (pages[page].buffer.empty()) { //fuck - waiting_on_page=page; - for(int j=0;j<read_ahead;j++) { + waiting_on_page = page; + for (int j = 0; j < read_ahead; j++) { - _queue_page(page+j); + _queue_page(page + j); } buffer_mutex->unlock(); DEBUG_PRINT("wait"); @@ -461,30 +427,30 @@ int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{ DEBUG_PRINT("done"); } else { - for(int j=0;j<read_ahead;j++) { + for (int j = 0; j < read_ahead; j++) { - _queue_page(page+j); + _queue_page(page + j); } - buff=pages[page].buffer.ptr(); + buff = pages[page].buffer.ptr(); //queue pages buffer_mutex->unlock(); } - buff=pages[page].buffer.ptr(); - last_page_buff=buff; - last_page=page; + buff = pages[page].buffer.ptr(); + last_page_buff = buff; + last_page = page; } - p_dst[i]=buff[pos-uint64_t(page)*page_size]; + p_dst[i] = buff[pos - uint64_t(page) * page_size]; pos++; } return p_length; } -Error FileAccessNetwork::get_error() const{ +Error FileAccessNetwork::get_error() const { - return pos==total_size?ERR_FILE_EOF:OK; + return pos == total_size ? ERR_FILE_EOF : OK; } void FileAccessNetwork::store_8(uint8_t p_dest) { @@ -492,63 +458,59 @@ void FileAccessNetwork::store_8(uint8_t p_dest) { ERR_FAIL(); } -bool FileAccessNetwork::file_exists(const String& p_path){ +bool FileAccessNetwork::file_exists(const String &p_path) { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); nc->put_32(id); nc->put_32(COMMAND_FILE_EXISTS); - CharString cs=p_path.utf8(); + CharString cs = p_path.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); nc->unlock_mutex(); DEBUG_PRINT("FILE EXISTS POST"); nc->sem->post(); sem->wait(); - return exists_modtime!=0; - + return exists_modtime != 0; } -uint64_t FileAccessNetwork::_get_modified_time(const String& p_file){ +uint64_t FileAccessNetwork::_get_modified_time(const String &p_file) { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); nc->put_32(id); nc->put_32(COMMAND_GET_MODTIME); - CharString cs=p_file.utf8(); + CharString cs = p_file.utf8(); nc->put_32(cs.length()); - nc->client->put_data((const uint8_t*)cs.ptr(),cs.length()); + nc->client->put_data((const uint8_t *)cs.ptr(), cs.length()); nc->unlock_mutex(); DEBUG_PRINT("MODTIME POST"); nc->sem->post(); sem->wait(); return exists_modtime; - } FileAccessNetwork::FileAccessNetwork() { - eof_flag=false; - opened=false; - pos=0; - sem=Semaphore::create(); - page_sem=Semaphore::create(); - buffer_mutex=Mutex::create(); + eof_flag = false; + opened = false; + pos = 0; + sem = Semaphore::create(); + page_sem = Semaphore::create(); + buffer_mutex = Mutex::create(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); - id=nc->last_id++; - nc->accesses[id]=this; + id = nc->last_id++; + nc->accesses[id] = this; nc->unlock_mutex(); - page_size = GLOBAL_DEF("remote_fs/page_size",65536); - read_ahead = GLOBAL_DEF("remote_fs/page_read_ahead",4); - max_pages = GLOBAL_DEF("remote_fs/max_pages",20); - last_activity_val=0; - waiting_on_page=-1; - last_page=-1; - - + page_size = GLOBAL_DEF("remote_fs/page_size", 65536); + read_ahead = GLOBAL_DEF("remote_fs/page_read_ahead", 4); + max_pages = GLOBAL_DEF("remote_fs/max_pages", 20); + last_activity_val = 0; + waiting_on_page = -1; + last_page = -1; } FileAccessNetwork::~FileAccessNetwork() { @@ -560,8 +522,7 @@ FileAccessNetwork::~FileAccessNetwork() { FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); - id=nc->last_id++; + id = nc->last_id++; nc->accesses.erase(id); nc->unlock_mutex(); - } diff --git a/core/io/file_access_network.h b/core/io/file_access_network.h index 867991bcb..a77053184 100644 --- a/core/io/file_access_network.h +++ b/core/io/file_access_network.h @@ -29,16 +29,15 @@ #ifndef FILE_ACCESS_NETWORK_H #define FILE_ACCESS_NETWORK_H +#include "io/stream_peer_tcp.h" #include "os/file_access.h" #include "os/semaphore.h" #include "os/thread.h" -#include "io/stream_peer_tcp.h" class FileAccessNetwork; class FileAccessNetworkClient { - struct BlockRequest { int id; @@ -55,7 +54,7 @@ class FileAccessNetworkClient { bool quit; Mutex *mutex; Mutex *blockrequest_mutex; - Map<int,FileAccessNetwork*> accesses; + Map<int, FileAccessNetwork *> accesses; Ref<StreamPeerTCP> client; int last_id; @@ -72,18 +71,16 @@ class FileAccessNetworkClient { void lock_mutex(); void unlock_mutex(); -friend class FileAccessNetwork; + friend class FileAccessNetwork; static FileAccessNetworkClient *singleton; public: - static FileAccessNetworkClient *get_singleton() { return singleton; } - Error connect(const String& p_host,int p_port,const String& p_password=""); + Error connect(const String &p_host, int p_port, const String &p_password = ""); FileAccessNetworkClient(); ~FileAccessNetworkClient(); - }; class FileAccessNetwork : public FileAccess { @@ -109,21 +106,23 @@ class FileAccessNetwork : public FileAccess { int activity; bool queued; Vector<uint8_t> buffer; - Page() { activity=0; queued=false; } + Page() { + activity = 0; + queued = false; + } }; - mutable Vector< Page > pages; + mutable Vector<Page> pages; mutable Error response; uint64_t exists_modtime; -friend class FileAccessNetworkClient; + friend class FileAccessNetworkClient; void _queue_page(int p_page) const; - void _respond(size_t p_len,Error p_status); - void _set_block(size_t p_offset,const Vector<uint8_t>& p_block); + void _respond(size_t p_len, Error p_status); + void _set_block(size_t p_offset, const Vector<uint8_t> &p_block); public: - enum Command { COMMAND_OPEN_FILE, COMMAND_READ_BLOCK, @@ -139,13 +138,12 @@ public: RESPONSE_GET_MODTIME, }; - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file @@ -158,9 +156,9 @@ public: virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_path); ///< return true if a file exists + virtual bool file_exists(const String &p_path); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file); + virtual uint64_t _get_modified_time(const String &p_file); FileAccessNetwork(); ~FileAccessNetwork(); diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp index e6d22fd38..d32d695ff 100644 --- a/core/io/file_access_pack.cpp +++ b/core/io/file_access_pack.cpp @@ -33,9 +33,9 @@ #define PACK_VERSION 0 -Error PackedData::add_pack(const String& p_path) { +Error PackedData::add_pack(const String &p_path) { - for (int i=0; i<sources.size(); i++) { + for (int i = 0; i < sources.size(); i++) { if (sources[i]->try_open_pack(p_path)) { @@ -46,7 +46,7 @@ Error PackedData::add_pack(const String& p_path) { return ERR_FILE_UNRECOGNIZED; }; -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) { +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) { PathMD5 pmd5(path.md5_buffer()); //printf("adding path %ls, %lli, %lli\n", path.c_str(), pmd5.a, pmd5.b); @@ -54,35 +54,35 @@ void PackedData::add_path(const String& pkg_path, const String& path, uint64_t o bool exists = files.has(pmd5); 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.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[pmd5]=pf; + files[pmd5] = pf; if (!exists) { //search for dir - String p = path.replace_first("res://",""); - PackedDir *cd=root; + String p = path.replace_first("res://", ""); + PackedDir *cd = root; - if (p.find("/")!=-1) { //in a subdir + if (p.find("/") != -1) { //in a subdir - Vector<String> ds=p.get_base_dir().split("/"); + Vector<String> ds = p.get_base_dir().split("/"); - for(int j=0;j<ds.size();j++) { + 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; + 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 = cd->subdirs[ds[j]]; } } } @@ -97,61 +97,59 @@ void PackedData::add_pack_source(PackSource *p_source) { } }; -PackedData *PackedData::singleton=NULL; +PackedData *PackedData::singleton = NULL; PackedData::PackedData() { - singleton=this; - root=memnew(PackedDir); - root->parent=NULL; - disabled=false; + singleton = this; + root = memnew(PackedDir); + root->parent = NULL; + disabled = false; add_pack_source(memnew(PackedSourcePCK)); } void PackedData::_free_packed_dirs(PackedDir *p_dir) { - for (Map<String,PackedDir*>::Element *E=p_dir->subdirs.front();E;E=E->next()) + for (Map<String, PackedDir *>::Element *E = p_dir->subdirs.front(); E; E = E->next()) _free_packed_dirs(E->get()); memdelete(p_dir); } PackedData::~PackedData() { - for(int i=0;i<sources.size();i++) { + for (int i = 0; i < sources.size(); i++) { memdelete(sources[i]); } _free_packed_dirs(root); } - ////////////////////////////////////////////////////////////////// -bool PackedSourcePCK::try_open_pack(const String& p_path) { +bool PackedSourcePCK::try_open_pack(const String &p_path) { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) return false; //printf("try open %ls!\n", p_path.c_str()); - uint32_t magic= f->get_32(); + uint32_t magic = f->get_32(); if (magic != 0x43504447) { //maybe at he end.... self contained exe f->seek_end(); - f->seek( f->get_pos() -4 ); + f->seek(f->get_pos() - 4); magic = f->get_32(); if (magic != 0x43504447) { memdelete(f); return false; } - f->seek( f->get_pos() -12 ); - + f->seek(f->get_pos() - 12); uint64_t ds = f->get_64(); - f->seek( f->get_pos() -ds-8 ); + f->seek(f->get_pos() - ds - 8); magic = f->get_32(); if (magic != 0x43504447) { @@ -159,7 +157,6 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { memdelete(f); return false; } - } uint32_t version = f->get_32(); @@ -167,25 +164,25 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { uint32_t ver_minor = f->get_32(); uint32_t ver_rev = f->get_32(); - ERR_EXPLAIN("Pack version newer than supported by engine: "+itos(version)); - ERR_FAIL_COND_V( version > PACK_VERSION, ERR_INVALID_DATA); - ERR_EXPLAIN("Pack created with a newer version of the engine: "+itos(ver_major)+"."+itos(ver_minor)+"."+itos(ver_rev)); - ERR_FAIL_COND_V( ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA); + ERR_EXPLAIN("Pack version newer than supported by engine: " + itos(version)); + ERR_FAIL_COND_V(version > PACK_VERSION, ERR_INVALID_DATA); + ERR_EXPLAIN("Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "." + itos(ver_rev)); + ERR_FAIL_COND_V(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA); - for(int i=0;i<16;i++) { + for (int i = 0; i < 16; i++) { //reserved f->get_32(); } int file_count = f->get_32(); - for(int i=0;i<file_count;i++) { + for (int i = 0; i < file_count; i++) { uint32_t sl = f->get_32(); CharString cs; - cs.resize(sl+1); - f->get_buffer((uint8_t*)cs.ptr(),sl); - cs[sl]=0; + cs.resize(sl + 1); + f->get_buffer((uint8_t *)cs.ptr(), sl); + cs[sl] = 0; String path; path.parse_utf8(cs.ptr()); @@ -193,22 +190,21 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) { uint64_t ofs = f->get_64(); uint64_t size = f->get_64(); uint8_t md5[16]; - f->get_buffer(md5,16); - PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5,this); + f->get_buffer(md5, 16); + PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this); }; return true; }; -FileAccess* PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile* p_file) { +FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { - return memnew( FileAccessPack(p_path, *p_file)); + return memnew(FileAccessPack(p_path, *p_file)); }; ////////////////////////////////////////////////////////////////// - -Error FileAccessPack::_open(const String& p_path, int p_mode_flags) { +Error FileAccessPack::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_V(ERR_UNAVAILABLE); return ERR_UNAVAILABLE; @@ -219,45 +215,44 @@ void FileAccessPack::close() { f->close(); } -bool FileAccessPack::is_open() const{ +bool FileAccessPack::is_open() const { return f->is_open(); } -void FileAccessPack::seek(size_t p_position){ +void FileAccessPack::seek(size_t p_position) { - if (p_position>pf.size) { - eof=true; + if (p_position > pf.size) { + eof = true; } else { - eof=false; + eof = false; } - f->seek(pf.offset+p_position); - pos=p_position; + f->seek(pf.offset + p_position); + pos = p_position; } -void FileAccessPack::seek_end(int64_t p_position){ - - seek(pf.size+p_position); +void FileAccessPack::seek_end(int64_t p_position) { + seek(pf.size + p_position); } size_t FileAccessPack::get_pos() const { return pos; } -size_t FileAccessPack::get_len() const{ +size_t FileAccessPack::get_len() const { return pf.size; } -bool FileAccessPack::eof_reached() const{ +bool FileAccessPack::eof_reached() const { return eof; } uint8_t FileAccessPack::get_8() const { - if (pos>=pf.size) { - eof=true; + if (pos >= pf.size) { + eof = true; return 0; } @@ -265,23 +260,22 @@ uint8_t FileAccessPack::get_8() const { return f->get_8(); } - -int FileAccessPack::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessPack::get_buffer(uint8_t *p_dst, int p_length) const { if (eof) return 0; - int64_t to_read=p_length; - if (to_read+pos > pf.size) { - eof=true; - to_read=int64_t(pf.size)-int64_t(pos); + int64_t to_read = p_length; + if (to_read + pos > pf.size) { + eof = true; + to_read = int64_t(pf.size) - int64_t(pos); } - pos+=p_length; + pos += p_length; - if (to_read<=0) + if (to_read <= 0) return 0; - f->get_buffer(p_dst,to_read); + f->get_buffer(p_dst, to_read); return to_read; } @@ -301,32 +295,29 @@ Error FileAccessPack::get_error() const { void FileAccessPack::store_8(uint8_t p_dest) { ERR_FAIL(); - } -void FileAccessPack::store_buffer(const uint8_t *p_src,int p_length) { +void FileAccessPack::store_buffer(const uint8_t *p_src, int p_length) { ERR_FAIL(); - } -bool FileAccessPack::file_exists(const String& p_name) { +bool FileAccessPack::file_exists(const String &p_name) { return false; } +FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) { -FileAccessPack::FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file) { - - pf=p_file; - f=FileAccess::open(pf.pack,FileAccess::READ); + pf = p_file; + f = FileAccess::open(pf.pack, FileAccess::READ); if (!f) { - ERR_EXPLAIN("Can't open pack-referenced file: "+String(pf.pack)); + ERR_EXPLAIN("Can't open pack-referenced file: " + String(pf.pack)); ERR_FAIL_COND(!f); } f->seek(pf.offset); - pos=0; - eof=false; + pos = 0; + eof = false; } FileAccessPack::~FileAccessPack() { @@ -334,24 +325,21 @@ FileAccessPack::~FileAccessPack() { memdelete(f); } - ////////////////////////////////////////////////////////////////////////////////// // DIR ACCESS ////////////////////////////////////////////////////////////////////////////////// - bool DirAccessPack::list_dir_begin() { - list_dirs.clear(); list_files.clear(); - for (Map<String,PackedData::PackedDir*>::Element *E=current->subdirs.front();E;E=E->next()) { + for (Map<String, PackedData::PackedDir *>::Element *E = current->subdirs.front(); E; E = E->next()) { list_dirs.push_back(E->key()); } - for (Set<String>::Element *E=current->files.front();E;E=E->next()) { + for (Set<String>::Element *E = current->files.front(); E; E = E->next()) { list_files.push_back(E->get()); } @@ -359,15 +347,15 @@ bool DirAccessPack::list_dir_begin() { return true; } -String DirAccessPack::get_next(){ +String DirAccessPack::get_next() { if (list_dirs.size()) { - cdir=true; + cdir = true; String d = list_dirs.front()->get(); list_dirs.pop_front(); return d; } else if (list_files.size()) { - cdir=false; + cdir = false; String f = list_files.front()->get(); list_files.pop_front(); return f; @@ -375,11 +363,11 @@ String DirAccessPack::get_next(){ return String(); } } -bool DirAccessPack::current_is_dir() const{ +bool DirAccessPack::current_is_dir() const { return cdir; } -bool DirAccessPack::current_is_hidden() const{ +bool DirAccessPack::current_is_hidden() const { return false; } @@ -400,18 +388,18 @@ String DirAccessPack::get_drive(int p_drive) { Error DirAccessPack::change_dir(String p_dir) { - String nd = p_dir.replace("\\","/"); - bool absolute=false; + String nd = p_dir.replace("\\", "/"); + bool absolute = false; if (nd.begins_with("res://")) { - nd=nd.replace_first("res://",""); - absolute=true; + nd = nd.replace_first("res://", ""); + absolute = true; } - nd=nd.simplify_path(); + nd = nd.simplify_path(); if (nd.begins_with("/")) { - nd=nd.replace_first("/","") ; - absolute=true; + nd = nd.replace_first("/", ""); + absolute = true; } Vector<String> paths = nd.split("/"); @@ -423,18 +411,18 @@ Error DirAccessPack::change_dir(String p_dir) { else pd = current; - for(int i=0;i<paths.size();i++) { + for (int i = 0; i < paths.size(); i++) { String p = paths[i]; - if (p==".") { + if (p == ".") { continue; - } else if (p=="..") { + } else if (p == "..") { if (pd->parent) { - pd=pd->parent; + pd = pd->parent; } } else if (pd->subdirs.has(p)) { - pd=pd->subdirs[p]; + pd = pd->subdirs[p]; } else { @@ -442,29 +430,26 @@ Error DirAccessPack::change_dir(String p_dir) { } } - current=pd; + current = pd; return OK; - - } String DirAccessPack::get_current_dir() { String p; PackedData::PackedDir *pd = current; - while(pd->parent) { + while (pd->parent) { - if (pd!=current) - p="/"+p; - p=p+pd->name; + if (pd != current) + p = "/" + p; + p = p + pd->name; } - return "res://"+p; - + return "res://" + p; } -bool DirAccessPack::file_exists(String p_file){ +bool DirAccessPack::file_exists(String p_file) { return current->files.has(p_file); } @@ -474,36 +459,30 @@ bool DirAccessPack::dir_exists(String p_dir) { return current->subdirs.has(p_dir); } -Error DirAccessPack::make_dir(String p_dir){ +Error DirAccessPack::make_dir(String p_dir) { return ERR_UNAVAILABLE; } -Error DirAccessPack::rename(String p_from, String p_to){ +Error DirAccessPack::rename(String p_from, String p_to) { return ERR_UNAVAILABLE; - } -Error DirAccessPack::remove(String p_name){ +Error DirAccessPack::remove(String p_name) { return ERR_UNAVAILABLE; - } -size_t DirAccessPack::get_space_left(){ +size_t DirAccessPack::get_space_left() { return 0; } DirAccessPack::DirAccessPack() { - current=PackedData::get_singleton()->root; - cdir=false; + current = PackedData::get_singleton()->root; + cdir = false; } DirAccessPack::~DirAccessPack() { - - } - - diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h index 83340a662..017bef94c 100644 --- a/core/io/file_access_pack.h +++ b/core/io/file_access_pack.h @@ -29,18 +29,18 @@ #ifndef FILE_ACCESS_PACK_H #define FILE_ACCESS_PACK_H -#include "os/file_access.h" -#include "os/dir_access.h" -#include "map.h" #include "list.h" +#include "map.h" +#include "os/dir_access.h" +#include "os/file_access.h" #include "print_string.h" class PackSource; class PackedData { -friend class FileAccessPack; -friend class DirAccessPack; -friend class PackSource; + friend class FileAccessPack; + friend class DirAccessPack; + friend class PackSource; public: struct PackedFile { @@ -49,21 +49,21 @@ public: uint64_t offset; //if offset is ZERO, the file was ERASED uint64_t size; uint8_t md5[16]; - PackSource* src; + PackSource *src; }; private: struct PackedDir { PackedDir *parent; String name; - Map<String,PackedDir*> subdirs; + Map<String, PackedDir *> subdirs; Set<String> files; }; struct PathMD5 { uint64_t a; uint64_t b; - bool operator < (const PathMD5& p_md5) const { + bool operator<(const PathMD5 &p_md5) const { if (p_md5.a == a) { return b < p_md5.b; @@ -72,7 +72,7 @@ private: } } - bool operator == (const PathMD5& p_md5) const { + bool operator==(const PathMD5 &p_md5) const { return a == p_md5.a && b == p_md5.b; }; @@ -81,14 +81,14 @@ private: }; PathMD5(const Vector<uint8_t> p_buf) { - a = *((uint64_t*)&p_buf[0]); - b = *((uint64_t*)&p_buf[8]); + a = *((uint64_t *)&p_buf[0]); + b = *((uint64_t *)&p_buf[8]); }; }; - Map<PathMD5,PackedFile> files; + Map<PathMD5, PackedFile> files; - Vector<PackSource*> sources; + Vector<PackSource *> sources; PackedDir *root; //Map<String,PackedDir*> dirs; @@ -99,18 +99,17 @@ private: void _free_packed_dirs(PackedDir *p_dir); public: + void add_pack_source(PackSource *p_source); + void add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src); // for PackSource - void add_pack_source(PackSource* p_source); - void add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src); // for PackSource - - void set_disabled(bool p_disabled) { disabled=p_disabled; } + void set_disabled(bool p_disabled) { disabled = p_disabled; } _FORCE_INLINE_ bool is_disabled() const { return disabled; } static PackedData *get_singleton() { return singleton; } - Error add_pack(const String& p_path); + Error add_pack(const String &p_path); - _FORCE_INLINE_ FileAccess *try_open_path(const String& p_path); - _FORCE_INLINE_ bool has_path(const String& p_path); + _FORCE_INLINE_ FileAccess *try_open_path(const String &p_path); + _FORCE_INLINE_ bool has_path(const String &p_path); PackedData(); ~PackedData(); @@ -119,21 +118,18 @@ public: class PackSource { public: - - virtual bool try_open_pack(const String& p_path)=0; - virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file)=0; + virtual bool try_open_pack(const String &p_path) = 0; + virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file) = 0; virtual ~PackSource() {} }; class PackedSourcePCK : public PackSource { public: - virtual bool try_open_pack(const String &p_path); - virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file); + virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); }; - class FileAccessPack : public FileAccess { PackedData::PackedFile pf; @@ -142,17 +138,15 @@ class FileAccessPack : public FileAccess { mutable bool eof; FileAccess *f; - virtual Error _open(const String& p_path, int p_mode_flags); - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } + virtual Error _open(const String &p_path, int p_mode_flags); + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } public: - - virtual void close(); virtual bool is_open() const; virtual void seek(size_t p_position); - virtual void seek_end(int64_t p_position=0); + virtual void seek_end(int64_t p_position = 0); virtual size_t get_pos() const; virtual size_t get_len() const; @@ -160,8 +154,7 @@ public: virtual uint8_t get_8() const; - - virtual int get_buffer(uint8_t *p_dst,int p_length) const; + virtual int get_buffer(uint8_t *p_dst, int p_length) const; virtual void set_endian_swap(bool p_swap); @@ -169,38 +162,34 @@ public: virtual void store_8(uint8_t p_dest); - virtual void store_buffer(const uint8_t *p_src,int p_length); - - virtual bool file_exists(const String& p_name); + virtual void store_buffer(const uint8_t *p_src, int p_length); + virtual bool file_exists(const String &p_name); - FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file); + FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file); ~FileAccessPack(); }; - -FileAccess *PackedData::try_open_path(const String& p_path) { +FileAccess *PackedData::try_open_path(const String &p_path) { //print_line("try open path " + p_path); PathMD5 pmd5(p_path.md5_buffer()); - Map<PathMD5,PackedFile>::Element *E=files.find(pmd5); + Map<PathMD5, PackedFile>::Element *E = files.find(pmd5); if (!E) return NULL; //not found - if (E->get().offset==0) + if (E->get().offset == 0) return NULL; //was erased return E->get().src->get_file(p_path, &E->get()); } -bool PackedData::has_path(const String& p_path) { +bool PackedData::has_path(const String &p_path) { return files.has(PathMD5(p_path.md5_buffer())); } - class DirAccessPack : public DirAccess { - PackedData::PackedDir *current; List<String> list_dirs; @@ -208,7 +197,6 @@ class DirAccessPack : public DirAccess { bool cdir; public: - virtual bool list_dir_begin(); virtual String get_next(); virtual bool current_is_dir() const; @@ -221,7 +209,6 @@ public: virtual Error change_dir(String p_dir); virtual String get_current_dir(); - virtual bool file_exists(String p_file); virtual bool dir_exists(String p_dir); @@ -234,8 +221,6 @@ public: DirAccessPack(); ~DirAccessPack(); - }; - #endif // FILE_ACCESS_PACK_H diff --git a/core/io/file_access_zip.cpp b/core/io/file_access_zip.cpp index c4439f259..fcc19dea2 100644 --- a/core/io/file_access_zip.cpp +++ b/core/io/file_access_zip.cpp @@ -30,78 +30,75 @@ #include "file_access_zip.h" -#include "core/os/file_access.h" #include "core/os/copymem.h" +#include "core/os/file_access.h" -ZipArchive* ZipArchive::instance = NULL; +ZipArchive *ZipArchive::instance = NULL; extern "C" { -static void* godot_open(void* data, const char* p_fname, int mode) { +static void *godot_open(void *data, const char *p_fname, int mode) { if (mode & ZLIB_FILEFUNC_MODE_WRITE) { return NULL; }; - FileAccess* f = (FileAccess*)data; + FileAccess *f = (FileAccess *)data; f->open(p_fname, FileAccess::READ); - return f->is_open()?data:NULL; - + return f->is_open() ? data : NULL; }; -static uLong godot_read(void* data, void* fdata, void* buf, uLong size) { +static uLong godot_read(void *data, void *fdata, void *buf, uLong size) { - FileAccess* f = (FileAccess*)data; - f->get_buffer((uint8_t*)buf, size); + FileAccess *f = (FileAccess *)data; + f->get_buffer((uint8_t *)buf, size); return size; }; -static uLong godot_write(voidpf opaque, voidpf stream, const void* buf, uLong size) { +static uLong godot_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { return 0; }; +static long godot_tell(voidpf opaque, voidpf stream) { -static long godot_tell (voidpf opaque, voidpf stream) { - - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; return f->get_pos(); }; static long godot_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; int pos = offset; switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_pos() + offset; - break; - case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_len() + offset; - break; - default: - break; + case ZLIB_FILEFUNC_SEEK_CUR: + pos = f->get_pos() + offset; + break; + case ZLIB_FILEFUNC_SEEK_END: + pos = f->get_len() + offset; + break; + default: + break; }; f->seek(pos); return 0; }; - static int godot_close(voidpf opaque, voidpf stream) { - FileAccess* f = (FileAccess*)opaque; + FileAccess *f = (FileAccess *)opaque; f->close(); return 0; }; static int godot_testerror(voidpf opaque, voidpf stream) { - FileAccess* f = (FileAccess*)opaque; - return f->get_error()!=OK?1:0; + FileAccess *f = (FileAccess *)opaque; + return f->get_error() != OK ? 1 : 0; }; static voidpf godot_alloc(voidpf opaque, uInt items, uInt size) { @@ -119,7 +116,7 @@ static void godot_free(voidpf opaque, voidpf address) { void ZipArchive::close_handle(unzFile p_file) const { ERR_FAIL_COND(!p_file); - FileAccess* f = (FileAccess*)unzGetOpaque(p_file); + FileAccess *f = (FileAccess *)unzGetOpaque(p_file); unzCloseCurrentFile(p_file); unzClose(p_file); memdelete(f); @@ -130,7 +127,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const { ERR_FAIL_COND_V(!file_exists(p_file), NULL); File file = files[p_file]; - FileAccess* f = FileAccess::open(packages[file.package].filename, FileAccess::READ); + FileAccess *f = FileAccess::open(packages[file.package].filename, FileAccess::READ); ERR_FAIL_COND_V(!f, NULL); zlib_filefunc_def io; @@ -162,7 +159,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const { return pkg; }; -bool ZipArchive::try_open_pack(const String& p_name) { +bool ZipArchive::try_open_pack(const String &p_name) { //printf("opening zip pack %ls, %i, %i\n", p_name.c_str(), p_name.extension().nocasecmp_to("zip"), p_name.extension().nocasecmp_to("pcz")); if (p_name.extension().nocasecmp_to("zip") != 0 && p_name.extension().nocasecmp_to("pcz") != 0) @@ -170,7 +167,7 @@ bool ZipArchive::try_open_pack(const String& p_name) { zlib_filefunc_def io; - FileAccess* f = FileAccess::open(p_name, FileAccess::READ); + FileAccess *f = FileAccess::open(p_name, FileAccess::READ); if (!f) return false; io.opaque = f; @@ -188,20 +185,20 @@ bool ZipArchive::try_open_pack(const String& p_name) { unz_global_info64 gi; int err = unzGetGlobalInfo64(zfile, &gi); - ERR_FAIL_COND_V(err!=UNZ_OK, false); + ERR_FAIL_COND_V(err != UNZ_OK, false); Package pkg; pkg.filename = p_name; pkg.zfile = zfile; packages.push_back(pkg); - int pkg_num = packages.size()-1; + int pkg_num = packages.size() - 1; - for (unsigned int i=0;i<gi.number_entry;i++) { + for (unsigned int i = 0; i < gi.number_entry; i++) { char filename_inzip[256]; unz_file_info64 file_info; - err = unzGetCurrentFileInfo64(zfile,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); + err = unzGetCurrentFileInfo64(zfile, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); ERR_CONTINUE(err != UNZ_OK); File f; @@ -211,11 +208,11 @@ bool ZipArchive::try_open_pack(const String& p_name) { String fname = String("res://") + filename_inzip; files[fname] = f; - uint8_t md5[16]={0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0}; + uint8_t md5[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; PackedData::get_singleton()->add_path(p_name, fname, 1, 0, md5, this); //printf("packed data add path %ls, %ls\n", p_name.c_str(), fname.c_str()); - if ((i+1)<gi.number_entry) { + if ((i + 1) < gi.number_entry) { unzGoToNextFile(zfile); }; }; @@ -228,13 +225,12 @@ bool ZipArchive::file_exists(String p_name) const { return files.has(p_name); }; -FileAccess* ZipArchive::get_file(const String& p_path, PackedData::PackedFile* p_file) { +FileAccess *ZipArchive::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessZip(p_path, *p_file)); }; - -ZipArchive* ZipArchive::get_singleton() { +ZipArchive *ZipArchive::get_singleton() { if (instance == NULL) { instance = memnew(ZipArchive); @@ -251,9 +247,9 @@ ZipArchive::ZipArchive() { ZipArchive::~ZipArchive() { - for (int i=0; i<packages.size(); i++) { + for (int i = 0; i < packages.size(); i++) { - FileAccess* f = (FileAccess*)unzGetOpaque(packages[i].zfile); + FileAccess *f = (FileAccess *)unzGetOpaque(packages[i].zfile); unzClose(packages[i].zfile); memdelete(f); }; @@ -261,18 +257,17 @@ ZipArchive::~ZipArchive() { packages.clear(); }; - -Error FileAccessZip::_open(const String& p_path, int p_mode_flags) { +Error FileAccessZip::_open(const String &p_path, int p_mode_flags) { close(); ERR_FAIL_COND_V(p_mode_flags & FileAccess::WRITE, FAILED); - ZipArchive* arch = ZipArchive::get_singleton(); + ZipArchive *arch = ZipArchive::get_singleton(); ERR_FAIL_COND_V(!arch, FAILED); zfile = arch->get_file_handle(p_path); ERR_FAIL_COND_V(!zfile, FAILED); - int err = unzGetCurrentFileInfo64(zfile,&file_info,NULL,0,NULL,0,NULL,0); + int err = unzGetCurrentFileInfo64(zfile, &file_info, NULL, 0, NULL, 0, NULL, 0); ERR_FAIL_COND_V(err != UNZ_OK, FAILED); return OK; @@ -283,7 +278,7 @@ void FileAccessZip::close() { if (!zfile) return; - ZipArchive* arch = ZipArchive::get_singleton(); + ZipArchive *arch = ZipArchive::get_singleton(); ERR_FAIL_COND(!arch); arch->close_handle(zfile); zfile = NULL; @@ -332,7 +327,7 @@ uint8_t FileAccessZip::get_8() const { return ret; }; -int FileAccessZip::get_buffer(uint8_t *p_dst,int p_length) const { +int FileAccessZip::get_buffer(uint8_t *p_dst, int p_length) const { ERR_FAIL_COND_V(!zfile, -1); at_eof = unzeof(zfile); @@ -363,13 +358,12 @@ void FileAccessZip::store_8(uint8_t p_dest) { ERR_FAIL(); }; -bool FileAccessZip::file_exists(const String& p_name) { +bool FileAccessZip::file_exists(const String &p_name) { return false; }; - -FileAccessZip::FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file) { +FileAccessZip::FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file) { zfile = NULL; _open(p_path, FileAccess::READ); diff --git a/core/io/file_access_zip.h b/core/io/file_access_zip.h index e34bc1283..7d5be8678 100644 --- a/core/io/file_access_zip.h +++ b/core/io/file_access_zip.h @@ -31,15 +31,14 @@ #ifndef FILE_ACCESS_Zip_H #define FILE_ACCESS_Zip_H -#include <stdlib.h> #include "core/io/file_access_pack.h" -#include "unzip.h" #include "map.h" +#include "unzip.h" +#include <stdlib.h> class ZipArchive : public PackSource { public: - struct File { int package; @@ -50,23 +49,20 @@ public: }; }; - private: - struct Package { String filename; unzFile zfile; }; Vector<Package> packages; - Map<String,File> files; + Map<String, File> files; - static ZipArchive* instance; + static ZipArchive *instance; FileAccess::CreateFunc fa_create_func; public: - void close_handle(unzFile p_file) const; unzFile get_file_handle(String p_file) const; @@ -74,49 +70,47 @@ public: bool file_exists(String p_name) const; - virtual bool try_open_pack(const String& p_path); - FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file); + virtual bool try_open_pack(const String &p_path); + FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); - static ZipArchive* get_singleton(); + static ZipArchive *get_singleton(); ZipArchive(); ~ZipArchive(); }; - class FileAccessZip : public FileAccess { unzFile zfile; - unz_file_info64 file_info; + unz_file_info64 file_info; mutable bool at_eof; - ZipArchive* archive; + ZipArchive *archive; public: - - virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file + virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(size_t p_position); ///< seek to a given position - virtual void seek_end(int64_t p_position=0); ///< seek from the end of file + virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual size_t get_pos() const; ///< get position in the file virtual size_t get_len() const; ///< get size of the file virtual bool eof_reached() const; ///< reading passed EOF virtual uint8_t get_8() const; ///< get a byte - virtual int get_buffer(uint8_t *p_dst,int p_length) const; + virtual int get_buffer(uint8_t *p_dst, int p_length) const; virtual Error get_error() const; ///< get last error virtual void store_8(uint8_t p_dest); ///< store a byte - virtual bool file_exists(const String& p_name); ///< return true if a file exists + virtual bool file_exists(const String &p_name); ///< return true if a file exists - virtual uint64_t _get_modified_time(const String& p_file) { return 0; } // todo + virtual uint64_t _get_modified_time(const String &p_file) { return 0; } // todo - FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file); + FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file); ~FileAccessZip(); }; diff --git a/core/io/http_client.cpp b/core/io/http_client.cpp index 1a5c25954..adc95e962 100644 --- a/core/io/http_client.cpp +++ b/core/io/http_client.cpp @@ -33,53 +33,48 @@ void HTTPClient::set_ip_type(IP::Type p_type) { ip_type = p_type; } -Error HTTPClient::connect(const String &p_host, int p_port, bool p_ssl,bool p_verify_host){ +Error HTTPClient::connect(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) { close(); tcp_connection->set_ip_type(ip_type); - conn_port=p_port; - conn_host=p_host; + conn_port = p_port; + conn_host = p_host; if (conn_host.begins_with("http://")) { - conn_host=conn_host.replace_first("http://",""); + conn_host = conn_host.replace_first("http://", ""); } else if (conn_host.begins_with("https://")) { //use https - conn_host=conn_host.replace_first("https://",""); + conn_host = conn_host.replace_first("https://", ""); } - - ssl=p_ssl; - ssl_verify_host=p_verify_host; - connection=tcp_connection; - - + ssl = p_ssl; + ssl_verify_host = p_verify_host; + connection = tcp_connection; if (conn_host.is_valid_ip_address()) { //is ip - Error err = tcp_connection->connect(IP_Address(conn_host),p_port); + Error err = tcp_connection->connect(IP_Address(conn_host), p_port); if (err) { - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return err; } - status=STATUS_CONNECTING; + status = STATUS_CONNECTING; } else { //is hostname - resolving=IP::get_singleton()->resolve_hostname_queue_item(conn_host, ip_type); - status=STATUS_RESOLVING; - + resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host, ip_type); + status = STATUS_RESOLVING; } return OK; } -void HTTPClient::set_connection(const Ref<StreamPeer>& p_connection){ +void HTTPClient::set_connection(const Ref<StreamPeer> &p_connection) { close(); - connection=p_connection; - status=STATUS_CONNECTED; - + connection = p_connection; + status = STATUS_CONNECTED; } Ref<StreamPeer> HTTPClient::get_connection() const { @@ -87,14 +82,13 @@ Ref<StreamPeer> HTTPClient::get_connection() const { return connection; } -Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const DVector<uint8_t>& p_body) { - - ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA); +Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const DVector<uint8_t> &p_body) { + ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA); - static const char* _methods[METHOD_MAX]={ + static const char *_methods[METHOD_MAX] = { "GET", "HEAD", "POST", @@ -102,54 +96,54 @@ Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vecto "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; + "CONNECT" + }; - String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n"; - request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n"; - bool add_clen=p_body.size()>0; - for(int i=0;i<p_headers.size();i++) { - request+=p_headers[i]+"\r\n"; - if (add_clen && p_headers[i].find("Content-Length:")==0) { - add_clen=false; + String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n"; + request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n"; + bool add_clen = p_body.size() > 0; + for (int i = 0; i < p_headers.size(); i++) { + request += p_headers[i] + "\r\n"; + if (add_clen && p_headers[i].find("Content-Length:") == 0) { + add_clen = false; } } if (add_clen) { - request+="Content-Length: "+itos(p_body.size())+"\r\n"; + request += "Content-Length: " + itos(p_body.size()) + "\r\n"; //should it add utf8 encoding? not sure } - request+="\r\n"; - CharString cs=request.utf8(); + request += "\r\n"; + CharString cs = request.utf8(); DVector<uint8_t> data; //Maybe this goes faster somehow? - for(int i=0;i<cs.length();i++) { - data.append( cs[i] ); + for (int i = 0; i < cs.length(); i++) { + data.append(cs[i]); } - data.append_array( p_body ); + data.append_array(p_body); DVector<uint8_t>::Read r = data.read(); Error err = connection->put_data(&r[0], data.size()); if (err) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return err; } - status=STATUS_REQUESTING; + status = STATUS_REQUESTING; return OK; } -Error HTTPClient::request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body) { +Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) { - ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA); + ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA); - - static const char* _methods[METHOD_MAX]={ + static const char *_methods[METHOD_MAX] = { "GET", "HEAD", "POST", @@ -157,50 +151,51 @@ Error HTTPClient::request( Method p_method, const String& p_url, const Vector<St "DELETE", "OPTIONS", "TRACE", - "CONNECT"}; + "CONNECT" + }; - String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n"; - request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n"; - bool add_clen=p_body.length()>0; - for(int i=0;i<p_headers.size();i++) { - request+=p_headers[i]+"\r\n"; - if (add_clen && p_headers[i].find("Content-Length:")==0) { - add_clen=false; + String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n"; + request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n"; + bool add_clen = p_body.length() > 0; + for (int i = 0; i < p_headers.size(); i++) { + request += p_headers[i] + "\r\n"; + if (add_clen && p_headers[i].find("Content-Length:") == 0) { + add_clen = false; } } if (add_clen) { - request+="Content-Length: "+itos(p_body.utf8().length())+"\r\n"; + request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n"; //should it add utf8 encoding? not sure } - request+="\r\n"; - request+=p_body; + request += "\r\n"; + request += p_body; - CharString cs=request.utf8(); - Error err = connection->put_data((const uint8_t*)cs.ptr(),cs.length()); + CharString cs = request.utf8(); + Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length()); if (err) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return err; } - status=STATUS_REQUESTING; + status = STATUS_REQUESTING; return OK; } -Error HTTPClient::send_body_text(const String& p_body){ +Error HTTPClient::send_body_text(const String &p_body) { return OK; } -Error HTTPClient::send_body_data(const ByteArray& p_body){ +Error HTTPClient::send_body_data(const ByteArray &p_body) { return OK; } bool HTTPClient::has_response() const { - return response_headers.size()!=0; + return response_headers.size() != 0; } bool HTTPClient::is_response_chunked() const { @@ -218,7 +213,7 @@ Error HTTPClient::get_response_headers(List<String> *r_response) { if (!response_headers.size()) return ERR_INVALID_PARAMETER; - for(int i=0;i<response_headers.size();i++) { + for (int i = 0; i < response_headers.size(); i++) { r_response->push_back(response_headers[i]); } @@ -228,71 +223,67 @@ Error HTTPClient::get_response_headers(List<String> *r_response) { return OK; } +void HTTPClient::close() { -void HTTPClient::close(){ - - if (tcp_connection->get_status()!=StreamPeerTCP::STATUS_NONE) + if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE) tcp_connection->disconnect(); connection.unref(); - status=STATUS_DISCONNECTED; - if (resolving!=IP::RESOLVER_INVALID_ID) { + status = STATUS_DISCONNECTED; + if (resolving != IP::RESOLVER_INVALID_ID) { IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; - + resolving = IP::RESOLVER_INVALID_ID; } response_headers.clear(); response_str.clear(); - body_size=0; - body_left=0; - chunk_left=0; - response_num=0; + body_size = 0; + body_left = 0; + chunk_left = 0; + response_num = 0; } +Error HTTPClient::poll() { -Error HTTPClient::poll(){ - - switch(status) { - + switch (status) { case STATUS_RESOLVING: { - ERR_FAIL_COND_V(resolving==IP::RESOLVER_INVALID_ID,ERR_BUG); + 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 + 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); + Error err = tcp_connection->connect(host, conn_port); IP::get_singleton()->erase_resolve_item(resolving); - resolving=IP::RESOLVER_INVALID_ID; + resolving = IP::RESOLVER_INVALID_ID; if (err) { - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return err; } - status=STATUS_CONNECTING; + 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; + resolving = IP::RESOLVER_INVALID_ID; close(); - status=STATUS_CANT_RESOLVE; + status = STATUS_CANT_RESOLVE; return ERR_CANT_RESOLVE; } break; - } } break; case STATUS_CONNECTING: { StreamPeerTCP::Status s = tcp_connection->get_status(); - switch(s) { + switch (s) { case StreamPeerTCP::STATUS_CONNECTING: { return OK; //do none @@ -300,23 +291,23 @@ Error HTTPClient::poll(){ case StreamPeerTCP::STATUS_CONNECTED: { if (ssl) { Ref<StreamPeerSSL> ssl = StreamPeerSSL::create(); - Error err = ssl->connect(tcp_connection,true,ssl_verify_host?conn_host:String()); - if (err!=OK) { + Error err = ssl->connect(tcp_connection, true, ssl_verify_host ? conn_host : String()); + if (err != OK) { close(); - status=STATUS_SSL_HANDSHAKE_ERROR; + status = STATUS_SSL_HANDSHAKE_ERROR; return ERR_CANT_CONNECT; } //print_line("SSL! TURNED ON!"); - connection=ssl; + connection = ssl; } - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; return OK; } break; case StreamPeerTCP::STATUS_ERROR: case StreamPeerTCP::STATUS_NONE: { close(); - status=STATUS_CANT_CONNECT; + status = STATUS_CANT_CONNECT; return ERR_CANT_CONNECT; } break; } @@ -327,78 +318,73 @@ Error HTTPClient::poll(){ } break; case STATUS_REQUESTING: { - - while(true) { + while (true) { uint8_t byte; - int rec=0; - Error err = _get_http_data(&byte,1,rec); - if (err!=OK) { + int rec = 0; + Error err = _get_http_data(&byte, 1, rec); + if (err != OK) { close(); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ERR_CONNECTION_ERROR; } - if (rec==0) + 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') - ) { - + (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()); + 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; + body_size = 0; + chunked = false; + body_left = 0; + chunk_left = 0; response_str.clear(); response_headers.clear(); response_num = RESPONSE_OK; - for(int i=0;i<responses.size();i++) { + for (int i = 0; i < responses.size(); i++) { String header = responses[i].strip_edges(); String s = header.to_lower(); - if (s.length()==0) + 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; + 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 = header.substr(header.find(":")+1,header.length()).strip_edges(); + String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges(); //print_line("TRANSFER ENCODING: "+encoding); - if (encoding=="chunked") { - chunked=true; + if (encoding == "chunked") { + chunked = true; } - } - if (i==0 && responses[i].begins_with("HTTP")) { + if (i == 0 && responses[i].begins_with("HTTP")) { - String num = responses[i].get_slicec(' ',1); - response_num=num.to_int(); + String num = responses[i].get_slicec(' ', 1); + response_num = num.to_int(); } else { response_headers.push_back(header); } - } - if (body_size==0 && !chunked) { + if (body_size == 0 && !chunked) { - status=STATUS_CONNECTED; //ask for something again? + status = STATUS_CONNECTED; //ask for something again? } else { - status=STATUS_BODY; + status = STATUS_BODY; } return OK; } @@ -420,25 +406,22 @@ Error HTTPClient::poll(){ } break; } - return OK; } - Dictionary HTTPClient::_get_response_headers_as_dictionary() { List<String> rh; get_response_headers(&rh); Dictionary ret; - for(const List<String>::Element *E=rh.front();E;E=E->next()) { + for (const List<String>::Element *E = rh.front(); E; E = E->next()) { String s = E->get(); int sp = s.find(":"); - if (sp==-1) + if (sp == -1) continue; - String key = s.substr(0,sp).strip_edges(); - String value = s.substr(sp+1,s.length()).strip_edges(); - ret[key]=value; - + String key = s.substr(0, sp).strip_edges(); + String value = s.substr(sp + 1, s.length()).strip_edges(); + ret[key] = value; } return ret; @@ -450,9 +433,9 @@ StringArray HTTPClient::_get_response_headers() { get_response_headers(&rh); StringArray ret; ret.resize(rh.size()); - int idx=0; - for(const List<String>::Element *E=rh.front();E;E=E->next()) { - ret.set(idx++,E->get()); + int idx = 0; + for (const List<String>::Element *E = rh.front(); E; E = E->next()) { + ret.set(idx++, E->get()); } return ret; @@ -465,96 +448,93 @@ int HTTPClient::get_response_body_length() const { ByteArray HTTPClient::read_response_body_chunk() { - ERR_FAIL_COND_V( status !=STATUS_BODY, ByteArray() ); + ERR_FAIL_COND_V(status != STATUS_BODY, ByteArray()); - Error err=OK; + Error err = OK; if (chunked) { - while(true) { + while (true) { - if (chunk_left==0) { + if (chunk_left == 0) { //reading len uint8_t b; - int rec=0; - err = _get_http_data(&b,1,rec); + int rec = 0; + err = _get_http_data(&b, 1, rec); - if (rec==0) + if (rec == 0) break; chunk.push_back(b); - if (chunk.size()>32) { + if (chunk.size() > 32) { ERR_PRINT("HTTP Invalid chunk hex len"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ByteArray(); } - if (chunk.size()>2 && chunk[chunk.size()-2]=='\r' && chunk[chunk.size()-1]=='\n') { + if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') { - int len=0; - for(int i=0;i<chunk.size()-2;i++) { + int len = 0; + for (int i = 0; i < chunk.size() - 2; i++) { char c = chunk[i]; - int v=0; - if (c>='0' && c<='9') - v=c-'0'; - else if (c>='a' && c<='f') - v=c-'a'+10; - else if (c>='A' && c<='F') - v=c-'A'+10; + int v = 0; + if (c >= '0' && c <= '9') + v = c - '0'; + else if (c >= 'a' && c <= 'f') + v = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + v = c - 'A' + 10; else { ERR_PRINT("HTTP Chunk len not in hex!!"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ByteArray(); } - len<<=4; - len|=v; - if (len>(1<<24)) { + len <<= 4; + len |= v; + if (len > (1 << 24)) { ERR_PRINT("HTTP Chunk too big!! >16mb"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ByteArray(); } - } - if (len==0) { + if (len == 0) { //end! - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; chunk.clear(); return ByteArray(); } - chunk_left=len+2; + chunk_left = len + 2; chunk.resize(chunk_left); - } } else { - int rec=0; - err = _get_http_data(&chunk[chunk.size()-chunk_left],chunk_left,rec); - if (rec==0) { + int rec = 0; + err = _get_http_data(&chunk[chunk.size() - chunk_left], chunk_left, rec); + if (rec == 0) { break; } - chunk_left-=rec; + chunk_left -= rec; - if (chunk_left==0) { + if (chunk_left == 0) { - if (chunk[chunk.size()-2]!='\r' || chunk[chunk.size()-1]!='\n') { + if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') { ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)"); - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; return ByteArray(); } ByteArray ret; - ret.resize(chunk.size()-2); + ret.resize(chunk.size() - 2); { ByteArray::Write w = ret.write(); - copymem(w.ptr(),chunk.ptr(),chunk.size()-2); + copymem(w.ptr(), chunk.ptr(), chunk.size() - 2); } chunk.clear(); return ret; - } break; @@ -563,46 +543,44 @@ ByteArray HTTPClient::read_response_body_chunk() { } else { - int to_read = MIN(body_left,read_chunk_size); + int to_read = MIN(body_left, read_chunk_size); ByteArray ret; ret.resize(to_read); int _offset = 0; while (to_read > 0) { - int rec=0; + int rec = 0; { ByteArray::Write w = ret.write(); - err = _get_http_data(w.ptr()+_offset,to_read,rec); + err = _get_http_data(w.ptr() + _offset, to_read, rec); } - if (rec>0) { - body_left-=rec; - to_read-=rec; + if (rec > 0) { + body_left -= rec; + to_read -= rec; _offset += rec; } else { - if (to_read>0) //ended up reading less + if (to_read > 0) //ended up reading less ret.resize(_offset); break; } } - if (body_left==0) { - status=STATUS_CONNECTED; + if (body_left == 0) { + status = STATUS_CONNECTED; } return ret; - } - - if (err!=OK) { + if (err != OK) { close(); - if (err==ERR_FILE_EOF) { + if (err == ERR_FILE_EOF) { - status=STATUS_DISCONNECTED; //server disconnected + status = STATUS_DISCONNECTED; //server disconnected } else { - status=STATUS_CONNECTION_ERROR; + status = STATUS_CONNECTION_ERROR; } - } else if (body_left==0 && !chunked) { + } else if (body_left == 0 && !chunked) { - status=STATUS_CONNECTED; + status = STATUS_CONNECTED; } return ByteArray(); @@ -610,181 +588,174 @@ ByteArray HTTPClient::read_response_body_chunk() { HTTPClient::Status HTTPClient::get_status() const { - return status; } void HTTPClient::set_blocking_mode(bool p_enable) { - blocking=p_enable; + blocking = p_enable; } -bool HTTPClient::is_blocking_mode_enabled() const{ +bool HTTPClient::is_blocking_mode_enabled() const { return blocking; } -Error HTTPClient::_get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received) { +Error HTTPClient::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) { if (blocking) { - Error err = connection->get_data(p_buffer,p_bytes); - if (err==OK) - r_received=p_bytes; + Error err = connection->get_data(p_buffer, p_bytes); + if (err == OK) + r_received = p_bytes; else - r_received=0; + r_received = 0; return err; } else { - return connection->get_partial_data(p_buffer,p_bytes,r_received); + return connection->get_partial_data(p_buffer, p_bytes, r_received); } } void HTTPClient::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&HTTPClient::set_ip_type); - ObjectTypeDB::bind_method(_MD("connect:Error","host","port","use_ssl","verify_host"),&HTTPClient::connect,DEFVAL(false),DEFVAL(true)); - ObjectTypeDB::bind_method(_MD("set_connection","connection:StreamPeer"),&HTTPClient::set_connection); - ObjectTypeDB::bind_method(_MD("get_connection:StreamPeer"),&HTTPClient::get_connection); - ObjectTypeDB::bind_method(_MD("request_raw","method","url","headers","body"),&HTTPClient::request_raw); - ObjectTypeDB::bind_method(_MD("request","method","url","headers","body"),&HTTPClient::request,DEFVAL(String())); - ObjectTypeDB::bind_method(_MD("send_body_text","body"),&HTTPClient::send_body_text); - ObjectTypeDB::bind_method(_MD("send_body_data","body"),&HTTPClient::send_body_data); - ObjectTypeDB::bind_method(_MD("close"),&HTTPClient::close); - - ObjectTypeDB::bind_method(_MD("has_response"),&HTTPClient::has_response); - ObjectTypeDB::bind_method(_MD("is_response_chunked"),&HTTPClient::is_response_chunked); - ObjectTypeDB::bind_method(_MD("get_response_code"),&HTTPClient::get_response_code); - ObjectTypeDB::bind_method(_MD("get_response_headers"),&HTTPClient::_get_response_headers); - ObjectTypeDB::bind_method(_MD("get_response_headers_as_dictionary"),&HTTPClient::_get_response_headers_as_dictionary); - ObjectTypeDB::bind_method(_MD("get_response_body_length"),&HTTPClient::get_response_body_length); - ObjectTypeDB::bind_method(_MD("read_response_body_chunk"),&HTTPClient::read_response_body_chunk); - ObjectTypeDB::bind_method(_MD("set_read_chunk_size","bytes"),&HTTPClient::set_read_chunk_size); + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &HTTPClient::set_ip_type); + ObjectTypeDB::bind_method(_MD("connect:Error", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect, DEFVAL(false), DEFVAL(true)); + ObjectTypeDB::bind_method(_MD("set_connection", "connection:StreamPeer"), &HTTPClient::set_connection); + ObjectTypeDB::bind_method(_MD("get_connection:StreamPeer"), &HTTPClient::get_connection); + ObjectTypeDB::bind_method(_MD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw); + ObjectTypeDB::bind_method(_MD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String())); + ObjectTypeDB::bind_method(_MD("send_body_text", "body"), &HTTPClient::send_body_text); + ObjectTypeDB::bind_method(_MD("send_body_data", "body"), &HTTPClient::send_body_data); + ObjectTypeDB::bind_method(_MD("close"), &HTTPClient::close); - ObjectTypeDB::bind_method(_MD("set_blocking_mode","enabled"),&HTTPClient::set_blocking_mode); - ObjectTypeDB::bind_method(_MD("is_blocking_mode_enabled"),&HTTPClient::is_blocking_mode_enabled); + ObjectTypeDB::bind_method(_MD("has_response"), &HTTPClient::has_response); + ObjectTypeDB::bind_method(_MD("is_response_chunked"), &HTTPClient::is_response_chunked); + ObjectTypeDB::bind_method(_MD("get_response_code"), &HTTPClient::get_response_code); + ObjectTypeDB::bind_method(_MD("get_response_headers"), &HTTPClient::_get_response_headers); + ObjectTypeDB::bind_method(_MD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary); + ObjectTypeDB::bind_method(_MD("get_response_body_length"), &HTTPClient::get_response_body_length); + ObjectTypeDB::bind_method(_MD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk); + ObjectTypeDB::bind_method(_MD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size); - ObjectTypeDB::bind_method(_MD("get_status"),&HTTPClient::get_status); - ObjectTypeDB::bind_method(_MD("poll:Error"),&HTTPClient::poll); + ObjectTypeDB::bind_method(_MD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode); + ObjectTypeDB::bind_method(_MD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled); - ObjectTypeDB::bind_method(_MD("query_string_from_dict:String","fields"),&HTTPClient::query_string_from_dict); + ObjectTypeDB::bind_method(_MD("get_status"), &HTTPClient::get_status); + ObjectTypeDB::bind_method(_MD("poll:Error"), &HTTPClient::poll); + ObjectTypeDB::bind_method(_MD("query_string_from_dict:String", "fields"), &HTTPClient::query_string_from_dict); - BIND_CONSTANT( METHOD_GET ); - BIND_CONSTANT( METHOD_HEAD ); - BIND_CONSTANT( METHOD_POST ); - BIND_CONSTANT( METHOD_PUT ); - BIND_CONSTANT( METHOD_DELETE ); - BIND_CONSTANT( METHOD_OPTIONS ); - BIND_CONSTANT( METHOD_TRACE ); - BIND_CONSTANT( METHOD_CONNECT ); - BIND_CONSTANT( METHOD_MAX ); + BIND_CONSTANT(METHOD_GET); + BIND_CONSTANT(METHOD_HEAD); + BIND_CONSTANT(METHOD_POST); + BIND_CONSTANT(METHOD_PUT); + BIND_CONSTANT(METHOD_DELETE); + BIND_CONSTANT(METHOD_OPTIONS); + BIND_CONSTANT(METHOD_TRACE); + BIND_CONSTANT(METHOD_CONNECT); + BIND_CONSTANT(METHOD_MAX); - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_RESOLVING ); //resolving hostname (if passed a hostname) - BIND_CONSTANT( STATUS_CANT_RESOLVE ); - BIND_CONSTANT( STATUS_CONNECTING ); //connecting to ip - BIND_CONSTANT( STATUS_CANT_CONNECT ); - BIND_CONSTANT( STATUS_CONNECTED ); //connected ); requests only accepted here - BIND_CONSTANT( STATUS_REQUESTING ); // request in progress - BIND_CONSTANT( STATUS_BODY ); // request resulted in body ); which must be read - BIND_CONSTANT( STATUS_CONNECTION_ERROR ); - BIND_CONSTANT( STATUS_SSL_HANDSHAKE_ERROR ); + BIND_CONSTANT(STATUS_DISCONNECTED); + BIND_CONSTANT(STATUS_RESOLVING); //resolving hostname (if passed a hostname) + BIND_CONSTANT(STATUS_CANT_RESOLVE); + BIND_CONSTANT(STATUS_CONNECTING); //connecting to ip + BIND_CONSTANT(STATUS_CANT_CONNECT); + BIND_CONSTANT(STATUS_CONNECTED); //connected ); requests only accepted here + BIND_CONSTANT(STATUS_REQUESTING); // request in progress + BIND_CONSTANT(STATUS_BODY); // request resulted in body ); which must be read + BIND_CONSTANT(STATUS_CONNECTION_ERROR); + BIND_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR); - - BIND_CONSTANT( RESPONSE_CONTINUE ); - BIND_CONSTANT( RESPONSE_SWITCHING_PROTOCOLS ); - BIND_CONSTANT( RESPONSE_PROCESSING ); + BIND_CONSTANT(RESPONSE_CONTINUE); + BIND_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS); + BIND_CONSTANT(RESPONSE_PROCESSING); // 2xx successful - BIND_CONSTANT( RESPONSE_OK ); - BIND_CONSTANT( RESPONSE_CREATED ); - BIND_CONSTANT( RESPONSE_ACCEPTED ); - BIND_CONSTANT( RESPONSE_NON_AUTHORITATIVE_INFORMATION ); - BIND_CONSTANT( RESPONSE_NO_CONTENT ); - BIND_CONSTANT( RESPONSE_RESET_CONTENT ); - BIND_CONSTANT( RESPONSE_PARTIAL_CONTENT ); - BIND_CONSTANT( RESPONSE_MULTI_STATUS ); - BIND_CONSTANT( RESPONSE_IM_USED ); + BIND_CONSTANT(RESPONSE_OK); + BIND_CONSTANT(RESPONSE_CREATED); + BIND_CONSTANT(RESPONSE_ACCEPTED); + BIND_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION); + BIND_CONSTANT(RESPONSE_NO_CONTENT); + BIND_CONSTANT(RESPONSE_RESET_CONTENT); + BIND_CONSTANT(RESPONSE_PARTIAL_CONTENT); + BIND_CONSTANT(RESPONSE_MULTI_STATUS); + BIND_CONSTANT(RESPONSE_IM_USED); // 3xx redirection - BIND_CONSTANT( RESPONSE_MULTIPLE_CHOICES ); - BIND_CONSTANT( RESPONSE_MOVED_PERMANENTLY ); - BIND_CONSTANT( RESPONSE_FOUND ); - BIND_CONSTANT( RESPONSE_SEE_OTHER ); - BIND_CONSTANT( RESPONSE_NOT_MODIFIED ); - BIND_CONSTANT( RESPONSE_USE_PROXY ); - BIND_CONSTANT( RESPONSE_TEMPORARY_REDIRECT ); + BIND_CONSTANT(RESPONSE_MULTIPLE_CHOICES); + BIND_CONSTANT(RESPONSE_MOVED_PERMANENTLY); + BIND_CONSTANT(RESPONSE_FOUND); + BIND_CONSTANT(RESPONSE_SEE_OTHER); + BIND_CONSTANT(RESPONSE_NOT_MODIFIED); + BIND_CONSTANT(RESPONSE_USE_PROXY); + BIND_CONSTANT(RESPONSE_TEMPORARY_REDIRECT); // 4xx client error - BIND_CONSTANT( RESPONSE_BAD_REQUEST ); - BIND_CONSTANT( RESPONSE_UNAUTHORIZED ); - BIND_CONSTANT( RESPONSE_PAYMENT_REQUIRED ); - BIND_CONSTANT( RESPONSE_FORBIDDEN ); - BIND_CONSTANT( RESPONSE_NOT_FOUND ); - BIND_CONSTANT( RESPONSE_METHOD_NOT_ALLOWED ); - BIND_CONSTANT( RESPONSE_NOT_ACCEPTABLE ); - BIND_CONSTANT( RESPONSE_PROXY_AUTHENTICATION_REQUIRED ); - BIND_CONSTANT( RESPONSE_REQUEST_TIMEOUT ); - BIND_CONSTANT( RESPONSE_CONFLICT ); - BIND_CONSTANT( RESPONSE_GONE ); - BIND_CONSTANT( RESPONSE_LENGTH_REQUIRED ); - BIND_CONSTANT( RESPONSE_PRECONDITION_FAILED ); - BIND_CONSTANT( RESPONSE_REQUEST_ENTITY_TOO_LARGE ); - BIND_CONSTANT( RESPONSE_REQUEST_URI_TOO_LONG ); - BIND_CONSTANT( RESPONSE_UNSUPPORTED_MEDIA_TYPE ); - BIND_CONSTANT( RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE ); - BIND_CONSTANT( RESPONSE_EXPECTATION_FAILED ); - BIND_CONSTANT( RESPONSE_UNPROCESSABLE_ENTITY ); - BIND_CONSTANT( RESPONSE_LOCKED ); - BIND_CONSTANT( RESPONSE_FAILED_DEPENDENCY ); - BIND_CONSTANT( RESPONSE_UPGRADE_REQUIRED ); + BIND_CONSTANT(RESPONSE_BAD_REQUEST); + BIND_CONSTANT(RESPONSE_UNAUTHORIZED); + BIND_CONSTANT(RESPONSE_PAYMENT_REQUIRED); + BIND_CONSTANT(RESPONSE_FORBIDDEN); + BIND_CONSTANT(RESPONSE_NOT_FOUND); + BIND_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED); + BIND_CONSTANT(RESPONSE_NOT_ACCEPTABLE); + BIND_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED); + BIND_CONSTANT(RESPONSE_REQUEST_TIMEOUT); + BIND_CONSTANT(RESPONSE_CONFLICT); + BIND_CONSTANT(RESPONSE_GONE); + BIND_CONSTANT(RESPONSE_LENGTH_REQUIRED); + BIND_CONSTANT(RESPONSE_PRECONDITION_FAILED); + BIND_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE); + BIND_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG); + BIND_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE); + BIND_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE); + BIND_CONSTANT(RESPONSE_EXPECTATION_FAILED); + BIND_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY); + BIND_CONSTANT(RESPONSE_LOCKED); + BIND_CONSTANT(RESPONSE_FAILED_DEPENDENCY); + BIND_CONSTANT(RESPONSE_UPGRADE_REQUIRED); // 5xx server error - BIND_CONSTANT( RESPONSE_INTERNAL_SERVER_ERROR ); - BIND_CONSTANT( RESPONSE_NOT_IMPLEMENTED ); - BIND_CONSTANT( RESPONSE_BAD_GATEWAY ); - BIND_CONSTANT( RESPONSE_SERVICE_UNAVAILABLE ); - BIND_CONSTANT( RESPONSE_GATEWAY_TIMEOUT ); - BIND_CONSTANT( RESPONSE_HTTP_VERSION_NOT_SUPPORTED ); - BIND_CONSTANT( RESPONSE_INSUFFICIENT_STORAGE ); - BIND_CONSTANT( RESPONSE_NOT_EXTENDED ); - + BIND_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR); + BIND_CONSTANT(RESPONSE_NOT_IMPLEMENTED); + BIND_CONSTANT(RESPONSE_BAD_GATEWAY); + BIND_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE); + BIND_CONSTANT(RESPONSE_GATEWAY_TIMEOUT); + BIND_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED); + BIND_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE); + BIND_CONSTANT(RESPONSE_NOT_EXTENDED); } void HTTPClient::set_read_chunk_size(int p_size) { - ERR_FAIL_COND(p_size<256 || p_size>(1<<24)); - read_chunk_size=p_size; + ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24)); + read_chunk_size = p_size; } -String HTTPClient::query_string_from_dict(const Dictionary& p_dict) { - String query = ""; - Array keys = p_dict.keys(); - for (int i = 0; i < keys.size(); ++i) { - query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape(); - } - query.erase(0, 1); - return query; +String HTTPClient::query_string_from_dict(const Dictionary &p_dict) { + String query = ""; + Array keys = p_dict.keys(); + for (int i = 0; i < keys.size(); ++i) { + query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape(); + } + query.erase(0, 1); + return query; } -HTTPClient::HTTPClient(){ +HTTPClient::HTTPClient() { ip_type = IP::TYPE_ANY; tcp_connection = StreamPeerTCP::create_ref(); resolving = IP::RESOLVER_INVALID_ID; - status=STATUS_DISCONNECTED; - conn_port=80; - body_size=0; - chunked=false; - body_left=0; - chunk_left=0; - response_num=0; - ssl=false; - blocking=false; - read_chunk_size=4096; + status = STATUS_DISCONNECTED; + conn_port = 80; + body_size = 0; + chunked = false; + body_left = 0; + chunk_left = 0; + response_num = 0; + ssl = false; + blocking = false; + read_chunk_size = 4096; } -HTTPClient::~HTTPClient(){ - - +HTTPClient::~HTTPClient() { } - diff --git a/core/io/http_client.h b/core/io/http_client.h index ef0a687cd..43d6dc721 100644 --- a/core/io/http_client.h +++ b/core/io/http_client.h @@ -29,17 +29,16 @@ #ifndef HTTP_CLIENT_H #define HTTP_CLIENT_H +#include "io/ip.h" #include "io/stream_peer.h" #include "io/stream_peer_tcp.h" -#include "io/ip.h" #include "reference.h" - class HTTPClient : public Reference { - OBJ_TYPE(HTTPClient,Reference); -public: + OBJ_TYPE(HTTPClient, Reference); +public: enum ResponseCode { // 1xx informational @@ -131,7 +130,6 @@ public: }; private: - IP::Type ip_type; Status status; IP::ResolverID resolving; @@ -160,22 +158,20 @@ private: Dictionary _get_response_headers_as_dictionary(); int read_chunk_size; - Error _get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received); + Error _get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received); public: - - void set_ip_type(IP::Type p_type); //Error connect_and_get(const String& p_url,bool p_verify_host=true); //connects to a full url and perform request - Error connect(const String &p_host,int p_port,bool p_ssl=false,bool p_verify_host=true); + Error connect(const String &p_host, int p_port, bool p_ssl = false, bool p_verify_host = true); - void set_connection(const Ref<StreamPeer>& p_connection); + void set_connection(const Ref<StreamPeer> &p_connection); Ref<StreamPeer> get_connection() const; - Error request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const DVector<uint8_t>& p_body); - Error request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body=String()); - Error send_body_text(const String& p_body); - Error send_body_data(const ByteArray& p_body); + Error request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const DVector<uint8_t> &p_body); + Error request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body = String()); + Error send_body_text(const String &p_body); + Error send_body_data(const ByteArray &p_body); void close(); @@ -196,7 +192,7 @@ public: Error poll(); - String query_string_from_dict(const Dictionary& p_dict); + String query_string_from_dict(const Dictionary &p_dict); HTTPClient(); ~HTTPClient(); diff --git a/core/io/image_loader.cpp b/core/io/image_loader.cpp index d4d10e212..074015950 100644 --- a/core/io/image_loader.cpp +++ b/core/io/image_loader.cpp @@ -29,90 +29,78 @@ #include "image_loader.h" #include "print_string.h" -bool ImageFormatLoader::recognize(const String& p_extension) const { - +bool ImageFormatLoader::recognize(const String &p_extension) const { List<String> extensions; get_recognized_extensions(&extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(p_extension.extension())==0) + if (E->get().nocasecmp_to(p_extension.extension()) == 0) return true; } return false; } -Error ImageLoader::load_image(String p_file,Image *p_image, FileAccess *p_custom) { - +Error ImageLoader::load_image(String p_file, Image *p_image, FileAccess *p_custom) { - FileAccess *f=p_custom; + FileAccess *f = p_custom; if (!f) { Error err; - f=FileAccess::open(p_file,FileAccess::READ,&err); + f = FileAccess::open(p_file, FileAccess::READ, &err); if (!f) { - ERR_PRINTS("Error opening file: "+p_file); + ERR_PRINTS("Error opening file: " + p_file); return err; } } String extension = p_file.extension(); - - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; - Error err = loader[i]->load_image(p_image,f); - - if (err!=ERR_FILE_UNRECOGNIZED) { + Error err = loader[i]->load_image(p_image, f); + if (err != ERR_FILE_UNRECOGNIZED) { if (!p_custom) memdelete(f); return err; } - - } if (!p_custom) memdelete(f); return ERR_FILE_UNRECOGNIZED; - } void ImageLoader::get_recognized_extensions(List<String> *p_extensions) { - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { loader[i]->get_recognized_extensions(p_extensions); - } } -bool ImageLoader::recognize(const String& p_extension) { +bool ImageLoader::recognize(const String &p_extension) { - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (loader[i]->recognize(p_extension)) return true; - } return false; } ImageFormatLoader *ImageLoader::loader[MAX_LOADERS]; -int ImageLoader::loader_count=0; +int ImageLoader::loader_count = 0; void ImageLoader::add_image_format_loader(ImageFormatLoader *p_loader) { - ERR_FAIL_COND(loader_count >=MAX_LOADERS ); - loader[loader_count++]=p_loader; + ERR_FAIL_COND(loader_count >= MAX_LOADERS); + loader[loader_count++] = p_loader; } - - - diff --git a/core/io/image_loader.h b/core/io/image_loader.h index 4de7706ab..b70170303 100644 --- a/core/io/image_loader.h +++ b/core/io/image_loader.h @@ -30,14 +30,13 @@ #define IMAGE_LOADER_H #include "image.h" -#include "ustring.h" -#include "os/file_access.h" #include "list.h" +#include "os/file_access.h" +#include "ustring.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - /** * @class ImageScanLineLoader * @author Juan Linietsky <reduzio@gmail.com> @@ -46,21 +45,19 @@ */ class ImageLoader; - /** * @class ImageLoader * Base Class and singleton for loading images from disk * Can load images in one go, or by scanline */ - class ImageFormatLoader { -friend class ImageLoader; -protected: - virtual Error load_image(Image *p_image,FileAccess *p_fileaccess)=0; - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - bool recognize(const String& p_extension) const; + friend class ImageLoader; +protected: + virtual Error load_image(Image *p_image, FileAccess *p_fileaccess) = 0; + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + bool recognize(const String &p_extension) const; public: virtual ~ImageFormatLoader() {} @@ -69,23 +66,19 @@ public: class ImageLoader { enum { - MAX_LOADERS=8 + MAX_LOADERS = 8 }; static ImageFormatLoader *loader[MAX_LOADERS]; static int loader_count; protected: - - public: - - static Error load_image(String p_file,Image *p_image, FileAccess *p_custom=NULL); - static void get_recognized_extensions(List<String> *p_extensions) ; - static bool recognize(const String& p_extension) ; + static Error load_image(String p_file, Image *p_image, FileAccess *p_custom = NULL); + static void get_recognized_extensions(List<String> *p_extensions); + static bool recognize(const String &p_extension); static void add_image_format_loader(ImageFormatLoader *p_loader); - }; #endif diff --git a/core/io/ip.cpp b/core/io/ip.cpp index b057d72e4..963e8a612 100644 --- a/core/io/ip.cpp +++ b/core/io/ip.cpp @@ -27,15 +27,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "ip.h" -#include "os/thread.h" -#include "os/semaphore.h" #include "hash_map.h" +#include "os/semaphore.h" +#include "os/thread.h" VARIANT_ENUM_CAST(IP::ResolverStatus); /************* RESOLVER ******************/ - struct _IP_ResolverPrivate { struct QueueItem { @@ -49,7 +48,7 @@ struct _IP_ResolverPrivate { status = IP::RESOLVER_STATUS_NONE; response = IP_Address(); type = IP::TYPE_NONE; - hostname=""; + hostname = ""; }; QueueItem() { @@ -61,8 +60,8 @@ struct _IP_ResolverPrivate { IP::ResolverID find_empty_id() const { - for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) { - if (queue[i].status==IP::RESOLVER_STATUS_NONE) + for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) { + if (queue[i].status == IP::RESOLVER_STATUS_NONE) return i; } return IP::RESOLVER_INVALID_ID; @@ -70,39 +69,35 @@ struct _IP_ResolverPrivate { Semaphore *sem; - Thread* thread; + Thread *thread; //Semaphore* semaphore; bool thread_abort; void resolve_queues() { - for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) { + for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) { - if (queue[i].status!=IP::RESOLVER_STATUS_WAITING) + if (queue[i].status != IP::RESOLVER_STATUS_WAITING) continue; - queue[i].response=IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type); + queue[i].response = IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type); - if (queue[i].response==IP_Address()) - queue[i].status=IP::RESOLVER_STATUS_ERROR; + if (queue[i].response == IP_Address()) + queue[i].status = IP::RESOLVER_STATUS_ERROR; else - queue[i].status=IP::RESOLVER_STATUS_DONE; - + queue[i].status = IP::RESOLVER_STATUS_DONE; } } - static void _thread_function(void *self) { - _IP_ResolverPrivate *ipr=(_IP_ResolverPrivate*)self; + _IP_ResolverPrivate *ipr = (_IP_ResolverPrivate *)self; - while(!ipr->thread_abort) { + while (!ipr->thread_abort) { ipr->sem->wait(); GLOBAL_LOCK_FUNCTION; ipr->resolve_queues(); - } - } HashMap<String, IP_Address> cache; @@ -110,12 +105,9 @@ struct _IP_ResolverPrivate { static String get_cache_key(String p_hostname, IP::Type p_type) { return itos(p_type) + p_hostname; } - }; - - -IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) { +IP_Address IP::resolve_hostname(const String &p_hostname, IP::Type p_type) { GLOBAL_LOCK_FUNCTION; @@ -124,30 +116,29 @@ IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) { return resolver->cache[key]; IP_Address res = _resolve_hostname(p_hostname, p_type); - resolver->cache[key]=res; + resolver->cache[key] = res; return res; - } -IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Type p_type) { +IP::ResolverID IP::resolve_hostname_queue_item(const String &p_hostname, IP::Type p_type) { GLOBAL_LOCK_FUNCTION; ResolverID id = resolver->find_empty_id(); - if (id==RESOLVER_INVALID_ID) { + if (id == RESOLVER_INVALID_ID) { WARN_PRINT("Out of resolver queries"); return id; } String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type); - resolver->queue[id].hostname=p_hostname; + resolver->queue[id].hostname = p_hostname; resolver->queue[id].type = p_type; if (resolver->cache.has(key)) { - resolver->queue[id].response=resolver->cache[key]; - resolver->queue[id].status=IP::RESOLVER_STATUS_DONE; + resolver->queue[id].response = resolver->cache[key]; + resolver->queue[id].status = IP::RESOLVER_STATUS_DONE; } else { - resolver->queue[id].response=IP_Address(); - resolver->queue[id].status=IP::RESOLVER_STATUS_WAITING; + resolver->queue[id].response = IP_Address(); + resolver->queue[id].status = IP::RESOLVER_STATUS_WAITING; if (resolver->thread) resolver->sem->post(); else @@ -159,37 +150,33 @@ IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Typ IP::ResolverStatus IP::get_resolve_item_status(ResolverID p_id) const { - ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP::RESOLVER_STATUS_NONE); + ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP::RESOLVER_STATUS_NONE); GLOBAL_LOCK_FUNCTION; - ERR_FAIL_COND_V(resolver->queue[p_id].status==IP::RESOLVER_STATUS_NONE,IP::RESOLVER_STATUS_NONE); + ERR_FAIL_COND_V(resolver->queue[p_id].status == IP::RESOLVER_STATUS_NONE, IP::RESOLVER_STATUS_NONE); return resolver->queue[p_id].status; - } IP_Address IP::get_resolve_item_address(ResolverID p_id) const { - ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP_Address()); + ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP_Address()); GLOBAL_LOCK_FUNCTION; - if (resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE) { - ERR_EXPLAIN("Resolve of '"+resolver->queue[p_id].hostname+"'' didn't complete yet."); - ERR_FAIL_COND_V(resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE,IP_Address()); + if (resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE) { + ERR_EXPLAIN("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet."); + ERR_FAIL_COND_V(resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE, IP_Address()); } - return resolver->queue[p_id].response; - } void IP::erase_resolve_item(ResolverID p_id) { - ERR_FAIL_INDEX(p_id,IP::RESOLVER_MAX_QUERIES); + ERR_FAIL_INDEX(p_id, IP::RESOLVER_MAX_QUERIES); GLOBAL_LOCK_FUNCTION; - resolver->queue[p_id].status=IP::RESOLVER_STATUS_NONE; - + resolver->queue[p_id].status = IP::RESOLVER_STATUS_NONE; } void IP::clear_cache(const String &p_hostname) { @@ -209,7 +196,7 @@ Array IP::_get_local_addresses() const { Array addresses; List<IP_Address> ip_addresses; get_local_addresses(&ip_addresses); - for(List<IP_Address>::Element *E=ip_addresses.front();E;E=E->next()) { + for (List<IP_Address>::Element *E = ip_addresses.front(); E; E = E->next()) { addresses.push_back(E->get()); } @@ -218,87 +205,82 @@ Array IP::_get_local_addresses() const { void IP::_bind_methods() { - ObjectTypeDB::bind_method(_MD("resolve_hostname","host","ip_type"),&IP::resolve_hostname,DEFVAL(IP::TYPE_ANY)); - ObjectTypeDB::bind_method(_MD("resolve_hostname_queue_item","host","ip_type"),&IP::resolve_hostname_queue_item,DEFVAL(IP::TYPE_ANY)); - ObjectTypeDB::bind_method(_MD("get_resolve_item_status","id"),&IP::get_resolve_item_status); - ObjectTypeDB::bind_method(_MD("get_resolve_item_address","id"),&IP::get_resolve_item_address); - ObjectTypeDB::bind_method(_MD("erase_resolve_item","id"),&IP::erase_resolve_item); - ObjectTypeDB::bind_method(_MD("get_local_addresses"),&IP::_get_local_addresses); - ObjectTypeDB::bind_method(_MD("clear_cache"),&IP::clear_cache, DEFVAL("")); + ObjectTypeDB::bind_method(_MD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY)); + ObjectTypeDB::bind_method(_MD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY)); + ObjectTypeDB::bind_method(_MD("get_resolve_item_status", "id"), &IP::get_resolve_item_status); + ObjectTypeDB::bind_method(_MD("get_resolve_item_address", "id"), &IP::get_resolve_item_address); + ObjectTypeDB::bind_method(_MD("erase_resolve_item", "id"), &IP::erase_resolve_item); + ObjectTypeDB::bind_method(_MD("get_local_addresses"), &IP::_get_local_addresses); + ObjectTypeDB::bind_method(_MD("clear_cache"), &IP::clear_cache, DEFVAL("")); - BIND_CONSTANT( RESOLVER_STATUS_NONE ); - BIND_CONSTANT( RESOLVER_STATUS_WAITING ); - BIND_CONSTANT( RESOLVER_STATUS_DONE ); - BIND_CONSTANT( RESOLVER_STATUS_ERROR ); + BIND_CONSTANT(RESOLVER_STATUS_NONE); + BIND_CONSTANT(RESOLVER_STATUS_WAITING); + BIND_CONSTANT(RESOLVER_STATUS_DONE); + BIND_CONSTANT(RESOLVER_STATUS_ERROR); - BIND_CONSTANT( RESOLVER_MAX_QUERIES ); - BIND_CONSTANT( RESOLVER_INVALID_ID ); + BIND_CONSTANT(RESOLVER_MAX_QUERIES); + BIND_CONSTANT(RESOLVER_INVALID_ID); - BIND_CONSTANT( TYPE_NONE ); - BIND_CONSTANT( TYPE_IPV4 ); - BIND_CONSTANT( TYPE_IPV6 ); - BIND_CONSTANT( TYPE_ANY ); + BIND_CONSTANT(TYPE_NONE); + BIND_CONSTANT(TYPE_IPV4); + BIND_CONSTANT(TYPE_IPV6); + BIND_CONSTANT(TYPE_ANY); } +IP *IP::singleton = NULL; -IP*IP::singleton=NULL; - -IP* IP::get_singleton() { +IP *IP::get_singleton() { return singleton; } +IP *(*IP::_create)() = NULL; -IP* (*IP::_create)()=NULL; +IP *IP::create() { -IP* IP::create() { - - ERR_FAIL_COND_V(singleton,NULL); - ERR_FAIL_COND_V(!_create,NULL); + ERR_FAIL_COND_V(singleton, NULL); + ERR_FAIL_COND_V(!_create, NULL); return _create(); } IP::IP() { - singleton=this; - resolver = memnew( _IP_ResolverPrivate ); - resolver->sem=NULL; + singleton = this; + resolver = memnew(_IP_ResolverPrivate); + resolver->sem = NULL; #ifndef NO_THREADS //resolver->sem = Semaphore::create(); - resolver->sem=NULL; + resolver->sem = NULL; if (resolver->sem) { - resolver->thread_abort=false; + resolver->thread_abort = false; - resolver->thread = Thread::create( _IP_ResolverPrivate::_thread_function,resolver ); + resolver->thread = Thread::create(_IP_ResolverPrivate::_thread_function, resolver); if (!resolver->thread) memdelete(resolver->sem); //wtf } else { - resolver->thread=NULL; + resolver->thread = NULL; } #else resolver->sem = NULL; - resolver->thread=NULL; + resolver->thread = NULL; #endif - - } IP::~IP() { #ifndef NO_THREADS if (resolver->thread) { - resolver->thread_abort=true; + resolver->thread_abort = true; resolver->sem->post(); Thread::wait_to_finish(resolver->thread); - memdelete( resolver->thread ); - memdelete( resolver->sem); + memdelete(resolver->thread); + memdelete(resolver->sem); } memdelete(resolver); #endif - } diff --git a/core/io/ip.h b/core/io/ip.h index 0a0e75fe7..2fa1e46d6 100644 --- a/core/io/ip.h +++ b/core/io/ip.h @@ -29,17 +29,16 @@ #ifndef IP_H #define IP_H - -#include "os/os.h" #include "io/ip_address.h" +#include "os/os.h" struct _IP_ResolverPrivate; class IP : public Object { - OBJ_TYPE( IP, Object ); + OBJ_TYPE(IP, Object); OBJ_CATEGORY("Networking"); -public: +public: enum ResolverStatus { RESOLVER_STATUS_NONE, @@ -58,47 +57,40 @@ public: enum { RESOLVER_MAX_QUERIES = 32, - RESOLVER_INVALID_ID=-1 + RESOLVER_INVALID_ID = -1 }; - typedef int ResolverID; - private: - _IP_ResolverPrivate *resolver; -protected: - static IP*singleton; +protected: + static IP *singleton; static void _bind_methods(); - virtual IP_Address _resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY)=0; + virtual IP_Address _resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY) = 0; Array _get_local_addresses() const; - static IP* (*_create)(); -public: - + static IP *(*_create)(); - - IP_Address resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY); +public: + IP_Address resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY); // async resolver hostname - ResolverID resolve_hostname_queue_item(const String& p_hostname, Type p_type = TYPE_ANY); + ResolverID resolve_hostname_queue_item(const String &p_hostname, Type p_type = TYPE_ANY); ResolverStatus get_resolve_item_status(ResolverID p_id) const; IP_Address get_resolve_item_address(ResolverID p_id) const; - virtual void get_local_addresses(List<IP_Address> *r_addresses) const=0; + virtual void get_local_addresses(List<IP_Address> *r_addresses) const = 0; void erase_resolve_item(ResolverID p_id); - void clear_cache(const String& p_hostname = ""); + void clear_cache(const String &p_hostname = ""); - static IP* get_singleton(); + static IP *get_singleton(); - static IP* create(); + static IP *create(); IP(); ~IP(); - - }; VARIANT_ENUM_CAST(IP::Type); diff --git a/core/io/ip_address.cpp b/core/io/ip_address.cpp index 1fda7fed7..e03dac8d3 100644 --- a/core/io/ip_address.cpp +++ b/core/io/ip_address.cpp @@ -33,29 +33,29 @@ IP_Address::operator Variant() const { return operator String(); }*/ -#include <string.h> #include <stdio.h> +#include <string.h> IP_Address::operator String() const { - if(is_ipv4()) + if (is_ipv4()) // IPv4 address mapped to IPv6 - return itos(field8[12])+"."+itos(field8[13])+"."+itos(field8[14])+"."+itos(field8[15]); + return itos(field8[12]) + "." + itos(field8[13]) + "." + itos(field8[14]) + "." + itos(field8[15]); String ret; - for (int i=0; i<8; i++) { + for (int i = 0; i < 8; i++) { if (i > 0) ret = ret + ":"; - uint16_t num = (field8[i*2] << 8) + field8[i*2+1]; + uint16_t num = (field8[i * 2] << 8) + field8[i * 2 + 1]; ret = ret + String::num_int64(num, 16); }; return ret; } -static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) { +static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) { uint16_t ret = 0; - for (int i=p_start; i<p_start + 4; i++) { + for (int i = p_start; i < p_start + 4; i++) { if (i >= p_string.length()) { break; @@ -84,17 +84,17 @@ static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) { p_dst[1] = ret & 0xff; }; -void IP_Address::_parse_ipv6(const String& p_string) { +void IP_Address::_parse_ipv6(const String &p_string) { static const int parts_total = 8; - int parts[parts_total] = {0}; + int parts[parts_total] = { 0 }; int parts_count = 0; bool part_found = false; bool part_skip = false; bool part_ipv4 = false; int parts_idx = 0; - for (int i=0; i<p_string.length(); i++) { + for (int i = 0; i < p_string.length(); i++) { CharType c = p_string[i]; if (c == ':') { @@ -130,26 +130,25 @@ void IP_Address::_parse_ipv6(const String& p_string) { }; int idx = 0; - for (int i=0; i<parts_idx; i++) { + for (int i = 0; i < parts_idx; i++) { if (parts[i] == -1) { - for (int j=0; j<parts_extra; j++) { + for (int j = 0; j < parts_extra; j++) { field16[idx++] = 0; }; continue; }; if (part_ipv4 && i == parts_idx - 1) { - _parse_ipv4(p_string, parts[i], (uint8_t*)&field16[idx]); // should be the last one + _parse_ipv4(p_string, parts[i], (uint8_t *)&field16[idx]); // should be the last one } else { - _parse_hex(p_string, parts[i], (uint8_t*)&(field16[idx++])); + _parse_hex(p_string, parts[i], (uint8_t *)&(field16[idx++])); }; }; - }; -void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret) { +void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret) { String ip; if (p_start != 0) { @@ -159,12 +158,12 @@ void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret }; int slices = ip.get_slice_count("."); - if (slices!=4) { - ERR_EXPLAIN("Invalid IP Address String: "+ip); + if (slices != 4) { + ERR_EXPLAIN("Invalid IP Address String: " + ip); ERR_FAIL(); } - for(int i=0;i<4;i++) { - p_ret[i]=ip.get_slicec('.',i).to_int(); + for (int i = 0; i < 4; i++) { + p_ret[i] = ip.get_slicec('.', i).to_int(); } }; @@ -173,32 +172,32 @@ void IP_Address::clear() { memset(&field8[0], 0, sizeof(field8)); }; -bool IP_Address::is_ipv4() const{ - return (field32[0]==0 && field32[1]==0 && field16[4]==0 && field16[5]==0xffff); +bool IP_Address::is_ipv4() const { + return (field32[0] == 0 && field32[1] == 0 && field16[4] == 0 && field16[5] == 0xffff); } -const uint8_t *IP_Address::get_ipv4() const{ - ERR_FAIL_COND_V(!is_ipv4(),0); +const uint8_t *IP_Address::get_ipv4() const { + ERR_FAIL_COND_V(!is_ipv4(), 0); return &(field8[12]); } void IP_Address::set_ipv4(const uint8_t *p_ip) { clear(); - field16[5]=0xffff; - field32[3]=*((const uint32_t *)p_ip); + field16[5] = 0xffff; + field32[3] = *((const uint32_t *)p_ip); } -const uint8_t *IP_Address::get_ipv6() const{ +const uint8_t *IP_Address::get_ipv6() const { return field8; } void IP_Address::set_ipv6(const uint8_t *p_buf) { clear(); - for (int i=0; i<16; i++) + for (int i = 0; i < 16; i++) field8[i] = p_buf[i]; } -IP_Address::IP_Address(const String& p_string) { +IP_Address::IP_Address(const String &p_string) { clear(); if (p_string.find(":") >= 0) { @@ -211,7 +210,7 @@ IP_Address::IP_Address(const String& p_string) { }; } -_FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) { +_FORCE_INLINE_ static void _32_to_buf(uint8_t *p_dst, uint32_t p_n) { p_dst[0] = (p_n >> 24) & 0xff; p_dst[1] = (p_n >> 16) & 0xff; @@ -219,16 +218,16 @@ _FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) { p_dst[3] = (p_n >> 0) & 0xff; }; -IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6) { +IP_Address::IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6) { clear(); if (!is_v6) { // Mapped to IPv6 - field16[5]=0xffff; - field8[12]=p_a; - field8[13]=p_b; - field8[14]=p_c; - field8[15]=p_d; + field16[5] = 0xffff; + field8[12] = p_a; + field8[13] = p_b; + field8[14] = p_c; + field8[15] = p_d; } else { _32_to_buf(&field8[0], p_a); @@ -236,5 +235,4 @@ IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool _32_to_buf(&field8[8], p_c); _32_to_buf(&field8[12], p_d); } - } diff --git a/core/io/ip_address.h b/core/io/ip_address.h index 87f32b0ac..200df57aa 100644 --- a/core/io/ip_address.h +++ b/core/io/ip_address.h @@ -34,7 +34,6 @@ struct IP_Address { private: - union { uint8_t field8[16]; uint16_t field16[8]; @@ -42,19 +41,19 @@ private: }; protected: - void _parse_ipv6(const String& p_string); - void _parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret); + void _parse_ipv6(const String &p_string); + void _parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret); public: //operator Variant() const; - bool operator==(const IP_Address& p_ip) const { - for (int i=0; i<4; i++) + bool operator==(const IP_Address &p_ip) const { + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return false; return true; } - bool operator!=(const IP_Address& p_ip) const { - for (int i=0; i<4; i++) + bool operator!=(const IP_Address &p_ip) const { + for (int i = 0; i < 4; i++) if (field32[i] != p_ip.field32[i]) return true; return false; @@ -69,11 +68,9 @@ public: void set_ipv6(const uint8_t *buf); operator String() const; - IP_Address(const String& p_string); - IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6=false); + IP_Address(const String &p_string); + IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6 = false); IP_Address() { clear(); } }; - - #endif // IP_ADDRESS_H diff --git a/core/io/json.cpp b/core/io/json.cpp index fac8ebe72..a10baf545 100644 --- a/core/io/json.cpp +++ b/core/io/json.cpp @@ -29,7 +29,7 @@ #include "json.h" #include "print_string.h" -const char * JSON::tk_name[TK_MAX] = { +const char *JSON::tk_name[TK_MAX] = { "'{'", "'}'", "'['", @@ -42,14 +42,12 @@ const char * JSON::tk_name[TK_MAX] = { "EOF", }; +String JSON::_print_var(const Variant &p_var) { - -String JSON::_print_var(const Variant& p_var) { - - switch(p_var.get_type()) { + switch (p_var.get_type()) { case Variant::NIL: return "null"; - case Variant::BOOL: return p_var.operator bool() ? "true": "false"; + case Variant::BOOL: return p_var.operator bool() ? "true" : "false"; case Variant::INT: return itos(p_var); case Variant::REAL: return rtos(p_var); case Variant::INT_ARRAY: @@ -59,12 +57,12 @@ String JSON::_print_var(const Variant& p_var) { String s = "["; Array a = p_var; - for(int i=0;i<a.size();i++) { - if (i>0) - s+=", "; - s+=_print_var(a[i]); + for (int i = 0; i < a.size(); i++) { + if (i > 0) + s += ", "; + s += _print_var(a[i]); } - s+="]"; + s += "]"; return s; }; case Variant::DICTIONARY: { @@ -74,34 +72,31 @@ String JSON::_print_var(const Variant& p_var) { List<Variant> keys; d.get_key_list(&keys); - for (List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { - if (E!=keys.front()) - s+=", "; - s+=_print_var(String(E->get())); - s+=":"; - s+=_print_var(d[E->get()]); + if (E != keys.front()) + s += ", "; + s += _print_var(String(E->get())); + s += ":"; + s += _print_var(d[E->get()]); } - s+="}"; + s += "}"; return s; }; - default: return "\""+String(p_var).json_escape()+"\""; - + default: return "\"" + String(p_var).json_escape() + "\""; } - } -String JSON::print(const Dictionary& p_dict) { +String JSON::print(const Dictionary &p_dict) { return _print_var(p_dict); } - -Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_token,int &line,String &r_err_str) { +Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token &r_token, int &line, String &r_err_str) { while (true) { - switch(p_str[idx]) { + switch (p_str[idx]) { case '\n': { @@ -110,42 +105,42 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke break; }; case 0: { - r_token.type=TK_EOF; + r_token.type = TK_EOF; return OK; } break; case '{': { - r_token.type=TK_CURLY_BRACKET_OPEN; + r_token.type = TK_CURLY_BRACKET_OPEN; idx++; return OK; }; case '}': { - r_token.type=TK_CURLY_BRACKET_CLOSE; + r_token.type = TK_CURLY_BRACKET_CLOSE; idx++; return OK; }; case '[': { - r_token.type=TK_BRACKET_OPEN; + r_token.type = TK_BRACKET_OPEN; idx++; return OK; }; case ']': { - r_token.type=TK_BRACKET_CLOSE; + r_token.type = TK_BRACKET_CLOSE; idx++; return OK; }; case ':': { - r_token.type=TK_COLON; + r_token.type = TK_COLON; idx++; return OK; }; case ',': { - r_token.type=TK_COMMA; + r_token.type = TK_COMMA; idx++; return OK; }; @@ -153,66 +148,62 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke idx++; String str; - while(true) { - if (p_str[idx]==0) { - r_err_str="Unterminated String"; + while (true) { + if (p_str[idx] == 0) { + r_err_str = "Unterminated String"; return ERR_PARSE_ERROR; - } else if (p_str[idx]=='"') { + } else if (p_str[idx] == '"') { idx++; break; - } else if (p_str[idx]=='\\') { + } else if (p_str[idx] == '\\') { //escaped characters... idx++; CharType next = p_str[idx]; - if (next==0) { - r_err_str="Unterminated String"; - return ERR_PARSE_ERROR; + if (next == 0) { + r_err_str = "Unterminated String"; + return ERR_PARSE_ERROR; } - CharType res=0; + CharType res = 0; - switch(next) { + switch (next) { - case 'b': res=8; break; - case 't': res=9; break; - case 'n': res=10; break; - case 'f': res=12; break; - case 'r': res=13; break; + case 'b': res = 8; break; + case 't': res = 9; break; + case 'n': res = 10; break; + case 'f': res = 12; break; + case 'r': res = 13; break; case 'u': { //hexnumbarh - oct is deprecated - - for(int j=0;j<4;j++) { - CharType c = p_str[idx+j+1]; - if (c==0) { - r_err_str="Unterminated String"; + for (int j = 0; j < 4; j++) { + CharType c = p_str[idx + j + 1]; + if (c == 0) { + r_err_str = "Unterminated String"; return ERR_PARSE_ERROR; } - if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { - r_err_str="Malformed hex constant in string"; + r_err_str = "Malformed hex constant in string"; return ERR_PARSE_ERROR; } CharType v; - if (c>='0' && c<='9') { - v=c-'0'; - } else if (c>='a' && c<='f') { - v=c-'a'; - v+=10; - } else if (c>='A' && c<='F') { - v=c-'A'; - v+=10; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a'; + v += 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A'; + v += 10; } else { ERR_PRINT("BUG"); - v=0; + v = 0; } - res<<=4; - res|=v; - - + res <<= 4; + res |= v; } - idx+=4; //will add at the end anyway - + idx += 4; //will add at the end anyway } break; //case '\"': res='\"'; break; @@ -225,253 +216,236 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke } break; } - str+=res; + str += res; } else { - if (p_str[idx]=='\n') + if (p_str[idx] == '\n') line++; - str+=p_str[idx]; + str += p_str[idx]; } idx++; } - r_token.type=TK_STRING; - r_token.value=str; + r_token.type = TK_STRING; + r_token.value = str; return OK; } break; default: { - if (p_str[idx]<=32) { + if (p_str[idx] <= 32) { idx++; break; } - if (p_str[idx]=='-' || (p_str[idx]>='0' && p_str[idx]<='9')) { + if (p_str[idx] == '-' || (p_str[idx] >= '0' && p_str[idx] <= '9')) { //a number const CharType *rptr; - double number = String::to_double(&p_str[idx],&rptr); - idx+=(rptr - &p_str[idx]); - r_token.type=TK_NUMBER; - r_token.value=number; + double number = String::to_double(&p_str[idx], &rptr); + idx += (rptr - &p_str[idx]); + r_token.type = TK_NUMBER; + r_token.value = number; return OK; - } else if ((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) { + } else if ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) { String id; - while((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) { + while ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) { - id+=p_str[idx]; + id += p_str[idx]; idx++; } - r_token.type=TK_IDENTIFIER; - r_token.value=id; + r_token.type = TK_IDENTIFIER; + r_token.value = id; return OK; } else { - r_err_str="Unexpected character."; + r_err_str = "Unexpected character."; return ERR_PARSE_ERROR; } } - } } return ERR_PARSE_ERROR; } +Error JSON::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { - -Error JSON::_parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { - - - if (token.type==TK_CURLY_BRACKET_OPEN) { + if (token.type == TK_CURLY_BRACKET_OPEN) { Dictionary d(true); - Error err = _parse_object(d,p_str,index,p_len,line,r_err_str); + Error err = _parse_object(d, p_str, index, p_len, line, r_err_str); if (err) return err; - value=d; + value = d; return OK; - } else if (token.type==TK_BRACKET_OPEN) { + } else if (token.type == TK_BRACKET_OPEN) { Array a(true); - Error err = _parse_array(a,p_str,index,p_len,line,r_err_str); + Error err = _parse_array(a, p_str, index, p_len, line, r_err_str); if (err) return err; - value=a; + value = a; return OK; - } else if (token.type==TK_IDENTIFIER) { + } else if (token.type == TK_IDENTIFIER) { String id = token.value; - if (id=="true") - value=true; - else if (id=="false") - value=false; - else if (id=="null") - value=Variant(); + if (id == "true") + value = true; + else if (id == "false") + value = false; + else if (id == "null") + value = Variant(); else { - r_err_str="Expected 'true','false' or 'null', got '"+id+"'."; + r_err_str = "Expected 'true','false' or 'null', got '" + id + "'."; return ERR_PARSE_ERROR; } return OK; - } else if (token.type==TK_NUMBER) { + } else if (token.type == TK_NUMBER) { - value=token.value; + value = token.value; return OK; - } else if (token.type==TK_STRING) { + } else if (token.type == TK_STRING) { - value=token.value; + value = token.value; return OK; } else { - r_err_str="Expected value, got "+String(tk_name[token.type])+"."; + r_err_str = "Expected value, got " + String(tk_name[token.type]) + "."; return ERR_PARSE_ERROR; } return ERR_PARSE_ERROR; } - -Error JSON::_parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { +Error JSON::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { Token token; - bool need_comma=false; - + bool need_comma = false; - while(index<p_len) { + while (index < p_len) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_BRACKET_CLOSE) { + if (token.type == TK_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected ','"; + r_err_str = "Expected ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str); if (err) return err; array.push_back(v); - need_comma=true; - + need_comma = true; } return ERR_PARSE_ERROR; - } -Error JSON::_parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) { +Error JSON::_parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) { - bool at_key=true; + bool at_key = true; String key; Token token; - bool need_comma=false; - - - while(index<p_len) { + bool need_comma = false; + while (index < p_len) { if (at_key) { - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type==TK_CURLY_BRACKET_CLOSE) { + if (token.type == TK_CURLY_BRACKET_CLOSE) { return OK; } if (need_comma) { - if (token.type!=TK_COMMA) { + if (token.type != TK_COMMA) { - r_err_str="Expected '}' or ','"; + r_err_str = "Expected '}' or ','"; return ERR_PARSE_ERROR; } else { - need_comma=false; + need_comma = false; continue; } } - if (token.type!=TK_STRING) { - + if (token.type != TK_STRING) { - r_err_str="Expected key"; + r_err_str = "Expected key"; return ERR_PARSE_ERROR; } - key=token.value; - err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + key = token.value; + err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; - if (token.type!=TK_COLON) { + if (token.type != TK_COLON) { - r_err_str="Expected ':'"; + r_err_str = "Expected ':'"; return ERR_PARSE_ERROR; } - at_key=false; + at_key = false; } else { - - Error err = _get_token(p_str,index,p_len,token,line,r_err_str); - if (err!=OK) + Error err = _get_token(p_str, index, p_len, token, line, r_err_str); + if (err != OK) return err; Variant v; - err = _parse_value(v,token,p_str,index,p_len,line,r_err_str); + err = _parse_value(v, token, p_str, index, p_len, line, r_err_str); if (err) return err; - object[key]=v; - need_comma=true; - at_key=true; + object[key] = v; + need_comma = true; + at_key = true; } } return ERR_PARSE_ERROR; } - -Error JSON::parse(const String& p_json,Dictionary& r_ret,String &r_err_str,int &r_err_line) { - +Error JSON::parse(const String &p_json, Dictionary &r_ret, String &r_err_str, int &r_err_line) { const CharType *str = p_json.ptr(); int idx = 0; int len = p_json.length(); Token token; - int line=0; + int line = 0; String aux_key; - Error err = _get_token(str,idx,len,token,line,r_err_str); + Error err = _get_token(str, idx, len, token, line, r_err_str); if (err) return err; - if (token.type!=TK_CURLY_BRACKET_OPEN) { + if (token.type != TK_CURLY_BRACKET_OPEN) { - r_err_str="Expected '{'"; + r_err_str = "Expected '{'"; return ERR_PARSE_ERROR; } - return _parse_object(r_ret,str,idx,len,r_err_line,r_err_str); - + return _parse_object(r_ret, str, idx, len, r_err_line, r_err_str); } - - diff --git a/core/io/json.h b/core/io/json.h index 52fcac145..86881c7fd 100644 --- a/core/io/json.h +++ b/core/io/json.h @@ -29,11 +29,8 @@ #ifndef JSON_H #define JSON_H - - #include "variant.h" - class JSON { enum TokenType { @@ -64,18 +61,18 @@ class JSON { Variant value; }; - static const char * tk_name[TK_MAX]; + static const char *tk_name[TK_MAX]; - static String _print_var(const Variant& p_var); + static String _print_var(const Variant &p_var); - static Error _get_token(const CharType *p_str,int &index, int p_len,Token& r_token,int &line,String &r_err_str); - static Error _parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); - static Error _parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); - static Error _parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str); + static Error _get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str); + static Error _parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); + static Error _parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); + static Error _parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str); public: - static String print(const Dictionary& p_dict); - static Error parse(const String& p_json,Dictionary& r_ret,String &r_err_str,int &r_err_line); + static String print(const Dictionary &p_dict); + static Error parse(const String &p_json, Dictionary &r_ret, String &r_err_str, int &r_err_line); }; #endif // JSON_H diff --git a/core/io/marshalls.cpp b/core/io/marshalls.cpp index 6032d8210..eb669a658 100644 --- a/core/io/marshalls.cpp +++ b/core/io/marshalls.cpp @@ -27,79 +27,77 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "marshalls.h" -#include "print_string.h" #include "os/keyboard.h" +#include "print_string.h" #include <stdio.h> -Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len) { +Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) { - const uint8_t * buf=p_buffer; - int len=p_len; + const uint8_t *buf = p_buffer; + int len = p_len; - if (len<4) { + if (len < 4) { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); } + uint32_t type = decode_uint32(buf); - uint32_t type=decode_uint32(buf); + ERR_FAIL_COND_V(type >= Variant::VARIANT_MAX, ERR_INVALID_DATA); - ERR_FAIL_COND_V(type>=Variant::VARIANT_MAX,ERR_INVALID_DATA); - - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) - *r_len=4; + *r_len = 4; - switch(type) { + switch (type) { case Variant::NIL: { - r_variant=Variant(); + r_variant = Variant(); } break; case Variant::BOOL: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); bool val = decode_uint32(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case Variant::INT: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int val = decode_uint32(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case Variant::REAL: { - ERR_FAIL_COND_V(len<(int)4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4, ERR_INVALID_DATA); float val = decode_float(buf); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case Variant::STRING: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); - r_variant=str; + str.parse_utf8((const char *)buf, strlen); + r_variant = str; if (r_len) { - if (strlen%4) - (*r_len)+=4-strlen%4; - (*r_len)+=4+strlen; - + if (strlen % 4) + (*r_len) += 4 - strlen % 4; + (*r_len) += 4 + strlen; } } break; @@ -107,268 +105,262 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * case Variant::VECTOR2: { - ERR_FAIL_COND_V(len<(int)4*2,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 2, ERR_INVALID_DATA); Vector2 val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + r_variant = val; if (r_len) - (*r_len)+=4*2; + (*r_len) += 4 * 2; - } break; // 5 + } break; // 5 case Variant::RECT2: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Rect2 val; - val.pos.x=decode_float(&buf[0]); - val.pos.y=decode_float(&buf[4]); - val.size.x=decode_float(&buf[8]); - val.size.y=decode_float(&buf[12]); - r_variant=val; + val.pos.x = decode_float(&buf[0]); + val.pos.y = decode_float(&buf[4]); + val.size.x = decode_float(&buf[8]); + val.size.y = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::VECTOR3: { - ERR_FAIL_COND_V(len<(int)4*3,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 3, ERR_INVALID_DATA); Vector3 val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - val.z=decode_float(&buf[8]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + val.z = decode_float(&buf[8]); + r_variant = val; if (r_len) - (*r_len)+=4*3; + (*r_len) += 4 * 3; } break; case Variant::MATRIX32: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); Matrix32 val; - for(int i=0;i<3;i++) { - for(int j=0;j<2;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - val.elements[i][j]=decode_float(&buf[(i*2+j)*4]); + val.elements[i][j] = decode_float(&buf[(i * 2 + j) * 4]); } } - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*6; + (*r_len) += 4 * 6; } break; case Variant::PLANE: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Plane val; - val.normal.x=decode_float(&buf[0]); - val.normal.y=decode_float(&buf[4]); - val.normal.z=decode_float(&buf[8]); - val.d=decode_float(&buf[12]); - r_variant=val; + val.normal.x = decode_float(&buf[0]); + val.normal.y = decode_float(&buf[4]); + val.normal.z = decode_float(&buf[8]); + val.d = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::QUAT: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Quat val; - val.x=decode_float(&buf[0]); - val.y=decode_float(&buf[4]); - val.z=decode_float(&buf[8]); - val.w=decode_float(&buf[12]); - r_variant=val; + val.x = decode_float(&buf[0]); + val.y = decode_float(&buf[4]); + val.z = decode_float(&buf[8]); + val.w = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::_AABB: { - ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA); AABB val; - val.pos.x=decode_float(&buf[0]); - val.pos.y=decode_float(&buf[4]); - val.pos.z=decode_float(&buf[8]); - val.size.x=decode_float(&buf[12]); - val.size.y=decode_float(&buf[16]); - val.size.z=decode_float(&buf[20]); - r_variant=val; + val.pos.x = decode_float(&buf[0]); + val.pos.y = decode_float(&buf[4]); + val.pos.z = decode_float(&buf[8]); + val.size.x = decode_float(&buf[12]); + val.size.y = decode_float(&buf[16]); + val.size.z = decode_float(&buf[20]); + r_variant = val; if (r_len) - (*r_len)+=4*6; + (*r_len) += 4 * 6; } break; case Variant::MATRIX3: { - ERR_FAIL_COND_V(len<(int)4*9,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 9, ERR_INVALID_DATA); Matrix3 val; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - val.elements[i][j]=decode_float(&buf[(i*3+j)*4]); + val.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*9; + (*r_len) += 4 * 9; } break; case Variant::TRANSFORM: { - ERR_FAIL_COND_V(len<(int)4*12,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 12, ERR_INVALID_DATA); Transform val; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - val.basis.elements[i][j]=decode_float(&buf[(i*3+j)*4]); + val.basis.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } - val.origin[0]=decode_float(&buf[36]); - val.origin[1]=decode_float(&buf[40]); - val.origin[2]=decode_float(&buf[44]); + val.origin[0] = decode_float(&buf[36]); + val.origin[1] = decode_float(&buf[40]); + val.origin[2] = decode_float(&buf[44]); - r_variant=val; + r_variant = val; if (r_len) - (*r_len)+=4*12; + (*r_len) += 4 * 12; } break; // misc types case Variant::COLOR: { - ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA); Color val; - val.r=decode_float(&buf[0]); - val.g=decode_float(&buf[4]); - val.b=decode_float(&buf[8]); - val.a=decode_float(&buf[12]); - r_variant=val; + val.r = decode_float(&buf[0]); + val.g = decode_float(&buf[4]); + val.b = decode_float(&buf[8]); + val.a = decode_float(&buf[12]); + r_variant = val; if (r_len) - (*r_len)+=4*4; + (*r_len) += 4 * 4; } break; case Variant::IMAGE: { - ERR_FAIL_COND_V(len<(int)5*4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < (int)5 * 4, ERR_INVALID_DATA); Image::Format fmt = (Image::Format)decode_uint32(&buf[0]); - ERR_FAIL_INDEX_V( fmt, Image::FORMAT_MAX, ERR_INVALID_DATA); + ERR_FAIL_INDEX_V(fmt, Image::FORMAT_MAX, ERR_INVALID_DATA); uint32_t mipmaps = decode_uint32(&buf[4]); uint32_t w = decode_uint32(&buf[8]); uint32_t h = decode_uint32(&buf[12]); uint32_t datalen = decode_uint32(&buf[16]); Image img; - if (datalen>0) { - len-=5*4; - ERR_FAIL_COND_V( len < datalen, ERR_INVALID_DATA ); + if (datalen > 0) { + len -= 5 * 4; + ERR_FAIL_COND_V(len < datalen, ERR_INVALID_DATA); DVector<uint8_t> data; data.resize(datalen); DVector<uint8_t>::Write wr = data.write(); - copymem(&wr[0],&buf[20],datalen); + copymem(&wr[0], &buf[20], datalen); wr = DVector<uint8_t>::Write(); - - - img=Image(w,h,mipmaps,fmt,data); + img = Image(w, h, mipmaps, fmt, data); } - r_variant=img; + r_variant = img; if (r_len) { - if (datalen%4) - (*r_len)+=4-datalen%4; + if (datalen % 4) + (*r_len) += 4 - datalen % 4; - (*r_len)+=4*5+datalen; + (*r_len) += 4 * 5 + datalen; } } break; case Variant::NODE_PATH: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - if (strlen&0x80000000) { + if (strlen & 0x80000000) { //new format - ERR_FAIL_COND_V(len<12,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 12, ERR_INVALID_DATA); Vector<StringName> names; Vector<StringName> subnames; StringName prop; - uint32_t namecount=strlen&=0x7FFFFFFF; - uint32_t subnamecount = decode_uint32(buf+4); - uint32_t flags = decode_uint32(buf+8); + uint32_t namecount = strlen &= 0x7FFFFFFF; + uint32_t subnamecount = decode_uint32(buf + 4); + uint32_t flags = decode_uint32(buf + 8); - len-=12; - buf+=12; + len -= 12; + buf += 12; - int total=namecount+subnamecount; - if (flags&2) + int total = namecount + subnamecount; + if (flags & 2) total++; if (r_len) - (*r_len)+=12; + (*r_len) += 12; + for (int i = 0; i < total; i++) { - for(int i=0;i<total;i++) { - - ERR_FAIL_COND_V((int)len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)len < 4, ERR_INVALID_DATA); strlen = decode_uint32(buf); - int pad=0; + int pad = 0; - if (strlen%4) - pad+=4-strlen%4; + if (strlen % 4) + pad += 4 - strlen % 4; - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen+pad>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen + pad > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); - - if (i<namecount) + if (i < namecount) names.push_back(str); - else if (i<namecount+subnamecount) + else if (i < namecount + subnamecount) subnames.push_back(str); else - prop=str; + prop = str; - buf+=strlen+pad; - len-=strlen+pad; + buf += strlen + pad; + len -= strlen + pad; if (r_len) - (*r_len)+=4+strlen+pad; - + (*r_len) += 4 + strlen + pad; } - r_variant=NodePath(names,subnames,flags&1,prop); + r_variant = NodePath(names, subnames, flags & 1, prop); } else { //old format, just a string - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); - r_variant=NodePath(str); + r_variant = NodePath(str); if (r_len) - (*r_len)+=4+strlen; + (*r_len) += 4 + strlen; } } break; @@ -383,64 +375,62 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * } break; case Variant::OBJECT: { - - r_variant = (Object*)NULL; + r_variant = (Object *)NULL; } break; case Variant::INPUT_EVENT: { InputEvent ie; - ie.type=decode_uint32(&buf[0]); - ie.device=decode_uint32(&buf[4]); + ie.type = decode_uint32(&buf[0]); + ie.device = decode_uint32(&buf[4]); if (r_len) - (*r_len)+=12; + (*r_len) += 12; - switch(ie.type) { + switch (ie.type) { case InputEvent::KEY: { - uint32_t mods=decode_uint32(&buf[12]); - if (mods&KEY_MASK_SHIFT) - ie.key.mod.shift=true; - if (mods&KEY_MASK_CTRL) - ie.key.mod.control=true; - if (mods&KEY_MASK_ALT) - ie.key.mod.alt=true; - if (mods&KEY_MASK_META) - ie.key.mod.meta=true; - ie.key.scancode=decode_uint32(&buf[16]); + uint32_t mods = decode_uint32(&buf[12]); + if (mods & KEY_MASK_SHIFT) + ie.key.mod.shift = true; + if (mods & KEY_MASK_CTRL) + ie.key.mod.control = true; + if (mods & KEY_MASK_ALT) + ie.key.mod.alt = true; + if (mods & KEY_MASK_META) + ie.key.mod.meta = true; + ie.key.scancode = decode_uint32(&buf[16]); if (r_len) - (*r_len)+=8; - + (*r_len) += 8; } break; case InputEvent::MOUSE_BUTTON: { - ie.mouse_button.button_index=decode_uint32(&buf[12]); + ie.mouse_button.button_index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::JOYSTICK_BUTTON: { - ie.joy_button.button_index=decode_uint32(&buf[12]); + ie.joy_button.button_index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::SCREEN_TOUCH: { - ie.screen_touch.index=decode_uint32(&buf[12]); + ie.screen_touch.index = decode_uint32(&buf[12]); if (r_len) - (*r_len)+=4; + (*r_len) += 4; } break; case InputEvent::JOYSTICK_MOTION: { - ie.joy_motion.axis=decode_uint32(&buf[12]); - ie.joy_motion.axis_value=decode_float(&buf[16]); + ie.joy_motion.axis = decode_uint32(&buf[12]); + ie.joy_motion.axis_value = decode_float(&buf[16]); if (r_len) - (*r_len)+=8; + (*r_len) += 8; } break; } @@ -449,125 +439,121 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * } break; case Variant::DICTIONARY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); - uint32_t count = decode_uint32(buf); - bool shared = count&0x80000000; - count&=0x7FFFFFFF; + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); + uint32_t count = decode_uint32(buf); + bool shared = count & 0x80000000; + count &= 0x7FFFFFFF; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } - Dictionary d(shared); + Dictionary d(shared); - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - Variant key,value; + Variant key, value; int used; - Error err = decode_variant(key,buf,len,&used); - ERR_FAIL_COND_V(err,err); + Error err = decode_variant(key, buf, len, &used); + ERR_FAIL_COND_V(err, err); - buf+=used; - len-=used; + buf += used; + len -= used; if (r_len) { - (*r_len)+=used; + (*r_len) += used; } - err = decode_variant(value,buf,len,&used); - ERR_FAIL_COND_V(err,err); + err = decode_variant(value, buf, len, &used); + ERR_FAIL_COND_V(err, err); - buf+=used; - len-=used; + buf += used; + len -= used; if (r_len) { - (*r_len)+=used; + (*r_len) += used; } - d[key]=value; + d[key] = value; } - r_variant=d; + r_variant = d; } break; case Variant::ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - bool shared = count&0x80000000; - count&=0x7FFFFFFF; + bool shared = count & 0x80000000; + count &= 0x7FFFFFFF; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } - Array varr(shared); + Array varr(shared); - for(uint32_t i=0;i<count;i++) { + for (uint32_t i = 0; i < count; i++) { - int used=0; + int used = 0; Variant v; - Error err = decode_variant(v,buf,len,&used); - ERR_FAIL_COND_V(err,err); - buf+=used; - len-=used; + Error err = decode_variant(v, buf, len, &used); + ERR_FAIL_COND_V(err, err); + buf += used; + len -= used; varr.push_back(v); if (r_len) { - (*r_len)+=used; + (*r_len) += used; } } - r_variant=varr; - + r_variant = varr; } break; // arrays case Variant::RAW_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count>len,ERR_INVALID_DATA); - + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count > len, ERR_INVALID_DATA); DVector<uint8_t> data; if (count) { data.resize(count); DVector<uint8_t>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=buf[i]; + w[i] = buf[i]; } w = DVector<uint8_t>::Write(); } - r_variant=data; + r_variant = data; if (r_len) { - if (count%4) - (*r_len)+=4-count%4; - (*r_len)+=4+count; + if (count % 4) + (*r_len) += 4 - count % 4; + (*r_len) += 4 + count; } - - } break; case Variant::INT_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA); DVector<int> data; @@ -575,26 +561,26 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const int*rbuf=(const int*)buf; data.resize(count); DVector<int>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=decode_uint32(&buf[i*4]); + w[i] = decode_uint32(&buf[i * 4]); } w = DVector<int>::Write(); } - r_variant=Variant(data); + r_variant = Variant(data); if (r_len) { - (*r_len)+=4+count*sizeof(int); + (*r_len) += 4 + count * sizeof(int); } } break; case Variant::REAL_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA); DVector<float> data; @@ -602,186 +588,177 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * //const float*rbuf=(const float*)buf; data.resize(count); DVector<float>::Write w = data.write(); - for(int i=0;i<count;i++) { + for (int i = 0; i < count; i++) { - w[i]=decode_float(&buf[i*4]); + w[i] = decode_float(&buf[i * 4]); } w = DVector<float>::Write(); } - r_variant=data; + r_variant = data; if (r_len) { - (*r_len)+=4+count*sizeof(float); + (*r_len) += 4 + count * sizeof(float); } - } break; case Variant::STRING_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); DVector<String> strings; - buf+=4; - len-=4; + buf += 4; + len -= 4; if (r_len) - (*r_len)+=4; + (*r_len) += 4; //printf("string count: %i\n",count); - for(int i=0;i<(int)count;i++) { + for (int i = 0; i < (int)count; i++) { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t strlen = decode_uint32(buf); - buf+=4; - len-=4; - ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA); + buf += 4; + len -= 4; + ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA); //printf("loaded string: %s\n",(const char*)buf); String str; - str.parse_utf8((const char*)buf,strlen); + str.parse_utf8((const char *)buf, strlen); strings.push_back(str); - buf+=strlen; - len-=strlen; + buf += strlen; + len -= strlen; if (r_len) - (*r_len)+=4+strlen; + (*r_len) += 4 + strlen; - if (strlen%4) { - int pad = 4-(strlen%4); - buf+=pad; - len-=pad; + if (strlen % 4) { + int pad = 4 - (strlen % 4); + buf += pad; + len -= pad; if (r_len) { - (*r_len)+=pad; + (*r_len) += pad; } } - } - r_variant=strings; - + r_variant = strings; } break; case Variant::VECTOR2_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); - buf+=4; - len-=4; + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*2>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 2 > len, ERR_INVALID_DATA); DVector<Vector2> varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); DVector<Vector2>::Write w = varray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].x=decode_float(buf+i*4*2+4*0); - w[i].y=decode_float(buf+i*4*2+4*1); + for (int i = 0; i < (int)count; i++) { + w[i].x = decode_float(buf + i * 4 * 2 + 4 * 0); + w[i].y = decode_float(buf + i * 4 * 2 + 4 * 1); } - int adv = 4*2*count; + int adv = 4 * 2 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=varray; + r_variant = varray; } break; case Variant::VECTOR3_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); - buf+=4; - len-=4; + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*3>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 3 > len, ERR_INVALID_DATA); DVector<Vector3> varray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { varray.resize(count); DVector<Vector3>::Write w = varray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].x=decode_float(buf+i*4*3+4*0); - w[i].y=decode_float(buf+i*4*3+4*1); - w[i].z=decode_float(buf+i*4*3+4*2); + for (int i = 0; i < (int)count; i++) { + w[i].x = decode_float(buf + i * 4 * 3 + 4 * 0); + w[i].y = decode_float(buf + i * 4 * 3 + 4 * 1); + w[i].z = decode_float(buf + i * 4 * 3 + 4 * 2); } - int adv = 4*3*count; + int adv = 4 * 3 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=varray; + r_variant = varray; } break; case Variant::COLOR_ARRAY: { - ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA); + ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); uint32_t count = decode_uint32(buf); - ERR_FAIL_COND_V(count<0,ERR_INVALID_DATA); - buf+=4; - len-=4; + ERR_FAIL_COND_V(count < 0, ERR_INVALID_DATA); + buf += 4; + len -= 4; - ERR_FAIL_COND_V((int)count*4*4>len,ERR_INVALID_DATA); + ERR_FAIL_COND_V((int)count * 4 * 4 > len, ERR_INVALID_DATA); DVector<Color> carray; if (r_len) { - (*r_len)+=4; + (*r_len) += 4; } if (count) { carray.resize(count); DVector<Color>::Write w = carray.write(); - for(int i=0;i<(int)count;i++) { - - w[i].r=decode_float(buf+i*4*4+4*0); - w[i].g=decode_float(buf+i*4*4+4*1); - w[i].b=decode_float(buf+i*4*4+4*2); - w[i].a=decode_float(buf+i*4*4+4*3); + for (int i = 0; i < (int)count; i++) { + w[i].r = decode_float(buf + i * 4 * 4 + 4 * 0); + w[i].g = decode_float(buf + i * 4 * 4 + 4 * 1); + w[i].b = decode_float(buf + i * 4 * 4 + 4 * 2); + w[i].a = decode_float(buf + i * 4 * 4 + 4 * 3); } - int adv = 4*4*count; + int adv = 4 * 4 * count; if (r_len) - (*r_len)+=adv; - len-=adv; - buf+=adv; - + (*r_len) += adv; + len -= adv; + buf += adv; } - r_variant=carray; + r_variant = carray; } break; default: { ERR_FAIL_V(ERR_BUG); } @@ -790,19 +767,19 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int * return OK; } -Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { +Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) { - uint8_t * buf=r_buffer; + uint8_t *buf = r_buffer; - r_len=0; + r_len = 0; if (buf) { - encode_uint32(p_variant.get_type(),buf); - buf+=4; + encode_uint32(p_variant.get_type(), buf); + buf += 4; } - r_len+=4; + r_len += 4; - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::NIL: { @@ -811,96 +788,94 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::BOOL: { if (buf) { - encode_uint32(p_variant.operator bool(),buf); + encode_uint32(p_variant.operator bool(), buf); } - r_len+=4; + r_len += 4; } break; case Variant::INT: { if (buf) { - encode_uint32(p_variant.operator int(),buf); + encode_uint32(p_variant.operator int(), buf); } - r_len+=4; + r_len += 4; } break; case Variant::REAL: { if (buf) { - encode_float(p_variant.operator float(),buf); + encode_float(p_variant.operator float(), buf); } - r_len+=4; + r_len += 4; } break; case Variant::NODE_PATH: { - NodePath np=p_variant; + NodePath np = p_variant; if (buf) { - encode_uint32(uint32_t(np.get_name_count())|0x80000000,buf); //for compatibility with the old format - encode_uint32(np.get_subname_count(),buf+4); - uint32_t flags=0; + encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format + encode_uint32(np.get_subname_count(), buf + 4); + uint32_t flags = 0; if (np.is_absolute()) - flags|=1; - if (np.get_property()!=StringName()) - flags|=2; + flags |= 1; + if (np.get_property() != StringName()) + flags |= 2; - encode_uint32(flags,buf+8); + encode_uint32(flags, buf + 8); - buf+=12; + buf += 12; } - r_len+=12; + r_len += 12; - int total = np.get_name_count()+np.get_subname_count(); - if (np.get_property()!=StringName()) + int total = np.get_name_count() + np.get_subname_count(); + if (np.get_property() != StringName()) total++; - for(int i=0;i<total;i++) { + for (int i = 0; i < total; i++) { String str; - if (i<np.get_name_count()) - str=np.get_name(i); - else if (i<np.get_name_count()+np.get_subname_count()) - str=np.get_subname(i-np.get_subname_count()); + if (i < np.get_name_count()) + str = np.get_name(i); + else if (i < np.get_name_count() + np.get_subname_count()) + str = np.get_subname(i - np.get_subname_count()); else - str=np.get_property(); + str = np.get_property(); CharString utf8 = str.utf8(); int pad = 0; - if (utf8.length()%4) - pad=4-utf8.length()%4; + if (utf8.length() % 4) + pad = 4 - utf8.length() % 4; if (buf) { - encode_uint32(utf8.length(),buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()); - buf+=pad+utf8.length(); + encode_uint32(utf8.length(), buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length()); + buf += pad + utf8.length(); } - - r_len+=4+utf8.length()+pad; + r_len += 4 + utf8.length() + pad; } } break; case Variant::STRING: { - CharString utf8 = p_variant.operator String().utf8(); if (buf) { - encode_uint32(utf8.length(),buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()); + encode_uint32(utf8.length(), buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length()); } - r_len+=4+utf8.length(); - while (r_len%4) + r_len += 4 + utf8.length(); + while (r_len % 4) r_len++; //pad } break; @@ -909,132 +884,126 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::VECTOR2: { if (buf) { - Vector2 v2=p_variant; - encode_float(v2.x,&buf[0]); - encode_float(v2.y,&buf[4]); - + Vector2 v2 = p_variant; + encode_float(v2.x, &buf[0]); + encode_float(v2.y, &buf[4]); } - r_len+=2*4; + r_len += 2 * 4; - } break; // 5 + } break; // 5 case Variant::RECT2: { if (buf) { - Rect2 r2=p_variant; - encode_float(r2.pos.x,&buf[0]); - encode_float(r2.pos.y,&buf[4]); - encode_float(r2.size.x,&buf[8]); - encode_float(r2.size.y,&buf[12]); + Rect2 r2 = p_variant; + encode_float(r2.pos.x, &buf[0]); + encode_float(r2.pos.y, &buf[4]); + encode_float(r2.size.x, &buf[8]); + encode_float(r2.size.y, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::VECTOR3: { if (buf) { - Vector3 v3=p_variant; - encode_float(v3.x,&buf[0]); - encode_float(v3.y,&buf[4]); - encode_float(v3.z,&buf[8]); + Vector3 v3 = p_variant; + encode_float(v3.x, &buf[0]); + encode_float(v3.y, &buf[4]); + encode_float(v3.z, &buf[8]); } - r_len+=3*4; + r_len += 3 * 4; } break; case Variant::MATRIX32: { if (buf) { - Matrix32 val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<2;j++) { + Matrix32 val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - copymem(&buf[(i*2+j)*4],&val.elements[i][j],sizeof(float)); + copymem(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float)); } } } - - r_len+=6*4; + r_len += 6 * 4; } break; case Variant::PLANE: { if (buf) { - Plane p=p_variant; - encode_float(p.normal.x,&buf[0]); - encode_float(p.normal.y,&buf[4]); - encode_float(p.normal.z,&buf[8]); - encode_float(p.d,&buf[12]); + Plane p = p_variant; + encode_float(p.normal.x, &buf[0]); + encode_float(p.normal.y, &buf[4]); + encode_float(p.normal.z, &buf[8]); + encode_float(p.d, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::QUAT: { if (buf) { - Quat q=p_variant; - encode_float(q.x,&buf[0]); - encode_float(q.y,&buf[4]); - encode_float(q.z,&buf[8]); - encode_float(q.w,&buf[12]); + Quat q = p_variant; + encode_float(q.x, &buf[0]); + encode_float(q.y, &buf[4]); + encode_float(q.z, &buf[8]); + encode_float(q.w, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::_AABB: { if (buf) { - AABB aabb=p_variant; - encode_float(aabb.pos.x,&buf[0]); - encode_float(aabb.pos.y,&buf[4]); - encode_float(aabb.pos.z,&buf[8]); - encode_float(aabb.size.x,&buf[12]); - encode_float(aabb.size.y,&buf[16]); - encode_float(aabb.size.z,&buf[20]); + AABB aabb = p_variant; + encode_float(aabb.pos.x, &buf[0]); + encode_float(aabb.pos.y, &buf[4]); + encode_float(aabb.pos.z, &buf[8]); + encode_float(aabb.size.x, &buf[12]); + encode_float(aabb.size.y, &buf[16]); + encode_float(aabb.size.z, &buf[20]); } - r_len+=6*4; - + r_len += 6 * 4; } break; case Variant::MATRIX3: { if (buf) { - Matrix3 val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Matrix3 val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - copymem(&buf[(i*3+j)*4],&val.elements[i][j],sizeof(float)); + copymem(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float)); } } } - - r_len+=9*4; + r_len += 9 * 4; } break; case Variant::TRANSFORM: { if (buf) { - Transform val=p_variant; - for(int i=0;i<3;i++) { - for(int j=0;j<3;j++) { + Transform val = p_variant; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - copymem(&buf[(i*3+j)*4],&val.basis.elements[i][j],sizeof(float)); + copymem(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float)); } } - encode_float(val.origin.x,&buf[36]); - encode_float(val.origin.y,&buf[40]); - encode_float(val.origin.z,&buf[44]); - - + encode_float(val.origin.x, &buf[36]); + encode_float(val.origin.y, &buf[40]); + encode_float(val.origin.z, &buf[44]); } - r_len+=12*4; + r_len += 12 * 4; } break; @@ -1042,38 +1011,38 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::COLOR: { if (buf) { - Color c=p_variant; - encode_float(c.r,&buf[0]); - encode_float(c.g,&buf[4]); - encode_float(c.b,&buf[8]); - encode_float(c.a,&buf[12]); + Color c = p_variant; + encode_float(c.r, &buf[0]); + encode_float(c.g, &buf[4]); + encode_float(c.b, &buf[8]); + encode_float(c.a, &buf[12]); } - r_len+=4*4; + r_len += 4 * 4; } break; case Variant::IMAGE: { Image image = p_variant; - DVector<uint8_t> data=image.get_data(); + DVector<uint8_t> data = image.get_data(); if (buf) { - encode_uint32(image.get_format(),&buf[0]); - encode_uint32(image.get_mipmaps(),&buf[4]); - encode_uint32(image.get_width(),&buf[8]); - encode_uint32(image.get_height(),&buf[12]); - int ds=data.size(); - encode_uint32(ds,&buf[16]); + encode_uint32(image.get_format(), &buf[0]); + encode_uint32(image.get_mipmaps(), &buf[4]); + encode_uint32(image.get_width(), &buf[8]); + encode_uint32(image.get_height(), &buf[12]); + int ds = data.size(); + encode_uint32(ds, &buf[16]); DVector<uint8_t>::Read r = data.read(); - copymem(&buf[20],&r[0],ds); + copymem(&buf[20], &r[0], ds); } - int pad=0; - if (data.size()%4) - pad=4-data.size()%4; + int pad = 0; + if (data.size() % 4) + pad = 4 - data.size() % 4; - r_len+=data.size()+5*4+pad; + r_len += data.size() + 5 * 4 + pad; } break; /*case Variant::RESOURCE: { @@ -1084,84 +1053,81 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::_RID: case Variant::OBJECT: { - } break; case Variant::INPUT_EVENT: { - - InputEvent ie=p_variant; + InputEvent ie = p_variant; if (buf) { - encode_uint32(ie.type,&buf[0]); - encode_uint32(ie.device,&buf[4]); - encode_uint32(0,&buf[8]); + encode_uint32(ie.type, &buf[0]); + encode_uint32(ie.device, &buf[4]); + encode_uint32(0, &buf[8]); } - int llen=12; + int llen = 12; - switch(ie.type) { + switch (ie.type) { case InputEvent::KEY: { if (buf) { - uint32_t mods=0; + uint32_t mods = 0; if (ie.key.mod.shift) - mods|=KEY_MASK_SHIFT; + mods |= KEY_MASK_SHIFT; if (ie.key.mod.control) - mods|=KEY_MASK_CTRL; + mods |= KEY_MASK_CTRL; if (ie.key.mod.alt) - mods|=KEY_MASK_ALT; + mods |= KEY_MASK_ALT; if (ie.key.mod.meta) - mods|=KEY_MASK_META; + mods |= KEY_MASK_META; - encode_uint32(mods,&buf[llen]); - encode_uint32(ie.key.scancode,&buf[llen+4]); + encode_uint32(mods, &buf[llen]); + encode_uint32(ie.key.scancode, &buf[llen + 4]); } - llen+=8; + llen += 8; } break; case InputEvent::MOUSE_BUTTON: { if (buf) { - encode_uint32(ie.mouse_button.button_index,&buf[llen]); + encode_uint32(ie.mouse_button.button_index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::JOYSTICK_BUTTON: { if (buf) { - encode_uint32(ie.joy_button.button_index,&buf[llen]); + encode_uint32(ie.joy_button.button_index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::SCREEN_TOUCH: { if (buf) { - encode_uint32(ie.screen_touch.index,&buf[llen]); + encode_uint32(ie.screen_touch.index, &buf[llen]); } - llen+=4; + llen += 4; } break; case InputEvent::JOYSTICK_MOTION: { if (buf) { int axis = ie.joy_motion.axis; - encode_uint32(axis,&buf[llen]); - encode_float(ie.joy_motion.axis_value, &buf[llen+4]); + encode_uint32(axis, &buf[llen]); + encode_float(ie.joy_motion.axis_value, &buf[llen + 4]); } - llen+=8; + llen += 8; } break; } if (buf) - encode_uint32(llen,&buf[8]); - r_len+=llen; - + encode_uint32(llen, &buf[8]); + r_len += llen; // not supported } break; @@ -1170,16 +1136,15 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { Dictionary d = p_variant; if (buf) { - encode_uint32(uint32_t(d.size())|(d.is_shared()?0x80000000:0),buf); - buf+=4; + encode_uint32(uint32_t(d.size()) | (d.is_shared() ? 0x80000000 : 0), buf); + buf += 4; } - r_len+=4; + r_len += 4; List<Variant> keys; d.get_key_list(&keys); - - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* CharString utf8 = E->->utf8(); @@ -1195,14 +1160,14 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { r_len++; //pad */ int len; - encode_variant(E->get(),buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(E->get(), buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) buf += len; - encode_variant(d[E->get()],buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(d[E->get()], buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) buf += len; } @@ -1213,107 +1178,101 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { Array v = p_variant; if (buf) { - encode_uint32(uint32_t(v.size())|(v.is_shared()?0x80000000:0),buf); - buf+=4; + encode_uint32(uint32_t(v.size()) | (v.is_shared() ? 0x80000000 : 0), buf); + buf += 4; } - r_len+=4; + r_len += 4; - for(int i=0;i<v.size();i++) { + for (int i = 0; i < v.size(); i++) { int len; - encode_variant(v.get(i),buf,len); - ERR_FAIL_COND_V(len%4,ERR_BUG); - r_len+=len; + encode_variant(v.get(i), buf, len); + ERR_FAIL_COND_V(len % 4, ERR_BUG); + r_len += len; if (buf) - buf+=len; + buf += len; } - } break; // arrays case Variant::RAW_ARRAY: { DVector<uint8_t> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(uint8_t); + int datalen = data.size(); + int datasize = sizeof(uint8_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; DVector<uint8_t>::Read r = data.read(); - copymem(buf,&r[0],datalen*datasize); - + copymem(buf, &r[0], datalen * datasize); } - r_len+=4+datalen*datasize; - while(r_len%4) + r_len += 4 + datalen * datasize; + while (r_len % 4) r_len++; } break; case Variant::INT_ARRAY: { DVector<int> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(int32_t); + int datalen = data.size(); + int datasize = sizeof(int32_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; DVector<int>::Read r = data.read(); - for(int i=0;i<datalen;i++) - encode_uint32(r[i],&buf[i*datasize]); - + for (int i = 0; i < datalen; i++) + encode_uint32(r[i], &buf[i * datasize]); } - r_len+=4+datalen*datasize; + r_len += 4 + datalen * datasize; } break; case Variant::REAL_ARRAY: { DVector<real_t> data = p_variant; - int datalen=data.size(); - int datasize=sizeof(real_t); + int datalen = data.size(); + int datasize = sizeof(real_t); if (buf) { - encode_uint32(datalen,buf); - buf+=4; + encode_uint32(datalen, buf); + buf += 4; DVector<real_t>::Read r = data.read(); - for(int i=0;i<datalen;i++) - encode_float(r[i],&buf[i*datasize]); - + for (int i = 0; i < datalen; i++) + encode_float(r[i], &buf[i * datasize]); } - r_len+=4+datalen*datasize; + r_len += 4 + datalen * datasize; } break; case Variant::STRING_ARRAY: { - DVector<String> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; - - for(int i=0;i<len;i++) { + r_len += 4; + for (int i = 0; i < len; i++) { CharString utf8 = data.get(i).utf8(); if (buf) { - encode_uint32(utf8.length()+1,buf); - buf+=4; - copymem(buf,utf8.get_data(),utf8.length()+1); - buf+=utf8.length()+1; + encode_uint32(utf8.length() + 1, buf); + buf += 4; + copymem(buf, utf8.get_data(), utf8.length() + 1); + buf += utf8.length() + 1; } - r_len+=4+utf8.length()+1; - while (r_len%4) { + r_len += 4 + utf8.length() + 1; + while (r_len % 4) { r_len++; //pad if (buf) buf++; @@ -1324,95 +1283,89 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) { case Variant::VECTOR2_ARRAY: { DVector<Vector2> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Vector2 v = data.get(i); - encode_float(v.x,&buf[0]); - encode_float(v.y,&buf[4]); - buf+=4*2; - + encode_float(v.x, &buf[0]); + encode_float(v.y, &buf[4]); + buf += 4 * 2; } } - r_len+=4*2*len; + r_len += 4 * 2 * len; } break; case Variant::VECTOR3_ARRAY: { DVector<Vector3> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Vector3 v = data.get(i); - encode_float(v.x,&buf[0]); - encode_float(v.y,&buf[4]); - encode_float(v.z,&buf[8]); - buf+=4*3; - + encode_float(v.x, &buf[0]); + encode_float(v.y, &buf[4]); + encode_float(v.z, &buf[8]); + buf += 4 * 3; } } - r_len+=4*3*len; + r_len += 4 * 3 * len; } break; case Variant::COLOR_ARRAY: { DVector<Color> data = p_variant; - int len=data.size(); + int len = data.size(); if (buf) { - encode_uint32(len,buf); - buf+=4; + encode_uint32(len, buf); + buf += 4; } - r_len+=4; + r_len += 4; if (buf) { - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { Color c = data.get(i); - - encode_float(c.r,&buf[0]); - encode_float(c.g,&buf[4]); - encode_float(c.b,&buf[8]); - encode_float(c.a,&buf[12]); - buf+=4*4; + encode_float(c.r, &buf[0]); + encode_float(c.g, &buf[4]); + encode_float(c.b, &buf[8]); + encode_float(c.a, &buf[12]); + buf += 4 * 4; } } - r_len+=4*4*len; + r_len += 4 * 4 * len; } break; default: { ERR_FAIL_V(ERR_BUG); } } return OK; - } - - diff --git a/core/io/marshalls.h b/core/io/marshalls.h index f04ec9a25..939ed9cea 100644 --- a/core/io/marshalls.h +++ b/core/io/marshalls.h @@ -38,7 +38,6 @@ * in an endian independent way */ - union MarshallFloat { uint32_t i; ///< int @@ -53,41 +52,44 @@ union MarshallDouble { static inline unsigned int encode_uint16(uint16_t p_uint, uint8_t *p_arr) { - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } - return sizeof( uint16_t ); + return sizeof(uint16_t); } static inline unsigned int encode_uint32(uint32_t p_uint, uint8_t *p_arr) { - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } - return sizeof( uint32_t ); + return sizeof(uint32_t); } static inline unsigned int encode_float(float p_float, uint8_t *p_arr) { MarshallFloat mf; - mf.f=p_float; - encode_uint32( mf.i, p_arr ); + mf.f = p_float; + encode_uint32(mf.i, p_arr); - return sizeof( uint32_t ); + return sizeof(uint32_t); } static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) { - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - *p_arr=p_uint&0xFF; - p_arr++; p_uint>>=8; + *p_arr = p_uint & 0xFF; + p_arr++; + p_uint >>= 8; } return sizeof(uint64_t); @@ -96,23 +98,21 @@ static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) { static inline unsigned int encode_double(double p_double, uint8_t *p_arr) { MarshallDouble md; - md.d=p_double; - encode_uint64( md.l, p_arr ); + md.d = p_double; + encode_uint64(md.l, p_arr); return sizeof(uint64_t); - } +static inline int encode_cstring(const char *p_string, uint8_t *p_data) { -static inline int encode_cstring(const char *p_string, uint8_t * p_data) { - - int len=0; + int len = 0; while (*p_string) { if (p_data) { - *p_data=(uint8_t)*p_string; + *p_data = (uint8_t)*p_string; p_data++; } p_string++; @@ -120,18 +120,18 @@ static inline int encode_cstring(const char *p_string, uint8_t * p_data) { }; if (p_data) *p_data = 0; - return len+1; + return len + 1; } static inline uint16_t decode_uint16(const uint8_t *p_arr) { - uint16_t u=0; + uint16_t u = 0; - for (int i=0;i<2;i++) { + for (int i = 0; i < 2; i++) { uint16_t b = *p_arr; - b<<=(i*8); - u|=b; + b <<= (i * 8); + u |= b; p_arr++; } @@ -140,13 +140,13 @@ static inline uint16_t decode_uint16(const uint8_t *p_arr) { static inline uint32_t decode_uint32(const uint8_t *p_arr) { - uint32_t u=0; + uint32_t u = 0; - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { uint32_t b = *p_arr; - b<<=(i*8); - u|=b; + b <<= (i * 8); + u |= b; p_arr++; } @@ -162,13 +162,13 @@ static inline float decode_float(const uint8_t *p_arr) { static inline uint64_t decode_uint64(const uint8_t *p_arr) { - uint64_t u=0; + uint64_t u = 0; - for (int i=0;i<8;i++) { + for (int i = 0; i < 8; i++) { - uint64_t b = (*p_arr)&0xFF; - b<<=(i*8); - u|=b; + uint64_t b = (*p_arr) & 0xFF; + b <<= (i * 8); + u |= b; p_arr++; } @@ -178,13 +178,11 @@ static inline uint64_t decode_uint64(const uint8_t *p_arr) { static inline double decode_double(const uint8_t *p_arr) { MarshallDouble md; - md.l = decode_uint64( p_arr ); + md.l = decode_uint64(p_arr); return md.d; - } - -Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len=NULL); -Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len); +Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len = NULL); +Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len); #endif diff --git a/core/io/packet_peer.cpp b/core/io/packet_peer.cpp index fc95aa0b1..3c6aec1be 100644 --- a/core/io/packet_peer.cpp +++ b/core/io/packet_peer.cpp @@ -28,77 +28,71 @@ /*************************************************************************/ #include "packet_peer.h" -#include "io/marshalls.h" #include "globals.h" +#include "io/marshalls.h" /* helpers / binders */ - - PacketPeer::PacketPeer() { - last_get_error=OK; + last_get_error = OK; } Error PacketPeer::get_packet_buffer(DVector<uint8_t> &r_buffer) const { const uint8_t *buffer; int buffer_size; - Error err = get_packet(&buffer,buffer_size); + Error err = get_packet(&buffer, buffer_size); if (err) return err; r_buffer.resize(buffer_size); - if (buffer_size==0) + if (buffer_size == 0) return OK; DVector<uint8_t>::Write w = r_buffer.write(); - for(int i=0;i<buffer_size;i++) - w[i]=buffer[i]; + for (int i = 0; i < buffer_size; i++) + w[i] = buffer[i]; return OK; - } Error PacketPeer::put_packet_buffer(const DVector<uint8_t> &p_buffer) { int len = p_buffer.size(); - if (len==0) + if (len == 0) return OK; DVector<uint8_t>::Read r = p_buffer.read(); - return put_packet(&r[0],len); - + return put_packet(&r[0], len); } Error PacketPeer::get_var(Variant &r_variant) const { const uint8_t *buffer; int buffer_size; - Error err = get_packet(&buffer,buffer_size); + Error err = get_packet(&buffer, buffer_size); if (err) return err; - return decode_variant(r_variant,buffer,buffer_size); - + return decode_variant(r_variant, buffer, buffer_size); } -Error PacketPeer::put_var(const Variant& p_packet) { +Error PacketPeer::put_var(const Variant &p_packet) { int len; - Error err = encode_variant(p_packet,NULL,len); // compute len first + Error err = encode_variant(p_packet, NULL, len); // compute len first if (err) return err; - if (len==0) + if (len == 0) return OK; - uint8_t *buf = (uint8_t*)alloca(len); - ERR_FAIL_COND_V(!buf,ERR_OUT_OF_MEMORY); - err = encode_variant(p_packet,buf,len); + uint8_t *buf = (uint8_t *)alloca(len); + ERR_FAIL_COND_V(!buf, ERR_OUT_OF_MEMORY); + err = encode_variant(p_packet, buf, len); ERR_FAIL_COND_V(err, err); return put_packet(buf, len); - } Variant PacketPeer::_bnd_get_var() const { @@ -108,13 +102,13 @@ Variant PacketPeer::_bnd_get_var() const { return var; }; -Error PacketPeer::_put_packet(const DVector<uint8_t> &p_buffer) { +Error PacketPeer::_put_packet(const DVector<uint8_t> &p_buffer) { return put_packet_buffer(p_buffer); } DVector<uint8_t> PacketPeer::_get_packet() const { DVector<uint8_t> raw; - last_get_error=get_packet_buffer(raw); + last_get_error = get_packet_buffer(raw); return raw; } @@ -123,20 +117,18 @@ Error PacketPeer::_get_packet_error() const { return last_get_error; } - void PacketPeer::_bind_methods() { - ObjectTypeDB::bind_method(_MD("get_var:Variant"),&PacketPeer::_bnd_get_var); - ObjectTypeDB::bind_method(_MD("put_var", "var:Variant"),&PacketPeer::put_var); - ObjectTypeDB::bind_method(_MD("get_packet"),&PacketPeer::_get_packet); - ObjectTypeDB::bind_method(_MD("put_packet:Error", "buffer"),&PacketPeer::_put_packet); - ObjectTypeDB::bind_method(_MD("get_packet_error:Error"),&PacketPeer::_get_packet_error); - ObjectTypeDB::bind_method(_MD("get_available_packet_count"),&PacketPeer::get_available_packet_count); + ObjectTypeDB::bind_method(_MD("get_var:Variant"), &PacketPeer::_bnd_get_var); + ObjectTypeDB::bind_method(_MD("put_var", "var:Variant"), &PacketPeer::put_var); + ObjectTypeDB::bind_method(_MD("get_packet"), &PacketPeer::_get_packet); + ObjectTypeDB::bind_method(_MD("put_packet:Error", "buffer"), &PacketPeer::_put_packet); + ObjectTypeDB::bind_method(_MD("get_packet_error:Error"), &PacketPeer::_get_packet_error); + ObjectTypeDB::bind_method(_MD("get_available_packet_count"), &PacketPeer::get_available_packet_count); }; /***************/ - void PacketPeerStream::_set_stream_peer(REF p_peer) { ERR_FAIL_COND(p_peer.is_null()); @@ -145,22 +137,22 @@ void PacketPeerStream::_set_stream_peer(REF p_peer) { void PacketPeerStream::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_stream_peer","peer:StreamPeer"),&PacketPeerStream::_set_stream_peer); + ObjectTypeDB::bind_method(_MD("set_stream_peer", "peer:StreamPeer"), &PacketPeerStream::_set_stream_peer); } Error PacketPeerStream::_poll_buffer() const { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); int read = 0; Error err = peer->get_partial_data(&temp_buffer[0], ring_buffer.space_left(), read); if (err) return err; - if (read==0) + if (read == 0) return OK; - int w = ring_buffer.write(&temp_buffer[0],read); - ERR_FAIL_COND_V(w!=read,ERR_BUG); + int w = ring_buffer.write(&temp_buffer[0], read); + ERR_FAIL_COND_V(w != read, ERR_BUG); return OK; } @@ -171,73 +163,71 @@ int PacketPeerStream::get_available_packet_count() const { uint32_t remaining = ring_buffer.data_left(); - int ofs=0; - int count=0; + int ofs = 0; + int count = 0; - while(remaining>=4) { + while (remaining >= 4) { uint8_t lbuf[4]; - ring_buffer.copy(lbuf,ofs,4); + ring_buffer.copy(lbuf, ofs, 4); uint32_t len = decode_uint32(lbuf); - remaining-=4; - ofs+=4; - if (len>remaining) + remaining -= 4; + ofs += 4; + if (len > remaining) break; - remaining-=len; - ofs+=len; + remaining -= len; + ofs += len; count++; } return count; } -Error PacketPeerStream::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const { +Error PacketPeerStream::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); _poll_buffer(); int remaining = ring_buffer.data_left(); - ERR_FAIL_COND_V(remaining<4,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(remaining < 4, ERR_UNAVAILABLE); uint8_t lbuf[4]; - ring_buffer.copy(lbuf,0,4); - remaining-=4; + ring_buffer.copy(lbuf, 0, 4); + remaining -= 4; uint32_t len = decode_uint32(lbuf); - ERR_FAIL_COND_V(remaining<(int)len,ERR_UNAVAILABLE); + ERR_FAIL_COND_V(remaining < (int)len, ERR_UNAVAILABLE); - ring_buffer.read(lbuf,4); //get rid of first 4 bytes - ring_buffer.read(&temp_buffer[0],len); // read packet + ring_buffer.read(lbuf, 4); //get rid of first 4 bytes + ring_buffer.read(&temp_buffer[0], len); // read packet - *r_buffer=&temp_buffer[0]; - r_buffer_size=len; + *r_buffer = &temp_buffer[0]; + r_buffer_size = len; return OK; - } -Error PacketPeerStream::put_packet(const uint8_t *p_buffer,int p_buffer_size) { +Error PacketPeerStream::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED); + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); Error err = _poll_buffer(); //won't hurt to poll here too if (err) return err; - if (p_buffer_size==0) + if (p_buffer_size == 0) return OK; - ERR_FAIL_COND_V( p_buffer_size<0, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V( p_buffer_size+4 > temp_buffer.size(), ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(p_buffer_size < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_buffer_size + 4 > temp_buffer.size(), ERR_INVALID_PARAMETER); - encode_uint32(p_buffer_size,&temp_buffer[0]); - uint8_t *dst=&temp_buffer[4]; - for(int i=0;i<p_buffer_size;i++) - dst[i]=p_buffer[i]; + encode_uint32(p_buffer_size, &temp_buffer[0]); + uint8_t *dst = &temp_buffer[4]; + for (int i = 0; i < p_buffer_size; i++) + dst[i] = p_buffer[i]; - return peer->put_data(&temp_buffer[0],p_buffer_size+4); + return peer->put_data(&temp_buffer[0], p_buffer_size + 4); } int PacketPeerStream::get_max_packet_size() const { - return temp_buffer.size(); } @@ -249,7 +239,7 @@ void PacketPeerStream::set_stream_peer(const Ref<StreamPeer> &p_peer) { ring_buffer.advance_read(ring_buffer.data_left()); // reset the ring buffer }; - peer=p_peer; + peer = p_peer; } void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { @@ -257,18 +247,14 @@ void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { //warning may lose packets ERR_EXPLAIN("Buffer in use, resizing would cause loss of data"); ERR_FAIL_COND(ring_buffer.data_left()); - ring_buffer.resize(nearest_shift(p_max_size+4)); - temp_buffer.resize(nearest_power_of_2(p_max_size+4)); - + ring_buffer.resize(nearest_shift(p_max_size + 4)); + temp_buffer.resize(nearest_power_of_2(p_max_size + 4)); } PacketPeerStream::PacketPeerStream() { - - int rbsize=GLOBAL_DEF( "core/packet_stream_peer_max_buffer_po2",(16)); + int rbsize = GLOBAL_DEF("core/packet_stream_peer_max_buffer_po2", (16)); ring_buffer.resize(rbsize); - temp_buffer.resize(1<<rbsize); - - + temp_buffer.resize(1 << rbsize); } diff --git a/core/io/packet_peer.h b/core/io/packet_peer.h index ec2f46b82..b6114df2e 100644 --- a/core/io/packet_peer.h +++ b/core/io/packet_peer.h @@ -29,33 +29,30 @@ #ifndef PACKET_PEER_H #define PACKET_PEER_H -#include "object.h" #include "io/stream_peer.h" +#include "object.h" #include "ring_buffer.h" class PacketPeer : public Reference { - OBJ_TYPE( PacketPeer, Reference ); + OBJ_TYPE(PacketPeer, Reference); Variant _bnd_get_var() const; - void _bnd_put_var(const Variant& p_var); + void _bnd_put_var(const Variant &p_var); static void _bind_methods(); - Error _put_packet(const DVector<uint8_t> &p_buffer); DVector<uint8_t> _get_packet() const; Error _get_packet_error() const; - mutable Error last_get_error; public: + virtual int get_available_packet_count() const = 0; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const = 0; ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0; - virtual int get_available_packet_count() const=0; - virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const=0; ///< buffer is GONE after next get_packet - virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size)=0; - - virtual int get_max_packet_size() const=0; + virtual int get_max_packet_size() const = 0; /* helpers / binders */ @@ -63,15 +60,15 @@ public: virtual Error put_packet_buffer(const DVector<uint8_t> &p_buffer); virtual Error get_var(Variant &r_variant) const; - virtual Error put_var(const Variant& p_packet); + virtual Error put_var(const Variant &p_packet); PacketPeer(); - ~PacketPeer(){} + ~PacketPeer() {} }; class PacketPeerStream : public PacketPeer { - OBJ_TYPE(PacketPeerStream,PacketPeer); + OBJ_TYPE(PacketPeerStream, PacketPeer); //the way the buffers work sucks, will change later @@ -80,23 +77,21 @@ class PacketPeerStream : public PacketPeer { mutable Vector<uint8_t> temp_buffer; Error _poll_buffer() const; -protected: +protected: void _set_stream_peer(REF p_peer); static void _bind_methods(); -public: +public: virtual int get_available_packet_count() const; - virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const; - virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size); + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const; + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); virtual int get_max_packet_size() const; - void set_stream_peer(const Ref<StreamPeer>& p_peer); + void set_stream_peer(const Ref<StreamPeer> &p_peer); void set_input_buffer_max_size(int p_max_size); PacketPeerStream(); - }; - #endif // PACKET_STREAM_H diff --git a/core/io/packet_peer_udp.cpp b/core/io/packet_peer_udp.cpp index 6216176e7..eb51a4207 100644 --- a/core/io/packet_peer_udp.cpp +++ b/core/io/packet_peer_udp.cpp @@ -29,25 +29,25 @@ #include "packet_peer_udp.h" #include "io/ip.h" -PacketPeerUDP* (*PacketPeerUDP::_create)()=NULL; +PacketPeerUDP *(*PacketPeerUDP::_create)() = NULL; String PacketPeerUDP::_get_packet_ip() const { return get_packet_address(); } -Error PacketPeerUDP::_set_send_address(const String& p_address, int p_port) { +Error PacketPeerUDP::_set_send_address(const String &p_address, int p_port) { IP_Address ip; if (p_address.is_valid_ip_address()) { - ip=p_address; + ip = p_address; } else { - ip=IP::get_singleton()->resolve_hostname(p_address, ip_type); - if (ip==IP_Address()) + ip = IP::get_singleton()->resolve_hostname(p_address, ip_type); + if (ip == IP_Address()) return ERR_CANT_RESOLVE; } - set_send_address(ip,p_port); + set_send_address(ip, p_port); return OK; } @@ -58,17 +58,15 @@ void PacketPeerUDP::set_ip_type(IP::Type p_type) { void PacketPeerUDP::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&PacketPeerUDP::set_ip_type); - ObjectTypeDB::bind_method(_MD("listen:Error","port", "recv_buf_size"),&PacketPeerUDP::listen,DEFVAL(65536)); - ObjectTypeDB::bind_method(_MD("close"),&PacketPeerUDP::close); - ObjectTypeDB::bind_method(_MD("wait:Error"),&PacketPeerUDP::wait); - ObjectTypeDB::bind_method(_MD("is_listening"),&PacketPeerUDP::is_listening); - ObjectTypeDB::bind_method(_MD("get_packet_ip"),&PacketPeerUDP::_get_packet_ip); + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &PacketPeerUDP::set_ip_type); + ObjectTypeDB::bind_method(_MD("listen:Error", "port", "recv_buf_size"), &PacketPeerUDP::listen, DEFVAL(65536)); + ObjectTypeDB::bind_method(_MD("close"), &PacketPeerUDP::close); + ObjectTypeDB::bind_method(_MD("wait:Error"), &PacketPeerUDP::wait); + ObjectTypeDB::bind_method(_MD("is_listening"), &PacketPeerUDP::is_listening); + ObjectTypeDB::bind_method(_MD("get_packet_ip"), &PacketPeerUDP::_get_packet_ip); //ObjectTypeDB::bind_method(_MD("get_packet_address"),&PacketPeerUDP::_get_packet_address); - ObjectTypeDB::bind_method(_MD("get_packet_port"),&PacketPeerUDP::get_packet_port); - ObjectTypeDB::bind_method(_MD("set_send_address","host","port"),&PacketPeerUDP::_set_send_address); - - + ObjectTypeDB::bind_method(_MD("get_packet_port"), &PacketPeerUDP::get_packet_port); + ObjectTypeDB::bind_method(_MD("set_send_address", "host", "port"), &PacketPeerUDP::_set_send_address); } Ref<PacketPeerUDP> PacketPeerUDP::create_ref() { @@ -78,14 +76,13 @@ Ref<PacketPeerUDP> PacketPeerUDP::create_ref() { return Ref<PacketPeerUDP>(_create()); } -PacketPeerUDP* PacketPeerUDP::create() { +PacketPeerUDP *PacketPeerUDP::create() { if (!_create) return NULL; return _create(); } -PacketPeerUDP::PacketPeerUDP() -{ +PacketPeerUDP::PacketPeerUDP() { ip_type = IP::TYPE_ANY; } diff --git a/core/io/packet_peer_udp.h b/core/io/packet_peer_udp.h index 5f80ea08f..e17f9b505 100644 --- a/core/io/packet_peer_udp.h +++ b/core/io/packet_peer_udp.h @@ -29,38 +29,34 @@ #ifndef PACKET_PEER_UDP_H #define PACKET_PEER_UDP_H - #include "io/ip.h" #include "io/packet_peer.h" class PacketPeerUDP : public PacketPeer { - OBJ_TYPE(PacketPeerUDP,PacketPeer); + OBJ_TYPE(PacketPeerUDP, PacketPeer); protected: - IP::Type ip_type; - static PacketPeerUDP* (*_create)(); + static PacketPeerUDP *(*_create)(); static void _bind_methods(); String _get_packet_ip() const; - virtual Error _set_send_address(const String& p_address,int p_port); + virtual Error _set_send_address(const String &p_address, int p_port); public: - virtual void set_ip_type(IP::Type p_type); - virtual Error listen(int p_port, int p_recv_buffer_size=65536)=0; - virtual void close()=0; - virtual Error wait()=0; - virtual bool is_listening() const=0; - virtual IP_Address get_packet_address() const=0; - virtual int get_packet_port() const=0; - virtual void set_send_address(const IP_Address& p_address,int p_port)=0; - + virtual Error listen(int p_port, int p_recv_buffer_size = 65536) = 0; + virtual void close() = 0; + virtual Error wait() = 0; + virtual bool is_listening() const = 0; + virtual IP_Address get_packet_address() const = 0; + virtual int get_packet_port() const = 0; + virtual void set_send_address(const IP_Address &p_address, int p_port) = 0; static Ref<PacketPeerUDP> create_ref(); - static PacketPeerUDP* create(); + static PacketPeerUDP *create(); PacketPeerUDP(); }; diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp index 6d35acf18..35690e696 100644 --- a/core/io/pck_packer.cpp +++ b/core/io/pck_packer.cpp @@ -42,9 +42,9 @@ static uint64_t _align(uint64_t p_n, int p_alignment) { return p_n + (p_alignment - rest); }; -static void _pad(FileAccess* p_file, int p_bytes) { +static void _pad(FileAccess *p_file, int p_bytes) { - for (int i=0; i<p_bytes; i++) { + for (int i = 0; i < p_bytes; i++) { p_file->store_8(0); }; @@ -52,13 +52,12 @@ static void _pad(FileAccess* p_file, int p_bytes) { void PCKPacker::_bind_methods() { - ObjectTypeDB::bind_method(_MD("pck_start","pck_name","alignment"),&PCKPacker::pck_start); - ObjectTypeDB::bind_method(_MD("add_file","pck_path","source_path"),&PCKPacker::add_file); - ObjectTypeDB::bind_method(_MD("flush","verbose"),&PCKPacker::flush); + ObjectTypeDB::bind_method(_MD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start); + ObjectTypeDB::bind_method(_MD("add_file", "pck_path", "source_path"), &PCKPacker::add_file); + ObjectTypeDB::bind_method(_MD("flush", "verbose"), &PCKPacker::flush); }; - -Error PCKPacker::pck_start(const String& p_file, int p_alignment) { +Error PCKPacker::pck_start(const String &p_file, int p_alignment) { file = FileAccess::open(p_file, FileAccess::WRITE); if (file == NULL) { @@ -74,7 +73,7 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) { file->store_32(0); // # minor file->store_32(0); // # revision - for (int i=0; i<16; i++) { + for (int i = 0; i < 16; i++) { file->store_32(0); // reserved }; @@ -84,9 +83,9 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) { return OK; }; -Error PCKPacker::add_file(const String& p_file, const String& p_src) { +Error PCKPacker::add_file(const String &p_file, const String &p_src) { - FileAccess* f = FileAccess::open(p_src, FileAccess::READ); + FileAccess *f = FileAccess::open(p_src, FileAccess::READ); if (!f) { return ERR_FILE_CANT_OPEN; }; @@ -116,7 +115,7 @@ Error PCKPacker::flush(bool p_verbose) { file->store_32(files.size()); - for (int i=0; i<files.size(); i++) { + for (int i = 0; i < files.size(); i++) { file->store_pascal_string(files[i].path); files[i].offset_offset = file->get_pos(); @@ -130,7 +129,6 @@ Error PCKPacker::flush(bool p_verbose) { file->store_32(0); }; - uint64_t ofs = file->get_pos(); ofs = _align(ofs, alignment); @@ -140,9 +138,9 @@ Error PCKPacker::flush(bool p_verbose) { uint8_t *buf = memnew_arr(uint8_t, buf_max); int count = 0; - for (int i=0; i<files.size(); i++) { + for (int i = 0; i < files.size(); i++) { - FileAccess* src = FileAccess::open(files[i].src_path, FileAccess::READ); + FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ); uint64_t to_write = files[i].size; while (to_write > 0) { diff --git a/core/io/pck_packer.h b/core/io/pck_packer.h index 2ed5c050c..a532fc173 100644 --- a/core/io/pck_packer.h +++ b/core/io/pck_packer.h @@ -34,7 +34,7 @@ class PCKPacker : public Reference { OBJ_TYPE(PCKPacker, Reference); - FileAccess* file; + FileAccess *file; int alignment; static void _bind_methods(); @@ -49,11 +49,10 @@ class PCKPacker : public Reference { Vector<File> files; public: - Error pck_start(const String& p_file, int p_alignment); - Error add_file(const String& p_file, const String& p_src); + Error pck_start(const String &p_file, int p_alignment); + Error add_file(const String &p_file, const String &p_src); Error flush(bool p_verbose = false); - PCKPacker(); ~PCKPacker(); }; diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp index 16bcda398..d9f2eac72 100644 --- a/core/io/resource_format_binary.cpp +++ b/core/io/resource_format_binary.cpp @@ -26,314 +26,344 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "version.h" #include "resource_format_binary.h" #include "globals.h" #include "io/file_access_compressed.h" #include "io/marshalls.h" #include "os/dir_access.h" +#include "version.h" //#define print_bl(m_what) print_line(m_what) #define print_bl(m_what) - enum { //numbering must be different from variant, in case new variant types are added (variant must be always contiguous for jumptable optimization) - VARIANT_NIL=1, - VARIANT_BOOL=2, - VARIANT_INT=3, - VARIANT_REAL=4, - VARIANT_STRING=5, - VARIANT_VECTOR2=10, - VARIANT_RECT2=11, - VARIANT_VECTOR3=12, - VARIANT_PLANE=13, - VARIANT_QUAT=14, - VARIANT_AABB=15, - VARIANT_MATRIX3=16, - VARIANT_TRANSFORM=17, - VARIANT_MATRIX32=18, - VARIANT_COLOR=20, - VARIANT_IMAGE=21, - VARIANT_NODE_PATH=22, - VARIANT_RID=23, - VARIANT_OBJECT=24, - VARIANT_INPUT_EVENT=25, - VARIANT_DICTIONARY=26, - VARIANT_ARRAY=30, - VARIANT_RAW_ARRAY=31, - VARIANT_INT_ARRAY=32, - VARIANT_REAL_ARRAY=33, - VARIANT_STRING_ARRAY=34, - VARIANT_VECTOR3_ARRAY=35, - VARIANT_COLOR_ARRAY=36, - VARIANT_VECTOR2_ARRAY=37, - - IMAGE_ENCODING_EMPTY=0, - IMAGE_ENCODING_RAW=1, - IMAGE_ENCODING_LOSSLESS=2, - IMAGE_ENCODING_LOSSY=3, - - IMAGE_FORMAT_GRAYSCALE=0, - IMAGE_FORMAT_INTENSITY=1, - IMAGE_FORMAT_GRAYSCALE_ALPHA=2, - IMAGE_FORMAT_RGB=3, - IMAGE_FORMAT_RGBA=4, - IMAGE_FORMAT_INDEXED=5, - IMAGE_FORMAT_INDEXED_ALPHA=6, - IMAGE_FORMAT_BC1=7, - IMAGE_FORMAT_BC2=8, - IMAGE_FORMAT_BC3=9, - IMAGE_FORMAT_BC4=10, - IMAGE_FORMAT_BC5=11, - IMAGE_FORMAT_PVRTC2=12, - IMAGE_FORMAT_PVRTC2_ALPHA=13, - IMAGE_FORMAT_PVRTC4=14, - IMAGE_FORMAT_PVRTC4_ALPHA=15, - IMAGE_FORMAT_ETC=16, - IMAGE_FORMAT_ATC=17, - IMAGE_FORMAT_ATC_ALPHA_EXPLICIT=18, - IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED=19, - IMAGE_FORMAT_CUSTOM=30, + VARIANT_NIL = 1, + VARIANT_BOOL = 2, + VARIANT_INT = 3, + VARIANT_REAL = 4, + VARIANT_STRING = 5, + VARIANT_VECTOR2 = 10, + VARIANT_RECT2 = 11, + VARIANT_VECTOR3 = 12, + VARIANT_PLANE = 13, + VARIANT_QUAT = 14, + VARIANT_AABB = 15, + VARIANT_MATRIX3 = 16, + VARIANT_TRANSFORM = 17, + VARIANT_MATRIX32 = 18, + VARIANT_COLOR = 20, + VARIANT_IMAGE = 21, + VARIANT_NODE_PATH = 22, + VARIANT_RID = 23, + VARIANT_OBJECT = 24, + VARIANT_INPUT_EVENT = 25, + VARIANT_DICTIONARY = 26, + VARIANT_ARRAY = 30, + VARIANT_RAW_ARRAY = 31, + VARIANT_INT_ARRAY = 32, + VARIANT_REAL_ARRAY = 33, + VARIANT_STRING_ARRAY = 34, + VARIANT_VECTOR3_ARRAY = 35, + VARIANT_COLOR_ARRAY = 36, + VARIANT_VECTOR2_ARRAY = 37, + IMAGE_ENCODING_EMPTY = 0, + IMAGE_ENCODING_RAW = 1, + IMAGE_ENCODING_LOSSLESS = 2, + IMAGE_ENCODING_LOSSY = 3, - OBJECT_EMPTY=0, - OBJECT_EXTERNAL_RESOURCE=1, - OBJECT_INTERNAL_RESOURCE=2, - OBJECT_EXTERNAL_RESOURCE_INDEX=3, - FORMAT_VERSION=1, - FORMAT_VERSION_CAN_RENAME_DEPS=1 + IMAGE_FORMAT_GRAYSCALE = 0, + IMAGE_FORMAT_INTENSITY = 1, + IMAGE_FORMAT_GRAYSCALE_ALPHA = 2, + IMAGE_FORMAT_RGB = 3, + IMAGE_FORMAT_RGBA = 4, + IMAGE_FORMAT_INDEXED = 5, + IMAGE_FORMAT_INDEXED_ALPHA = 6, + IMAGE_FORMAT_BC1 = 7, + IMAGE_FORMAT_BC2 = 8, + IMAGE_FORMAT_BC3 = 9, + IMAGE_FORMAT_BC4 = 10, + IMAGE_FORMAT_BC5 = 11, + IMAGE_FORMAT_PVRTC2 = 12, + IMAGE_FORMAT_PVRTC2_ALPHA = 13, + IMAGE_FORMAT_PVRTC4 = 14, + IMAGE_FORMAT_PVRTC4_ALPHA = 15, + IMAGE_FORMAT_ETC = 16, + IMAGE_FORMAT_ATC = 17, + IMAGE_FORMAT_ATC_ALPHA_EXPLICIT = 18, + IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED = 19, + IMAGE_FORMAT_CUSTOM = 30, + OBJECT_EMPTY = 0, + OBJECT_EXTERNAL_RESOURCE = 1, + OBJECT_INTERNAL_RESOURCE = 2, + OBJECT_EXTERNAL_RESOURCE_INDEX = 3, + FORMAT_VERSION = 1, + FORMAT_VERSION_CAN_RENAME_DEPS = 1 }; - void ResourceInteractiveLoaderBinary::_advance_padding(uint32_t p_len) { - uint32_t extra = 4-(p_len%4); - if (extra<4) { - for(uint32_t i=0;i<extra;i++) + uint32_t extra = 4 - (p_len % 4); + if (extra < 4) { + for (uint32_t i = 0; i < extra; i++) f->get_8(); //pad to 32 } - } -Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_export_data) { - +Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v, bool p_for_export_data) { uint32_t type = f->get_32(); - print_bl("find property of type: "+itos(type)); - + print_bl("find property of type: " + itos(type)); - switch(type) { + switch (type) { case VARIANT_NIL: { - r_v=Variant(); + r_v = Variant(); } break; case VARIANT_BOOL: { - r_v=bool(f->get_32()); + r_v = bool(f->get_32()); } break; case VARIANT_INT: { - r_v=int(f->get_32()); + r_v = int(f->get_32()); } break; case VARIANT_REAL: { - r_v=f->get_real(); + r_v = f->get_real(); } break; case VARIANT_STRING: { - r_v=get_unicode_string(); + r_v = get_unicode_string(); } break; case VARIANT_VECTOR2: { Vector2 v; - v.x=f->get_real(); - v.y=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + r_v = v; } break; case VARIANT_RECT2: { Rect2 v; - v.pos.x=f->get_real(); - v.pos.y=f->get_real(); - v.size.x=f->get_real(); - v.size.y=f->get_real(); - r_v=v; + v.pos.x = f->get_real(); + v.pos.y = f->get_real(); + v.size.x = f->get_real(); + v.size.y = f->get_real(); + r_v = v; } break; case VARIANT_VECTOR3: { Vector3 v; - v.x=f->get_real(); - v.y=f->get_real(); - v.z=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + v.z = f->get_real(); + r_v = v; } break; case VARIANT_PLANE: { Plane v; - v.normal.x=f->get_real(); - v.normal.y=f->get_real(); - v.normal.z=f->get_real(); - v.d=f->get_real(); - r_v=v; + v.normal.x = f->get_real(); + v.normal.y = f->get_real(); + v.normal.z = f->get_real(); + v.d = f->get_real(); + r_v = v; } break; case VARIANT_QUAT: { Quat v; - v.x=f->get_real(); - v.y=f->get_real(); - v.z=f->get_real(); - v.w=f->get_real(); - r_v=v; + v.x = f->get_real(); + v.y = f->get_real(); + v.z = f->get_real(); + v.w = f->get_real(); + r_v = v; } break; case VARIANT_AABB: { AABB v; - v.pos.x=f->get_real(); - v.pos.y=f->get_real(); - v.pos.z=f->get_real(); - v.size.x=f->get_real(); - v.size.y=f->get_real(); - v.size.z=f->get_real(); - r_v=v; + v.pos.x = f->get_real(); + v.pos.y = f->get_real(); + v.pos.z = f->get_real(); + v.size.x = f->get_real(); + v.size.y = f->get_real(); + v.size.z = f->get_real(); + r_v = v; } break; case VARIANT_MATRIX32: { Matrix32 v; - v.elements[0].x=f->get_real(); - v.elements[0].y=f->get_real(); - v.elements[1].x=f->get_real(); - v.elements[1].y=f->get_real(); - v.elements[2].x=f->get_real(); - v.elements[2].y=f->get_real(); - r_v=v; + v.elements[0].x = f->get_real(); + v.elements[0].y = f->get_real(); + v.elements[1].x = f->get_real(); + v.elements[1].y = f->get_real(); + v.elements[2].x = f->get_real(); + v.elements[2].y = f->get_real(); + r_v = v; } break; case VARIANT_MATRIX3: { Matrix3 v; - v.elements[0].x=f->get_real(); - v.elements[0].y=f->get_real(); - v.elements[0].z=f->get_real(); - v.elements[1].x=f->get_real(); - v.elements[1].y=f->get_real(); - v.elements[1].z=f->get_real(); - v.elements[2].x=f->get_real(); - v.elements[2].y=f->get_real(); - v.elements[2].z=f->get_real(); - r_v=v; + v.elements[0].x = f->get_real(); + v.elements[0].y = f->get_real(); + v.elements[0].z = f->get_real(); + v.elements[1].x = f->get_real(); + v.elements[1].y = f->get_real(); + v.elements[1].z = f->get_real(); + v.elements[2].x = f->get_real(); + v.elements[2].y = f->get_real(); + v.elements[2].z = f->get_real(); + r_v = v; } break; case VARIANT_TRANSFORM: { Transform v; - v.basis.elements[0].x=f->get_real(); - v.basis.elements[0].y=f->get_real(); - v.basis.elements[0].z=f->get_real(); - v.basis.elements[1].x=f->get_real(); - v.basis.elements[1].y=f->get_real(); - v.basis.elements[1].z=f->get_real(); - v.basis.elements[2].x=f->get_real(); - v.basis.elements[2].y=f->get_real(); - v.basis.elements[2].z=f->get_real(); - v.origin.x=f->get_real(); - v.origin.y=f->get_real(); - v.origin.z=f->get_real(); - r_v=v; + v.basis.elements[0].x = f->get_real(); + v.basis.elements[0].y = f->get_real(); + v.basis.elements[0].z = f->get_real(); + v.basis.elements[1].x = f->get_real(); + v.basis.elements[1].y = f->get_real(); + v.basis.elements[1].z = f->get_real(); + v.basis.elements[2].x = f->get_real(); + v.basis.elements[2].y = f->get_real(); + v.basis.elements[2].z = f->get_real(); + v.origin.x = f->get_real(); + v.origin.y = f->get_real(); + v.origin.z = f->get_real(); + r_v = v; } break; case VARIANT_COLOR: { Color v; - v.r=f->get_real(); - v.g=f->get_real(); - v.b=f->get_real(); - v.a=f->get_real(); - r_v=v; + v.r = f->get_real(); + v.g = f->get_real(); + v.b = f->get_real(); + v.a = f->get_real(); + r_v = v; } break; case VARIANT_IMAGE: { - uint32_t encoding = f->get_32(); - if (encoding==IMAGE_ENCODING_EMPTY) { - r_v=Variant(); + if (encoding == IMAGE_ENCODING_EMPTY) { + r_v = Variant(); break; - } else if (encoding==IMAGE_ENCODING_RAW) { + } else if (encoding == IMAGE_ENCODING_RAW) { uint32_t width = f->get_32(); uint32_t height = f->get_32(); uint32_t mipmaps = f->get_32(); uint32_t format = f->get_32(); Image::Format fmt; - switch(format) { + switch (format) { - case IMAGE_FORMAT_GRAYSCALE: { fmt=Image::FORMAT_GRAYSCALE; } break; - case IMAGE_FORMAT_INTENSITY: { fmt=Image::FORMAT_INTENSITY; } break; - case IMAGE_FORMAT_GRAYSCALE_ALPHA: { fmt=Image::FORMAT_GRAYSCALE_ALPHA; } break; - case IMAGE_FORMAT_RGB: { fmt=Image::FORMAT_RGB; } break; - case IMAGE_FORMAT_RGBA: { fmt=Image::FORMAT_RGBA; } break; - case IMAGE_FORMAT_INDEXED: { fmt=Image::FORMAT_INDEXED; } break; - case IMAGE_FORMAT_INDEXED_ALPHA: { fmt=Image::FORMAT_INDEXED_ALPHA; } break; - case IMAGE_FORMAT_BC1: { fmt=Image::FORMAT_BC1; } break; - case IMAGE_FORMAT_BC2: { fmt=Image::FORMAT_BC2; } break; - case IMAGE_FORMAT_BC3: { fmt=Image::FORMAT_BC3; } break; - case IMAGE_FORMAT_BC4: { fmt=Image::FORMAT_BC4; } break; - case IMAGE_FORMAT_BC5: { fmt=Image::FORMAT_BC5; } break; - case IMAGE_FORMAT_PVRTC2: { fmt=Image::FORMAT_PVRTC2; } break; - case IMAGE_FORMAT_PVRTC2_ALPHA: { fmt=Image::FORMAT_PVRTC2_ALPHA; } break; - case IMAGE_FORMAT_PVRTC4: { fmt=Image::FORMAT_PVRTC4; } break; - case IMAGE_FORMAT_PVRTC4_ALPHA: { fmt=Image::FORMAT_PVRTC4_ALPHA; } break; - case IMAGE_FORMAT_ETC: { fmt=Image::FORMAT_ETC; } break; - case IMAGE_FORMAT_ATC: { fmt=Image::FORMAT_ATC; } break; - case IMAGE_FORMAT_ATC_ALPHA_EXPLICIT: { fmt=Image::FORMAT_ATC_ALPHA_EXPLICIT; } break; - case IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED: { fmt=Image::FORMAT_ATC_ALPHA_INTERPOLATED; } break; - case IMAGE_FORMAT_CUSTOM: { fmt=Image::FORMAT_CUSTOM; } break; + case IMAGE_FORMAT_GRAYSCALE: { + fmt = Image::FORMAT_GRAYSCALE; + } break; + case IMAGE_FORMAT_INTENSITY: { + fmt = Image::FORMAT_INTENSITY; + } break; + case IMAGE_FORMAT_GRAYSCALE_ALPHA: { + fmt = Image::FORMAT_GRAYSCALE_ALPHA; + } break; + case IMAGE_FORMAT_RGB: { + fmt = Image::FORMAT_RGB; + } break; + case IMAGE_FORMAT_RGBA: { + fmt = Image::FORMAT_RGBA; + } break; + case IMAGE_FORMAT_INDEXED: { + fmt = Image::FORMAT_INDEXED; + } break; + case IMAGE_FORMAT_INDEXED_ALPHA: { + fmt = Image::FORMAT_INDEXED_ALPHA; + } break; + case IMAGE_FORMAT_BC1: { + fmt = Image::FORMAT_BC1; + } break; + case IMAGE_FORMAT_BC2: { + fmt = Image::FORMAT_BC2; + } break; + case IMAGE_FORMAT_BC3: { + fmt = Image::FORMAT_BC3; + } break; + case IMAGE_FORMAT_BC4: { + fmt = Image::FORMAT_BC4; + } break; + case IMAGE_FORMAT_BC5: { + fmt = Image::FORMAT_BC5; + } break; + case IMAGE_FORMAT_PVRTC2: { + fmt = Image::FORMAT_PVRTC2; + } break; + case IMAGE_FORMAT_PVRTC2_ALPHA: { + fmt = Image::FORMAT_PVRTC2_ALPHA; + } break; + case IMAGE_FORMAT_PVRTC4: { + fmt = Image::FORMAT_PVRTC4; + } break; + case IMAGE_FORMAT_PVRTC4_ALPHA: { + fmt = Image::FORMAT_PVRTC4_ALPHA; + } break; + case IMAGE_FORMAT_ETC: { + fmt = Image::FORMAT_ETC; + } break; + case IMAGE_FORMAT_ATC: { + fmt = Image::FORMAT_ATC; + } break; + case IMAGE_FORMAT_ATC_ALPHA_EXPLICIT: { + fmt = Image::FORMAT_ATC_ALPHA_EXPLICIT; + } break; + case IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED: { + fmt = Image::FORMAT_ATC_ALPHA_INTERPOLATED; + } break; + case IMAGE_FORMAT_CUSTOM: { + fmt = Image::FORMAT_CUSTOM; + } break; default: { ERR_FAIL_V(ERR_FILE_CORRUPT); } - } - uint32_t datalen = f->get_32(); DVector<uint8_t> imgdata; imgdata.resize(datalen); DVector<uint8_t>::Write w = imgdata.write(); - f->get_buffer(w.ptr(),datalen); + f->get_buffer(w.ptr(), datalen); _advance_padding(datalen); - w=DVector<uint8_t>::Write(); + w = DVector<uint8_t>::Write(); - r_v=Image(width,height,mipmaps,fmt,imgdata); + r_v = Image(width, height, mipmaps, fmt, imgdata); } else { //compressed DVector<uint8_t> data; data.resize(f->get_32()); DVector<uint8_t>::Write w = data.write(); - f->get_buffer(w.ptr(),data.size()); + f->get_buffer(w.ptr(), data.size()); w = DVector<uint8_t>::Write(); Image img; - if (encoding==IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { + if (encoding == IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { img = Image::lossy_unpacker(data); - } else if (encoding==IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { + } else if (encoding == IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { img = Image::lossless_unpacker(data); } _advance_padding(data.size()); - - r_v=img; - + r_v = img; } } break; @@ -346,80 +376,77 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp int name_count = f->get_16(); uint32_t subname_count = f->get_16(); - absolute=subname_count&0x8000; - subname_count&=0x7FFF; + absolute = subname_count & 0x8000; + subname_count &= 0x7FFF; - - for(int i=0;i<name_count;i++) + for (int i = 0; i < name_count; i++) names.push_back(string_map[f->get_32()]); - for(uint32_t i=0;i<subname_count;i++) + for (uint32_t i = 0; i < subname_count; i++) subnames.push_back(string_map[f->get_32()]); - property=string_map[f->get_32()]; + property = string_map[f->get_32()]; - NodePath np = NodePath(names,subnames,absolute,property); + NodePath np = NodePath(names, subnames, absolute, property); //print_line("got path: "+String(np)); - r_v=np; + r_v = np; } break; case VARIANT_RID: { - r_v=f->get_32(); + r_v = f->get_32(); } break; case VARIANT_OBJECT: { - uint32_t type=f->get_32(); + uint32_t type = f->get_32(); - switch(type) { + switch (type) { case OBJECT_EMPTY: { //do none } break; case OBJECT_INTERNAL_RESOURCE: { - uint32_t index=f->get_32(); + uint32_t index = f->get_32(); if (p_for_export_data) { - r_v="@RESLOCAL:"+itos(index); + r_v = "@RESLOCAL:" + itos(index); } else { - String path = res_path+"::"+itos(index); + String path = res_path + "::" + itos(index); RES res = ResourceLoader::load(path); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } } break; case OBJECT_EXTERNAL_RESOURCE: { //old file format, still around for compatibility - String type = get_unicode_string(); String path = get_unicode_string(); if (p_for_export_data) { - r_v="@RESPATH:"+type+":"+path; + r_v = "@RESPATH:" + type + ":" + path; } else { - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=Globals::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = Globals::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } if (remaps.find(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } } break; @@ -428,32 +455,30 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp uint32_t erindex = f->get_32(); if (p_for_export_data) { - r_v="@RESEXTERNAL:"+itos(erindex); + r_v = "@RESEXTERNAL:" + itos(erindex); } else { - if (erindex>=external_resources.size()) { + if (erindex >= external_resources.size()) { WARN_PRINT("Broken external resource! (index out of size"); - r_v=Variant(); + r_v = Variant(); } else { String type = external_resources[erindex].type; String path = external_resources[erindex].path; - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=Globals::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = Globals::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data()); } - r_v=res; + r_v = res; } } - } break; default: { @@ -467,33 +492,33 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp } break; case VARIANT_DICTIONARY: { - uint32_t len=f->get_32(); - Dictionary d(len&0x80000000); //last bit means shared - len&=0x7FFFFFFF; - for(uint32_t i=0;i<len;i++) { + uint32_t len = f->get_32(); + Dictionary d(len & 0x80000000); //last bit means shared + len &= 0x7FFFFFFF; + for (uint32_t i = 0; i < len; i++) { Variant key; - Error err = parse_variant(key,p_for_export_data); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + Error err = parse_variant(key, p_for_export_data); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); Variant value; - err = parse_variant(value,p_for_export_data); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - d[key]=value; + err = parse_variant(value, p_for_export_data); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); + d[key] = value; } - r_v=d; + r_v = d; } break; case VARIANT_ARRAY: { - uint32_t len=f->get_32(); - Array a(len&0x80000000); //last bit means shared - len&=0x7FFFFFFF; + uint32_t len = f->get_32(); + Array a(len & 0x80000000); //last bit means shared + len &= 0x7FFFFFFF; a.resize(len); - for(uint32_t i=0;i<len;i++) { + for (uint32_t i = 0; i < len; i++) { Variant val; - Error err = parse_variant(val,p_for_export_data); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); - a[i]=val; + Error err = parse_variant(val, p_for_export_data); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); + a[i] = val; } - r_v=a; + r_v = a; } break; case VARIANT_RAW_ARRAY: { @@ -503,10 +528,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<uint8_t> array; array.resize(len); DVector<uint8_t>::Write w = array.write(); - f->get_buffer(w.ptr(),len); + f->get_buffer(w.ptr(), len); _advance_padding(len); - w=DVector<uint8_t>::Write(); - r_v=array; + w = DVector<uint8_t>::Write(); + r_v = array; } break; case VARIANT_INT_ARRAY: { @@ -516,19 +541,19 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<int> array; array.resize(len); DVector<int>::Write w = array.write(); - f->get_buffer((uint8_t*)w.ptr(),len*4); + f->get_buffer((uint8_t *)w.ptr(), len * 4); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } #endif - w=DVector<int>::Write(); - r_v=array; + w = DVector<int>::Write(); + r_v = array; } break; case VARIANT_REAL_ARRAY: { @@ -537,20 +562,20 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<real_t> array; array.resize(len); DVector<real_t>::Write w = array.write(); - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)); + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t)); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } #endif - w=DVector<real_t>::Write(); - r_v=array; + w = DVector<real_t>::Write(); + r_v = array; } break; case VARIANT_STRING_ARRAY: { @@ -558,11 +583,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<String> array; array.resize(len); DVector<String>::Write w = array.write(); - for(uint32_t i=0;i<len;i++) - w[i]=get_unicode_string(); - w=DVector<String>::Write(); - r_v=array; - + for (uint32_t i = 0; i < len; i++) + w[i] = get_unicode_string(); + w = DVector<String>::Write(); + r_v = array; } break; case VARIANT_VECTOR2_ARRAY: { @@ -572,16 +596,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<Vector2> array; array.resize(len); DVector<Vector2>::Write w = array.write(); - if (sizeof(Vector2)==8) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*2); + if (sizeof(Vector2) == 8) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 2); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*2;i++) { + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 2; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); + } } - } #endif @@ -589,8 +613,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp ERR_EXPLAIN("Vector2 size is NOT 8!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=DVector<Vector2>::Write(); - r_v=array; + w = DVector<Vector2>::Write(); + r_v = array; } break; case VARIANT_VECTOR3_ARRAY: { @@ -600,14 +624,14 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<Vector3> array; array.resize(len); DVector<Vector3>::Write w = array.write(); - if (sizeof(Vector3)==12) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*3); + if (sizeof(Vector3) == 12) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 3); #ifdef BIG_ENDIAN_ENABLED { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*3;i++) { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 3; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); } } @@ -617,8 +641,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp ERR_EXPLAIN("Vector3 size is NOT 12!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=DVector<Vector3>::Write(); - r_v=array; + w = DVector<Vector3>::Write(); + r_v = array; } break; case VARIANT_COLOR_ARRAY: { @@ -628,16 +652,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp DVector<Color> array; array.resize(len); DVector<Color>::Write w = array.write(); - if (sizeof(Color)==16) { - f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*4); + if (sizeof(Color) == 16) { + f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 4); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr=(uint32_t*)w.ptr(); - for(int i=0;i<len*4;i++) { + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 4; i++) { - ptr[i]=BSWAP32(ptr[i]); + ptr[i] = BSWAP32(ptr[i]); + } } - } #endif @@ -645,8 +669,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp ERR_EXPLAIN("Color size is NOT 16!"); ERR_FAIL_V(ERR_UNAVAILABLE); } - w=DVector<Color>::Write(); - r_v=array; + w = DVector<Color>::Write(); + r_v = array; } break; default: { @@ -654,47 +678,41 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v,bool p_for_exp } break; } - - return OK; //never reach anyway - } +void ResourceInteractiveLoaderBinary::set_local_path(const String &p_local_path) { -void ResourceInteractiveLoaderBinary::set_local_path(const String& p_local_path) { - - res_path=p_local_path; + res_path = p_local_path; } -Ref<Resource> ResourceInteractiveLoaderBinary::get_resource(){ - +Ref<Resource> ResourceInteractiveLoaderBinary::get_resource() { return resource; } -Error ResourceInteractiveLoaderBinary::poll(){ +Error ResourceInteractiveLoaderBinary::poll() { - if (error!=OK) + if (error != OK) return error; - int s = stage; - if (s<external_resources.size()) { + if (s < external_resources.size()) { String path = external_resources[s].path; if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res = ResourceLoader::load(path,external_resources[s].type); + RES res = ResourceLoader::load(path, external_resources[s].type); if (res.is_null()) { if (!ResourceLoader::get_abort_on_missing_resources()) { - ResourceLoader::notify_dependency_error(local_path,path,external_resources[s].type); + ResourceLoader::notify_dependency_error(local_path, path, external_resources[s].type); } else { - error=ERR_FILE_MISSING_DEPENDENCIES; - ERR_EXPLAIN("Can't load dependency: "+path); + error = ERR_FILE_MISSING_DEPENDENCIES; + ERR_EXPLAIN("Can't load dependency: " + path); ERR_FAIL_V(error); } @@ -706,44 +724,39 @@ Error ResourceInteractiveLoaderBinary::poll(){ return error; } - s-=external_resources.size(); + s -= external_resources.size(); + if (s >= internal_resources.size()) { - if (s>=internal_resources.size()) { - - error=ERR_BUG; - ERR_FAIL_COND_V(s>=internal_resources.size(),error); + error = ERR_BUG; + ERR_FAIL_COND_V(s >= internal_resources.size(), error); } - bool main = s==(internal_resources.size()-1); + bool main = s == (internal_resources.size() - 1); //maybe it is loaded already String path; - int subindex=0; - - + int subindex = 0; if (!main) { - path=internal_resources[s].path; + path = internal_resources[s].path; if (path.begins_with("local://")) { - path=path.replace_first("local://",""); + path = path.replace_first("local://", ""); subindex = path.to_int(); - path=res_path+"::"+path; + path = res_path + "::" + path; } - - if (ResourceCache::has(path)) { //already loaded, don't do anything stage++; - error=OK; + error = OK; return error; } } else { if (!ResourceCache::has(res_path)) - path=res_path; + path = res_path; } uint64_t offset = internal_resources[s].offset; @@ -754,20 +767,20 @@ Error ResourceInteractiveLoaderBinary::poll(){ Object *obj = ObjectTypeDB::instance(t); if (!obj) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":Resource of unrecognized type in file: "+t); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":Resource of unrecognized type in file: " + t); } - ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!obj, ERR_FILE_CORRUPT); Resource *r = obj->cast_to<Resource>(); if (!r) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; memdelete(obj); //bye - ERR_EXPLAIN(local_path+":Resoucre type in resource field not a resource, type is: "+obj->get_type()); - ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":Resoucre type in resource field not a resource, type is: " + obj->get_type()); + ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT); } - RES res = RES( r ); + RES res = RES(r); r->set_path(path); r->set_subindex(subindex); @@ -776,11 +789,11 @@ Error ResourceInteractiveLoaderBinary::poll(){ //set properties - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { uint32_t name_idx = f->get_32(); - if (name_idx>=(uint32_t)string_map.size()) { - error=ERR_FILE_CORRUPT; + if (name_idx >= (uint32_t)string_map.size()) { + error = ERR_FILE_CORRUPT; ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -790,7 +803,7 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (error) return error; - res->set(string_map[name_idx],value); + res->set(string_map[name_idx], value); } #ifdef TOOLS_ENABLED res->set_edited(false); @@ -803,63 +816,58 @@ Error ResourceInteractiveLoaderBinary::poll(){ if (importmd_ofs) { f->seek(importmd_ofs); - Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata ); + Ref<ResourceImportMetadata> imd = memnew(ResourceImportMetadata); imd->set_editor(get_unicode_string()); int sc = f->get_32(); - for(int i=0;i<sc;i++) { + for (int i = 0; i < sc; i++) { String src = get_unicode_string(); String md5 = get_unicode_string(); - imd->add_source(src,md5); + imd->add_source(src, md5); } int pc = f->get_32(); - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { String name = get_unicode_string(); Variant val; parse_variant(val); - imd->set_option(name,val); + imd->set_option(name, val); } res->set_import_metadata(imd); - } f->close(); - resource=res; - error=ERR_FILE_EOF; + resource = res; + error = ERR_FILE_EOF; } else { - error=OK; + error = OK; } return OK; - } -int ResourceInteractiveLoaderBinary::get_stage() const{ +int ResourceInteractiveLoaderBinary::get_stage() const { return stage; } int ResourceInteractiveLoaderBinary::get_stage_count() const { - return external_resources.size()+internal_resources.size(); + return external_resources.size() + internal_resources.size(); } - -static void save_ustring(FileAccess* f,const String& p_string) { - +static void save_ustring(FileAccess *f, const String &p_string) { CharString utf8 = p_string.utf8(); - f->store_32(utf8.length()+1); - f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1); + f->store_32(utf8.length() + 1); + f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } - static String get_ustring(FileAccess *f) { int len = f->get_32(); Vector<char> str_buf; str_buf.resize(len); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; @@ -868,47 +876,45 @@ static String get_ustring(FileAccess *f) { String ResourceInteractiveLoaderBinary::get_unicode_string() { int len = f->get_32(); - if (len>str_buf.size()) { + if (len > str_buf.size()) { str_buf.resize(len); } - if (len==0) + if (len == 0) return String(); - f->get_buffer((uint8_t*)&str_buf[0],len); + f->get_buffer((uint8_t *)&str_buf[0], len); String s; s.parse_utf8(&str_buf[0]); return s; } -Error ResourceInteractiveLoaderBinary::get_export_data(ExportData& r_export_data) { +Error ResourceInteractiveLoaderBinary::get_export_data(ExportData &r_export_data) { - for(int i=0;i<external_resources.size();i++) { + for (int i = 0; i < external_resources.size(); i++) { ExportData::Dependency dep; - dep.path=external_resources[i].path; - dep.type=external_resources[i].type; - r_export_data.dependencies[i]=dep; + dep.path = external_resources[i].path; + dep.type = external_resources[i].type; + r_export_data.dependencies[i] = dep; } - for(int i=0;i<internal_resources.size();i++) { + for (int i = 0; i < internal_resources.size(); i++) { - bool main = i==(internal_resources.size()-1); + bool main = i == (internal_resources.size() - 1); //maybe it is loaded already + r_export_data.resources.resize(r_export_data.resources.size() + 1); + ExportData::ResourceData &res_data = r_export_data.resources[r_export_data.resources.size() - 1]; - r_export_data.resources.resize( r_export_data.resources.size()+1 ); - ExportData::ResourceData &res_data=r_export_data.resources[ r_export_data.resources.size()-1 ]; - - res_data.index=-1; + res_data.index = -1; if (!main) { - String path=internal_resources[i].path; + String path = internal_resources[i].path; if (path.begins_with("local://")) { - path=path.replace_first("local://",""); + path = path.replace_first("local://", ""); res_data.index = path.to_int(); } } else { - } uint64_t offset = internal_resources[i].offset; @@ -917,85 +923,76 @@ Error ResourceInteractiveLoaderBinary::get_export_data(ExportData& r_export_data String t = get_unicode_string(); - res_data.type=t; + res_data.type = t; int pc = f->get_32(); //set properties - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { uint32_t name_idx = f->get_32(); - if (name_idx>=(uint32_t)string_map.size()) { - error=ERR_FILE_CORRUPT; + if (name_idx >= (uint32_t)string_map.size()) { + error = ERR_FILE_CORRUPT; ERR_FAIL_V(ERR_FILE_CORRUPT); } Variant value; - error = parse_variant(value,true); + error = parse_variant(value, true); if (error) return error; ExportData::PropertyData pdata; - pdata.name=string_map[name_idx]; - pdata.value=value; + pdata.name = string_map[name_idx]; + pdata.value = value; res_data.properties.push_back(pdata); } - } return OK; } - - - -void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f,List<String> *p_dependencies,bool p_add_types) { +void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) { open(p_f); if (error) return; - for(int i=0;i<external_resources.size();i++) { + for (int i = 0; i < external_resources.size(); i++) { - String dep=external_resources[i].path; + String dep = external_resources[i].path; if (dep.ends_with("*")) { - dep=ResourceLoader::guess_full_filename(dep,external_resources[i].type); + dep = ResourceLoader::guess_full_filename(dep, external_resources[i].type); } - if (p_add_types && external_resources[i].type!=String()) { - dep+="::"+external_resources[i].type; + if (p_add_types && external_resources[i].type != String()) { + dep += "::" + external_resources[i].type; } p_dependencies->push_back(dep); } - } - - - void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { + error = OK; - error=OK; - - f=p_f; + f = p_f; uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal - error=ERR_FILE_UNRECOGNIZED; - ERR_EXPLAIN("Unrecognized binary resource file: "+local_path); + error = ERR_FILE_UNRECOGNIZED; + ERR_EXPLAIN("Unrecognized binary resource file: " + local_path); ERR_FAIL(); } @@ -1008,53 +1005,51 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - print_bl("big endian: "+itos(big_endian)); - print_bl("endian swap: "+itos(endian_swap)); - print_bl("real64: "+itos(use_real64)); - print_bl("major: "+itos(ver_major)); - print_bl("minor: "+itos(ver_minor)); - print_bl("format: "+itos(ver_format)); + print_bl("big endian: " + itos(big_endian)); + print_bl("endian swap: " + itos(endian_swap)); + print_bl("real64: " + itos(use_real64)); + print_bl("major: " + itos(ver_major)); + print_bl("minor: " + itos(ver_minor)); + print_bl("format: " + itos(ver_format)); - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { f->close(); - ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path); + ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL(); - } - type=get_unicode_string(); + type = get_unicode_string(); - print_bl("type: "+type); + print_bl("type: " + type); importmd_ofs = f->get_64(); - for(int i=0;i<14;i++) + for (int i = 0; i < 14; i++) f->get_32(); //skip a few reserved fields - uint32_t string_table_size=f->get_32(); + uint32_t string_table_size = f->get_32(); string_map.resize(string_table_size); - for(uint32_t i=0;i<string_table_size;i++) { + for (uint32_t i = 0; i < string_table_size; i++) { StringName s = get_unicode_string(); - string_map[i]=s; + string_map[i] = s; } - print_bl("strings: "+itos(string_table_size)); + print_bl("strings: " + itos(string_table_size)); - uint32_t ext_resources_size=f->get_32(); - for(uint32_t i=0;i<ext_resources_size;i++) { + uint32_t ext_resources_size = f->get_32(); + for (uint32_t i = 0; i < ext_resources_size; i++) { ExtResoucre er; - er.type=get_unicode_string(); - er.path=get_unicode_string(); + er.type = get_unicode_string(); + er.path = get_unicode_string(); external_resources.push_back(er); - } //see if the exporter has different set of external resources for more efficient loading @@ -1071,46 +1066,43 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) { print_line(res_path+" - EXTERNAL RESOURCES: "+itos(external_resources.size())); }*/ - print_bl("ext resources: "+itos(ext_resources_size)); - uint32_t int_resources_size=f->get_32(); + print_bl("ext resources: " + itos(ext_resources_size)); + uint32_t int_resources_size = f->get_32(); - for(uint32_t i=0;i<int_resources_size;i++) { + for (uint32_t i = 0; i < int_resources_size; i++) { IntResoucre ir; - ir.path=get_unicode_string(); - ir.offset=f->get_64(); + ir.path = get_unicode_string(); + ir.offset = f->get_64(); internal_resources.push_back(ir); } - print_bl("int resources: "+itos(int_resources_size)); - + print_bl("int resources: " + itos(int_resources_size)); if (f->eof_reached()) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN("Premature End Of File: "+local_path); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN("Premature End Of File: " + local_path); ERR_FAIL(); } - } String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) { - error=OK; + error = OK; - - f=p_f; + f = p_f; uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal - error=ERR_FILE_UNRECOGNIZED; + error = ERR_FILE_UNRECOGNIZED; return ""; } @@ -1123,30 +1115,30 @@ String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) { bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { f->close(); return ""; } - String type=get_unicode_string(); + String type = get_unicode_string(); return type; } ResourceInteractiveLoaderBinary::ResourceInteractiveLoaderBinary() { - f=NULL; - stage=0; - endian_swap=false; - use_real64=false; - error=OK; + f = NULL; + stage = 0; + endian_swap = false; + use_real64 = false; + error = OK; } ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { @@ -1155,196 +1147,183 @@ ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() { memdelete(f); } - Ref<ResourceInteractiveLoader> ResourceFormatLoaderBinary::load_interactive(const String &p_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err!=OK) { + if (err != OK) { - ERR_FAIL_COND_V(err!=OK,Ref<ResourceInteractiveLoader>()); + ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>()); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); - return ria; } -void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { +void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List<String> extensions; - ObjectTypeDB::get_extensions_for_type(p_type,&extensions); + ObjectTypeDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); p_extensions->push_back(ext); } - } -void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const { List<String> extensions; ObjectTypeDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); p_extensions->push_back(ext); } - } -bool ResourceFormatLoaderBinary::handles_type(const String& p_type) const{ - +bool ResourceFormatLoaderBinary::handles_type(const String &p_type) const { return true; //handles all } -Error ResourceFormatLoaderBinary::load_import_metadata(const String &p_path, Ref<ResourceImportMetadata>& r_var) const { - +Error ResourceFormatLoaderBinary::load_import_metadata(const String &p_path, Ref<ResourceImportMetadata> &r_var) const { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ERR_FILE_CANT_OPEN; } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->recognize(f); - if(ria->error!=OK) + if (ria->error != OK) return ERR_FILE_UNRECOGNIZED; - f=ria->f; + f = ria->f; uint64_t imp_ofs = f->get_64(); - if (imp_ofs==0) + if (imp_ofs == 0) return ERR_UNAVAILABLE; f->seek(imp_ofs); - Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata ); + Ref<ResourceImportMetadata> imd = memnew(ResourceImportMetadata); imd->set_editor(ria->get_unicode_string()); int sc = f->get_32(); - for(int i=0;i<sc;i++) { + for (int i = 0; i < sc; i++) { String src = ria->get_unicode_string(); String md5 = ria->get_unicode_string(); - imd->add_source(src,md5); + imd->add_source(src, md5); } int pc = f->get_32(); - for(int i=0;i<pc;i++) { + for (int i = 0; i < pc; i++) { String name = ria->get_unicode_string(); Variant val; ria->parse_variant(val); - imd->set_option(name,val); + imd->set_option(name, val); } - r_var=imd; + r_var = imd; return OK; - } -ResourceFormatLoaderBinary *ResourceFormatLoaderBinary::singleton=NULL; +ResourceFormatLoaderBinary *ResourceFormatLoaderBinary::singleton = NULL; -void ResourceFormatLoaderBinary::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types) { +void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND(!f); - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); - ria->get_dependencies(f,p_dependencies,p_add_types); + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + ria->get_dependencies(f, p_dependencies, p_add_types); } - -Error ResourceFormatLoaderBinary::get_export_data(const String& p_path,ExportData& r_export_data) { +Error ResourceFormatLoaderBinary::get_export_data(const String &p_path, ExportData &r_export_data) { Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err!=OK) { + if (err != OK) { - ERR_FAIL_COND_V(err!=OK,ERR_CANT_OPEN); + ERR_FAIL_COND_V(err != OK, ERR_CANT_OPEN); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); - return ria->get_export_data(r_export_data); - } -Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { +Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { + // Error error=OK; -// Error error=OK; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); + FileAccess *fw = NULL; //=FileAccess::open(p_path+".depren"); - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); - - FileAccess* fw=NULL;//=FileAccess::open(p_path+".depren"); - - String local_path=p_path.get_base_dir(); + String local_path = p_path.get_base_dir(); uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') { + f->get_buffer(header, 4); + if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { //compressed - FileAccessCompressed *fac = memnew( FileAccessCompressed ); + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->open_after_magic(f); - f=fac; + f = fac; - FileAccessCompressed *facw = memnew( FileAccessCompressed ); + FileAccessCompressed *facw = memnew(FileAccessCompressed); facw->configure("RSCC"); - Error err = facw->_open(p_path+".depren",FileAccess::WRITE); + Error err = facw->_open(p_path + ".depren", FileAccess::WRITE); if (err) { memdelete(fac); memdelete(facw); - ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT); } - fw=facw; + fw = facw; - - } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') { + } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { //not normal //error=ERR_FILE_UNRECOGNIZED; memdelete(f); - ERR_EXPLAIN("Unrecognized binary resource file: "+local_path); + ERR_EXPLAIN("Unrecognized binary resource file: " + local_path); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } else { - fw = FileAccess::open(p_path+".depren",FileAccess::WRITE); + fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); if (!fw) { memdelete(f); } - ERR_FAIL_COND_V(!fw,ERR_CANT_CREATE); + ERR_FAIL_COND_V(!fw, ERR_CANT_CREATE); } bool big_endian = f->get_32(); @@ -1356,144 +1335,139 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const bool use_real64 = f->get_32(); - f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian + f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian fw->store_32(endian_swap); - fw->set_endian_swap(big_endian!=0); + fw->set_endian_swap(big_endian != 0); fw->store_32(use_real64); //use real64 - uint32_t ver_major=f->get_32(); - uint32_t ver_minor=f->get_32(); - uint32_t ver_format=f->get_32(); + uint32_t ver_major = f->get_32(); + uint32_t ver_minor = f->get_32(); + uint32_t ver_format = f->get_32(); - if (ver_format<FORMAT_VERSION_CAN_RENAME_DEPS) { + if (ver_format < FORMAT_VERSION_CAN_RENAME_DEPS) { memdelete(f); memdelete(fw); DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - da->remove(p_path+".depren"); + da->remove(p_path + ".depren"); memdelete(da); //fuck it, use the old approach; - WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: "+p_path).utf8().get_data()); + WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path).utf8().get_data()); Error err; - f = FileAccess::open(p_path,FileAccess::READ,&err); - if (err!=OK) { - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CANT_OPEN); + f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { + ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN); } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - ria->remaps=p_map; - // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + ria->remaps = p_map; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); err = ria->poll(); - while(err==OK) { - err=ria->poll(); + while (err == OK) { + err = ria->poll(); } - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, ERR_FILE_CORRUPT); RES res = ria->get_resource(); - ERR_FAIL_COND_V(!res.is_valid(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!res.is_valid(), ERR_FILE_CORRUPT); - return ResourceFormatSaverBinary::singleton->save(p_path,res); + return ResourceFormatSaverBinary::singleton->save(p_path, res); } - if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) { + if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { memdelete(f); memdelete(fw); - ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path); + ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } - fw->store_32( VERSION_MAJOR ); //current version - fw->store_32( VERSION_MINOR ); - fw->store_32( FORMAT_VERSION ); - - save_ustring(fw,get_ustring(f)); //type + fw->store_32(VERSION_MAJOR); //current version + fw->store_32(VERSION_MINOR); + fw->store_32(FORMAT_VERSION); + save_ustring(fw, get_ustring(f)); //type size_t md_ofs = f->get_pos(); size_t importmd_ofs = f->get_64(); fw->store_64(0); //metadata offset - for(int i=0;i<14;i++) { + for (int i = 0; i < 14; i++) { fw->store_32(0); f->get_32(); } //string table - uint32_t string_table_size=f->get_32(); + uint32_t string_table_size = f->get_32(); fw->store_32(string_table_size); - for(uint32_t i=0;i<string_table_size;i++) { + for (uint32_t i = 0; i < string_table_size; i++) { String s = get_ustring(f); - save_ustring(fw,s); + save_ustring(fw, s); } //external resources - uint32_t ext_resources_size=f->get_32(); + uint32_t ext_resources_size = f->get_32(); fw->store_32(ext_resources_size); - for(uint32_t i=0;i<ext_resources_size;i++) { + for (uint32_t i = 0; i < ext_resources_size; i++) { String type = get_ustring(f); String path = get_ustring(f); - bool relative=false; + bool relative = false; if (!path.begins_with("res://")) { - path=local_path.plus_file(path).simplify_path(); - relative=true; + path = local_path.plus_file(path).simplify_path(); + relative = true; } - if (p_map.has(path)) { - String np=p_map[path]; - path=np; + String np = p_map[path]; + path = np; } if (relative) { //restore relative - path=local_path.path_to_file(path); + path = local_path.path_to_file(path); } - save_ustring(fw,type); - save_ustring(fw,path); + save_ustring(fw, type); + save_ustring(fw, path); } int64_t size_diff = (int64_t)fw->get_pos() - (int64_t)f->get_pos(); //internal resources - uint32_t int_resources_size=f->get_32(); + uint32_t int_resources_size = f->get_32(); fw->store_32(int_resources_size); - for(uint32_t i=0;i<int_resources_size;i++) { - + for (uint32_t i = 0; i < int_resources_size; i++) { - String path=get_ustring(f); - uint64_t offset=f->get_64(); - save_ustring(fw,path); - fw->store_64(offset+size_diff); + String path = get_ustring(f); + uint64_t offset = f->get_64(); + save_ustring(fw, path); + fw->store_64(offset + size_diff); } //rest of file uint8_t b = f->get_8(); - while(!f->eof_reached()) { + while (!f->eof_reached()) { fw->store_8(b); b = f->get_8(); } - bool all_ok = fw->get_error()==OK; + bool all_ok = fw->get_error() == OK; fw->seek(md_ofs); - fw->store_64(importmd_ofs+size_diff); - + fw->store_64(importmd_ofs + size_diff); memdelete(f); memdelete(fw); @@ -1504,50 +1478,42 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); - da->rename(p_path+".depren",p_path); + da->rename(p_path + ".depren", p_path); memdelete(da); return OK; } - String ResourceFormatLoaderBinary::get_resource_type(const String &p_path) const { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ""; //could not rwead } - Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); String r = ria->recognize(f); return r; - - } - - /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// - void ResourceFormatSaverBinaryInstance::_pad_buffer(int p_bytes) { - int extra = 4-(p_bytes%4); - if (extra<4) { - for(int i=0;i<extra;i++) + int extra = 4 - (p_bytes % 4); + if (extra < 4) { + for (int i = 0; i < extra; i++) f->store_8(0); //pad to 32 } - } +void ResourceFormatSaverBinaryInstance::write_variant(const Variant &p_property, const PropertyInfo &p_hint) { -void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,const PropertyInfo& p_hint) { - - switch(p_property.get_type()) { + switch (p_property.get_type()) { case Variant::NIL: { @@ -1557,33 +1523,33 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::BOOL: { f->store_32(VARIANT_BOOL); - bool val=p_property; + bool val = p_property; f->store_32(val); } break; case Variant::INT: { f->store_32(VARIANT_INT); - int val=p_property; + int val = p_property; f->store_32(val); } break; case Variant::REAL: { f->store_32(VARIANT_REAL); - real_t val=p_property; + real_t val = p_property; f->store_real(val); } break; case Variant::STRING: { f->store_32(VARIANT_STRING); - String val=p_property; + String val = p_property; save_unicode_string(val); } break; case Variant::VECTOR2: { f->store_32(VARIANT_VECTOR2); - Vector2 val=p_property; + Vector2 val = p_property; f->store_real(val.x); f->store_real(val.y); @@ -1591,7 +1557,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::RECT2: { f->store_32(VARIANT_RECT2); - Rect2 val=p_property; + Rect2 val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.size.x); @@ -1601,7 +1567,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::VECTOR3: { f->store_32(VARIANT_VECTOR3); - Vector3 val=p_property; + Vector3 val = p_property; f->store_real(val.x); f->store_real(val.y); f->store_real(val.z); @@ -1610,7 +1576,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::PLANE: { f->store_32(VARIANT_PLANE); - Plane val=p_property; + Plane val = p_property; f->store_real(val.normal.x); f->store_real(val.normal.y); f->store_real(val.normal.z); @@ -1620,7 +1586,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::QUAT: { f->store_32(VARIANT_QUAT); - Quat val=p_property; + Quat val = p_property; f->store_real(val.x); f->store_real(val.y); f->store_real(val.z); @@ -1630,7 +1596,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::_AABB: { f->store_32(VARIANT_AABB); - AABB val=p_property; + AABB val = p_property; f->store_real(val.pos.x); f->store_real(val.pos.y); f->store_real(val.pos.z); @@ -1642,7 +1608,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::MATRIX32: { f->store_32(VARIANT_MATRIX32); - Matrix32 val=p_property; + Matrix32 val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[1].x); @@ -1654,7 +1620,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::MATRIX3: { f->store_32(VARIANT_MATRIX3); - Matrix3 val=p_property; + Matrix3 val = p_property; f->store_real(val.elements[0].x); f->store_real(val.elements[0].y); f->store_real(val.elements[0].z); @@ -1669,7 +1635,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::TRANSFORM: { f->store_32(VARIANT_TRANSFORM); - Transform val=p_property; + Transform val = p_property; f->store_real(val.basis.elements[0].x); f->store_real(val.basis.elements[0].y); f->store_real(val.basis.elements[0].z); @@ -1687,7 +1653,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::COLOR: { f->store_32(VARIANT_COLOR); - Color val=p_property; + Color val = p_property; f->store_real(val.r); f->store_real(val.g); f->store_real(val.b); @@ -1697,104 +1663,123 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, case Variant::IMAGE: { f->store_32(VARIANT_IMAGE); - Image val =p_property; + Image val = p_property; if (val.empty()) { f->store_32(IMAGE_ENCODING_EMPTY); break; } - int encoding=IMAGE_ENCODING_RAW; - float quality=0.7; + int encoding = IMAGE_ENCODING_RAW; + float quality = 0.7; if (val.get_format() <= Image::FORMAT_INDEXED_ALPHA) { //can only compress uncompressed stuff - if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) { - encoding=IMAGE_ENCODING_LOSSY; - float qs=p_hint.hint_string.to_double(); - if (qs!=0.0) - quality=qs; - - } else if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) { - encoding=IMAGE_ENCODING_LOSSLESS; + if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) { + encoding = IMAGE_ENCODING_LOSSY; + float qs = p_hint.hint_string.to_double(); + if (qs != 0.0) + quality = qs; + } else if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) { + encoding = IMAGE_ENCODING_LOSSLESS; } } f->store_32(encoding); //raw encoding - if (encoding==IMAGE_ENCODING_RAW) { - + if (encoding == IMAGE_ENCODING_RAW) { f->store_32(val.get_width()); f->store_32(val.get_height()); f->store_32(val.get_mipmaps()); - switch(val.get_format()) { + switch (val.get_format()) { - case Image::FORMAT_GRAYSCALE: f->store_32(IMAGE_FORMAT_GRAYSCALE ); break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 - case Image::FORMAT_INTENSITY: f->store_32(IMAGE_FORMAT_INTENSITY ); break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 - case Image::FORMAT_GRAYSCALE_ALPHA: f->store_32(IMAGE_FORMAT_GRAYSCALE_ALPHA ); break; ///< two bytes per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255. alpha 0-255 - case Image::FORMAT_RGB: f->store_32(IMAGE_FORMAT_RGB ); break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B - case Image::FORMAT_RGBA: f->store_32(IMAGE_FORMAT_RGBA ); break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B: f->store_32(IMAGE_FORMAT_ ); break; one byte A - case Image::FORMAT_INDEXED: f->store_32(IMAGE_FORMAT_INDEXED ); break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*3 bytes of palette - case Image::FORMAT_INDEXED_ALPHA: f->store_32(IMAGE_FORMAT_INDEXED_ALPHA ); break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*4 bytes of palette (alpha) - case Image::FORMAT_BC1: f->store_32(IMAGE_FORMAT_BC1 ); break; // DXT1 - case Image::FORMAT_BC2: f->store_32(IMAGE_FORMAT_BC2 ); break; // DXT3 - case Image::FORMAT_BC3: f->store_32(IMAGE_FORMAT_BC3 ); break; // DXT5 - case Image::FORMAT_BC4: f->store_32(IMAGE_FORMAT_BC4 ); break; // ATI1 - case Image::FORMAT_BC5: f->store_32(IMAGE_FORMAT_BC5 ); break; // ATI2 - case Image::FORMAT_PVRTC2: f->store_32(IMAGE_FORMAT_PVRTC2 ); break; - case Image::FORMAT_PVRTC2_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC2_ALPHA ); break; - case Image::FORMAT_PVRTC4: f->store_32(IMAGE_FORMAT_PVRTC4 ); break; - case Image::FORMAT_PVRTC4_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC4_ALPHA ); break; + case Image::FORMAT_GRAYSCALE: + f->store_32(IMAGE_FORMAT_GRAYSCALE); + break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 + case Image::FORMAT_INTENSITY: + f->store_32(IMAGE_FORMAT_INTENSITY); + break; ///< one byte per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255 + case Image::FORMAT_GRAYSCALE_ALPHA: + f->store_32(IMAGE_FORMAT_GRAYSCALE_ALPHA); + break; ///< two bytes per pixel: f->store_32(IMAGE_FORMAT_ ); break; 0-255. alpha 0-255 + case Image::FORMAT_RGB: + f->store_32(IMAGE_FORMAT_RGB); + break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B + case Image::FORMAT_RGBA: + f->store_32(IMAGE_FORMAT_RGBA); + break; ///< one byte R: f->store_32(IMAGE_FORMAT_ ); break; one byte G: f->store_32(IMAGE_FORMAT_ ); break; one byte B: f->store_32(IMAGE_FORMAT_ ); break; one byte A + case Image::FORMAT_INDEXED: + f->store_32(IMAGE_FORMAT_INDEXED); + break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*3 bytes of palette + case Image::FORMAT_INDEXED_ALPHA: + f->store_32(IMAGE_FORMAT_INDEXED_ALPHA); + break; ///< index byte 0-256: f->store_32(IMAGE_FORMAT_ ); break; and after image end: f->store_32(IMAGE_FORMAT_ ); break; 256*4 bytes of palette (alpha) + case Image::FORMAT_BC1: + f->store_32(IMAGE_FORMAT_BC1); + break; // DXT1 + case Image::FORMAT_BC2: + f->store_32(IMAGE_FORMAT_BC2); + break; // DXT3 + case Image::FORMAT_BC3: + f->store_32(IMAGE_FORMAT_BC3); + break; // DXT5 + case Image::FORMAT_BC4: + f->store_32(IMAGE_FORMAT_BC4); + break; // ATI1 + case Image::FORMAT_BC5: + f->store_32(IMAGE_FORMAT_BC5); + break; // ATI2 + case Image::FORMAT_PVRTC2: f->store_32(IMAGE_FORMAT_PVRTC2); break; + case Image::FORMAT_PVRTC2_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC2_ALPHA); break; + case Image::FORMAT_PVRTC4: f->store_32(IMAGE_FORMAT_PVRTC4); break; + case Image::FORMAT_PVRTC4_ALPHA: f->store_32(IMAGE_FORMAT_PVRTC4_ALPHA); break; case Image::FORMAT_ETC: f->store_32(IMAGE_FORMAT_ETC); break; case Image::FORMAT_ATC: f->store_32(IMAGE_FORMAT_ATC); break; case Image::FORMAT_ATC_ALPHA_EXPLICIT: f->store_32(IMAGE_FORMAT_ATC_ALPHA_EXPLICIT); break; case Image::FORMAT_ATC_ALPHA_INTERPOLATED: f->store_32(IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED); break; - case Image::FORMAT_CUSTOM: f->store_32(IMAGE_FORMAT_CUSTOM ); break; + case Image::FORMAT_CUSTOM: f->store_32(IMAGE_FORMAT_CUSTOM); break; default: {} - } int dlen = val.get_data().size(); f->store_32(dlen); DVector<uint8_t>::Read r = val.get_data().read(); - f->store_buffer(r.ptr(),dlen); + f->store_buffer(r.ptr(), dlen); _pad_buffer(dlen); } else { DVector<uint8_t> data; - if (encoding==IMAGE_ENCODING_LOSSY) { - data=Image::lossy_packer(val,quality); - - } else if (encoding==IMAGE_ENCODING_LOSSLESS) { - data=Image::lossless_packer(val); + if (encoding == IMAGE_ENCODING_LOSSY) { + data = Image::lossy_packer(val, quality); + } else if (encoding == IMAGE_ENCODING_LOSSLESS) { + data = Image::lossless_packer(val); } - int ds=data.size(); + int ds = data.size(); f->store_32(ds); - if (ds>0) { + if (ds > 0) { DVector<uint8_t>::Read r = data.read(); - f->store_buffer(r.ptr(),ds); + f->store_buffer(r.ptr(), ds); _pad_buffer(ds); - } } } break; case Variant::NODE_PATH: { f->store_32(VARIANT_NODE_PATH); - NodePath np=p_property; + NodePath np = p_property; f->store_16(np.get_name_count()); uint16_t snc = np.get_subname_count(); if (np.is_absolute()) - snc|=0x8000; + snc |= 0x8000; f->store_16(snc); - for(int i=0;i<np.get_name_count();i++) + for (int i = 0; i < np.get_name_count(); i++) f->store_32(get_string_index(np.get_name(i))); - for(int i=0;i<np.get_subname_count();i++) + for (int i = 0; i < np.get_subname_count(); i++) f->store_32(get_string_index(np.get_subname(i))); f->store_32(get_string_index(np.get_property())); @@ -1815,7 +1800,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, return; // don't save it } - if (res->get_path().length() && res->get_path().find("::")==-1) { + if (res->get_path().length() && res->get_path().find("::") == -1) { f->store_32(OBJECT_EXTERNAL_RESOURCE_INDEX); f->store_32(external_resources[res]); } else { @@ -1831,7 +1816,6 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, //internal resource } - } break; case Variant::INPUT_EVENT: { @@ -1842,12 +1826,12 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_DICTIONARY); Dictionary d = p_property; - f->store_32(uint32_t(d.size())|(d.is_shared()?0x80000000:0)); + f->store_32(uint32_t(d.size()) | (d.is_shared() ? 0x80000000 : 0)); List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { //if (!_check_type(dict[E->get()])) // continue; @@ -1856,14 +1840,13 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, write_variant(d[E->get()]); } - } break; case Variant::ARRAY: { f->store_32(VARIANT_ARRAY); - Array a=p_property; - f->store_32(uint32_t(a.size())|(a.is_shared()?0x80000000:0)); - for(int i=0;i<a.size();i++) { + Array a = p_property; + f->store_32(uint32_t(a.size()) | (a.is_shared() ? 0x80000000 : 0)); + for (int i = 0; i < a.size(); i++) { write_variant(a[i]); } @@ -1873,10 +1856,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_RAW_ARRAY); DVector<uint8_t> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<uint8_t>::Read r = arr.read(); - f->store_buffer(r.ptr(),len); + f->store_buffer(r.ptr(), len); _pad_buffer(len); } break; @@ -1884,10 +1867,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_INT_ARRAY); DVector<int> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<int>::Read r = arr.read(); - for(int i=0;i<len;i++) + for (int i = 0; i < len; i++) f->store_32(r[i]); } break; @@ -1895,10 +1878,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_REAL_ARRAY); DVector<real_t> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<real_t>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i]); } @@ -1907,10 +1890,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_STRING_ARRAY); DVector<String> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<String>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { save_unicode_string(r[i]); } @@ -1919,10 +1902,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR3_ARRAY); DVector<Vector3> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<Vector3>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].x); f->store_real(r[i].y); f->store_real(r[i].z); @@ -1933,10 +1916,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_VECTOR2_ARRAY); DVector<Vector2> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<Vector2>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].x); f->store_real(r[i].y); } @@ -1946,10 +1929,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, f->store_32(VARIANT_COLOR_ARRAY); DVector<Color> arr = p_property; - int len=arr.size(); + int len = arr.size(); f->store_32(len); DVector<Color>::Read r = arr.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { f->store_real(r[i].r); f->store_real(r[i].g); f->store_real(r[i].b); @@ -1965,26 +1948,22 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property, } } +void ResourceFormatSaverBinaryInstance::_find_resources(const Variant &p_variant, bool p_main) { -void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant,bool p_main) { - - - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::OBJECT: { - RES res = p_variant.operator RefPtr(); if (res.is_null() || external_resources.has(res)) return; - if (!p_main && (!bundle_resources ) && res->get_path().length() && res->get_path().find("::") == -1 ) { + if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) { int idx = external_resources.size(); - external_resources[res]=idx; + external_resources[res] = idx; return; } - if (resource_set.has(res)) return; @@ -1992,9 +1971,9 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant res->get_property_list(&property_list); - for(List<PropertyInfo>::Element *E=property_list.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { - if (E->get().usage&PROPERTY_USAGE_STORAGE || (bundle_resources && E->get().usage&PROPERTY_USAGE_BUNDLE)) { + if (E->get().usage & PROPERTY_USAGE_STORAGE || (bundle_resources && E->get().usage & PROPERTY_USAGE_BUNDLE)) { _find_resources(res->get(E->get().name)); } @@ -2007,11 +1986,11 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::ARRAY: { - Array varray=p_variant; - int len=varray.size(); - for(int i=0;i<len;i++) { + Array varray = p_variant; + int len = varray.size(); + for (int i = 0; i < len; i++) { - Variant v=varray.get(i); + Variant v = varray.get(i); _find_resources(v); } @@ -2019,10 +1998,10 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::DICTIONARY: { - Dictionary d=p_variant; + Dictionary d = p_variant; List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _find_resources(E->get()); Variant v = d[E->get()]; @@ -2032,18 +2011,16 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant case Variant::NODE_PATH: { //take the chance and save node path strings NodePath np = p_variant; - for(int i=0;i<np.get_name_count();i++) + for (int i = 0; i < np.get_name_count(); i++) get_string_index(np.get_name(i)); - for(int i=0;i<np.get_subname_count();i++) + for (int i = 0; i < np.get_subname_count(); i++) get_string_index(np.get_subname(i)); get_string_index(np.get_property()); - } break; default: {} } - } #if 0 Error ResourceFormatSaverBinary::_save_obj(const Object *p_object,SavedObject *so) { @@ -2094,64 +2071,60 @@ Error ResourceFormatSaverBinary::save(const Object *p_object,const Variant &p_me } #endif -void ResourceFormatSaverBinaryInstance::save_unicode_string(const String& p_string) { - +void ResourceFormatSaverBinaryInstance::save_unicode_string(const String &p_string) { CharString utf8 = p_string.utf8(); - f->store_32(utf8.length()+1); - f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1); + f->store_32(utf8.length() + 1); + f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } -int ResourceFormatSaverBinaryInstance::get_string_index(const String& p_string) { +int ResourceFormatSaverBinaryInstance::get_string_index(const String &p_string) { - StringName s=p_string; + StringName s = p_string; if (string_map.has(s)) return string_map[s]; - string_map[s]=strings.size(); + string_map[s] = strings.size(); strings.push_back(s); - return strings.size()-1; + return strings.size() - 1; } - -Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +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 ); + if (p_flags & ResourceSaver::FLAG_COMPRESS) { + FileAccessCompressed *fac = memnew(FileAccessCompressed); fac->configure("RSCC"); - f=fac; - err = fac->_open(p_path,FileAccess::WRITE); + f = fac; + err = fac->_open(p_path, FileAccess::WRITE); if (err) memdelete(f); } else { - f=FileAccess::open(p_path,FileAccess::WRITE,&err); + f = FileAccess::open(p_path, FileAccess::WRITE, &err); } - - ERR_FAIL_COND_V(err,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; - takeover_paths=p_flags&ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; + 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; + takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; if (!p_path.begins_with("res://")) - takeover_paths=false; + takeover_paths = false; - local_path=p_path.get_base_dir(); + 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); + _find_resources(p_resource, true); - if (!(p_flags&ResourceSaver::FLAG_COMPRESS)) { + if (!(p_flags & ResourceSaver::FLAG_COMPRESS)) { //save header compressed - static const uint8_t header[4]={'R','S','R','C'}; - f->store_buffer(header,4); + static const uint8_t header[4] = { 'R', 'S', 'R', 'C' }; + f->store_buffer(header, 4); } if (big_endian) { @@ -2165,7 +2138,7 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ f->store_32(VERSION_MINOR); f->store_32(FORMAT_VERSION); - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } @@ -2174,50 +2147,41 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ 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++) + 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()) { - + 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(); + rd.type = E->get()->get_type(); List<PropertyInfo> property_list; - E->get()->get_property_list( &property_list ); + E->get()->get_property_list(&property_list); - for(List<PropertyInfo>::Element *F=property_list.front();F;F=F->next()) { + 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)) { + 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())||(F->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one()) ) + 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()) || (F->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one())) continue; - p.pi=F->get(); + 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++) { + for (int i = 0; i < strings.size(); i++) { //print_bl("saving string: "+strings[i]); save_unicode_string(strings[i]); } @@ -2227,15 +2191,15 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector<RES> save_order; save_order.resize(external_resources.size()); - for(Map<RES,int>::Element *E=external_resources.front();E;E=E->next()) { - save_order[E->get()]=E->key(); + for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) { + save_order[E->get()] = E->key(); } - for(int i=0;i<save_order.size();i++) { + for (int i = 0; i < save_order.size(); i++) { save_unicode_string(save_order[i]->get_save_type()); String path = save_order[i]->get_path(); - path=relative_paths?local_path.path_to_file(path):path; + path = relative_paths ? local_path.path_to_file(path) : path; save_unicode_string(path); } // save internal resource table @@ -2243,12 +2207,12 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ Vector<uint64_t> ofs_pos; Set<int> used_indices; - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { + 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) { + if (r->get_path() == "" || r->get_path().find("::") != -1) { - if (r->get_subindex()!=0) { + if (r->get_subindex() != 0) { if (used_indices.has(r->get_subindex())) { r->set_subindex(0); //repeated } else { @@ -2256,29 +2220,25 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ } } } - } - - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { - + 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) { - if (r->get_subindex()==0) { - int new_subindex=1; + if (r->get_path() == "" || r->get_path().find("::") != -1) { + if (r->get_subindex() == 0) { + int new_subindex = 1; if (used_indices.size()) { - new_subindex=used_indices.back()->get()+1; + new_subindex = used_indices.back()->get() + 1; } r->set_subindex(new_subindex); used_indices.insert(new_subindex); - } - save_unicode_string("local://"+itos(r->get_subindex())); + save_unicode_string("local://" + itos(r->get_subindex())); if (takeover_paths) { - r->set_path(p_path+"::"+itos(r->get_subindex()),true); + r->set_path(p_path + "::" + itos(r->get_subindex()), true); } } else { save_unicode_string(r->get_path()); //actual external @@ -2288,48 +2248,47 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ } Vector<uint64_t> ofs_table; -// int saved_idx=0; + // int saved_idx=0; //now actually save the resources - for(List<ResourceData>::Element *E=resources.front();E;E=E->next()) { + for (List<ResourceData>::Element *E = resources.front(); E; E = E->next()) { - ResourceData & rd = E->get(); + 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()) { + for (List<Property>::Element *F = rd.properties.front(); F; F = F->next()) { - Property &p=F->get(); + Property &p = F->get(); f->store_32(p.name_idx); - write_variant(p.value,F->get().pi); + write_variant(p.value, F->get().pi); } - } - for(int i=0;i<ofs_table.size();i++) { + for (int i = 0; i < ofs_table.size(); i++) { f->seek(ofs_pos[i]); f->store_64(ofs_table[i]); } f->seek_end(); - print_line("SAVING: "+p_path); + print_line("SAVING: " + p_path); if (p_resource->get_import_metadata().is_valid()) { uint64_t md_pos = f->get_pos(); - Ref<ResourceImportMetadata> imd=p_resource->get_import_metadata(); + 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++) { + 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)); - print_line("SAVE PATH: "+imd->get_source_path(i)); - print_line("SAVE MD5: "+imd->get_source_md5(i)); + print_line("SAVE PATH: " + imd->get_source_path(i)); + print_line("SAVE MD5: " + 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()) { + for (List<String>::Element *E = options.front(); E; E = E->next()) { save_unicode_string(E->get()); write_variant(imd->get_option(E->get())); } @@ -2339,48 +2298,39 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_ f->seek_end(); } + f->store_buffer((const uint8_t *)"RSRC", 4); //magic at end - f->store_buffer((const uint8_t*)"RSRC",4); //magic at end - - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } f->close(); - return OK; } - - -Error ResourceFormatSaverBinary::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { - +Error ResourceFormatSaverBinary::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { String local_path = Globals::get_singleton()->localize_path(p_path); ResourceFormatSaverBinaryInstance saver; - return saver.save(local_path,p_resource,p_flags); - + return saver.save(local_path, p_resource, p_flags); } - -bool ResourceFormatSaverBinary::recognize(const RES& p_resource) const { +bool ResourceFormatSaverBinary::recognize(const RES &p_resource) const { return true; //all recognized - } -void ResourceFormatSaverBinary::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { +void ResourceFormatSaverBinary::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { String base = p_resource->get_base_extension().to_lower(); p_extensions->push_back(base); - } -ResourceFormatSaverBinary* ResourceFormatSaverBinary::singleton=NULL; +ResourceFormatSaverBinary *ResourceFormatSaverBinary::singleton = NULL; ResourceFormatSaverBinary::ResourceFormatSaverBinary() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_format_binary.h b/core/io/resource_format_binary.h index 566767b83..a7bd782b3 100644 --- a/core/io/resource_format_binary.h +++ b/core/io/resource_format_binary.h @@ -33,7 +33,6 @@ #include "io/resource_saver.h" #include "os/file_access.h" - class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String local_path; @@ -43,7 +42,6 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { FileAccess *f; - bool endian_swap; bool use_real64; uint64_t importmd_ofs; @@ -71,62 +69,54 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader { String get_unicode_string(); void _advance_padding(uint32_t p_len); - Map<String,String> remaps; + Map<String, String> remaps; Error error; int stage; -friend class ResourceFormatLoaderBinary; + friend class ResourceFormatLoaderBinary; - - Error parse_variant(Variant& r_v, bool p_for_export_data=false); + Error parse_variant(Variant &r_v, bool p_for_export_data = false); public: - - virtual void set_local_path(const String& p_local_path); + virtual void set_local_path(const String &p_local_path); virtual Ref<Resource> get_resource(); virtual Error poll(); virtual int get_stage() const; virtual int get_stage_count() const; - void set_remaps(const Map<String,String>& p_remaps) { remaps=p_remaps; } + void set_remaps(const Map<String, String> &p_remaps) { remaps = p_remaps; } void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); - Error get_export_data(ExportData& r_export_data); + Error get_export_data(ExportData &r_export_data); ResourceInteractiveLoaderBinary(); ~ResourceInteractiveLoaderBinary(); - }; class ResourceFormatLoaderBinary : public ResourceFormatLoader { public: - - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - virtual void get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types=false); - virtual Error load_import_metadata(const String &p_path, Ref<ResourceImportMetadata>& r_var) const; - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - virtual Error get_export_data(const String& p_path,ExportData& r_export_data); + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error load_import_metadata(const String &p_path, Ref<ResourceImportMetadata> &r_var) const; + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); + virtual Error get_export_data(const String &p_path, ExportData &r_export_data); static ResourceFormatLoaderBinary *singleton; - ResourceFormatLoaderBinary() { singleton=this; } + ResourceFormatLoaderBinary() { singleton = this; } }; - - - -class ResourceFormatSaverBinaryInstance { +class ResourceFormatSaverBinaryInstance { String local_path; - bool relative_paths; bool bundle_resources; bool skip_editor; @@ -136,19 +126,16 @@ class ResourceFormatSaverBinaryInstance { FileAccess *f; String magic; Set<RES> resource_set; - Map<StringName,int> string_map; + Map<StringName, int> string_map; Vector<StringName> strings; - - Map<RES,int> external_resources; + Map<RES, int> external_resources; List<RES> saved_resources; - struct Property { int name_idx; Variant value; PropertyInfo pi; - }; struct ResourceData { @@ -157,36 +144,25 @@ class ResourceFormatSaverBinaryInstance { List<Property> properties; }; - - - void _pad_buffer(int p_bytes); - void write_variant(const Variant& p_property,const PropertyInfo& p_hint=PropertyInfo()); - void _find_resources(const Variant& p_variant,bool p_main=false); - void save_unicode_string(const String& p_string); - int get_string_index(const String& p_string); -public: + void write_variant(const Variant &p_property, const PropertyInfo &p_hint = PropertyInfo()); + void _find_resources(const Variant &p_variant, bool p_main = false); + void save_unicode_string(const String &p_string); + int get_string_index(const String &p_string); - - Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); +public: + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); }; - - -class ResourceFormatSaverBinary : public ResourceFormatSaver { - - - +class ResourceFormatSaverBinary : public ResourceFormatSaver { public: - - static ResourceFormatSaverBinary* singleton; - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - virtual bool recognize(const RES& p_resource) const; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const; + static ResourceFormatSaverBinary *singleton; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual bool recognize(const RES &p_resource) const; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; ResourceFormatSaverBinary(); }; - #endif // RESOURCE_FORMAT_BINARY_H diff --git a/core/io/resource_format_xml.cpp b/core/io/resource_format_xml.cpp index 8be6a32f6..e66e11b83 100644 --- a/core/io/resource_format_xml.cpp +++ b/core/io/resource_format_xml.cpp @@ -28,36 +28,35 @@ /*************************************************************************/ #include "resource_format_xml.h" #include "globals.h" -#include "version.h" #include "os/dir_access.h" +#include "version.h" +ResourceInteractiveLoaderXML::Tag *ResourceInteractiveLoaderXML::parse_tag(bool *r_exit, bool p_printerr, List<String> *r_order) { -ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool *r_exit, bool p_printerr, List<String> *r_order) { - - - while(get_char()!='<' && !f->eof_reached()) {} + while (get_char() != '<' && !f->eof_reached()) { + } if (f->eof_reached()) { return NULL; } Tag tag; - bool exit=false; + bool exit = false; if (r_exit) - *r_exit=false; + *r_exit = false; - bool complete=false; - while(!f->eof_reached()) { + bool complete = false; + while (!f->eof_reached()) { - CharType c=get_char(); - if (c<33 && tag.name.length() && !exit) { + CharType c = get_char(); + if (c < 33 && tag.name.length() && !exit) { break; - } else if (c=='>') { - complete=true; + } else if (c == '>') { + complete = true; break; - } else if (c=='/') { - exit=true; + } else if (c == '/') { + exit = true; } else { - tag.name+=c; + tag.name += c; } } @@ -70,67 +69,67 @@ ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool if (!tag_stack.size()) { if (!p_printerr) return NULL; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Unmatched exit tag </"+tag.name+">"); - ERR_FAIL_COND_V(!tag_stack.size(),NULL); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Unmatched exit tag </" + tag.name + ">"); + ERR_FAIL_COND_V(!tag_stack.size(), NULL); } - if (tag_stack.back()->get().name!=tag.name) { + if (tag_stack.back()->get().name != tag.name) { if (!p_printerr) return NULL; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Mismatched exit tag. Got </"+tag.name+">, expected </"+tag_stack.back()->get().name+">"); - ERR_FAIL_COND_V(tag_stack.back()->get().name!=tag.name,NULL); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Mismatched exit tag. Got </" + tag.name + ">, expected </" + tag_stack.back()->get().name + ">"); + ERR_FAIL_COND_V(tag_stack.back()->get().name != tag.name, NULL); } if (!complete) { - while(get_char()!='>' && !f->eof_reached()) {} + while (get_char() != '>' && !f->eof_reached()) { + } if (f->eof_reached()) return NULL; } if (r_exit) - *r_exit=true; + *r_exit = true; tag_stack.pop_back(); return NULL; - } if (!complete) { String name; CharString r_value; - bool reading_value=false; + bool reading_value = false; - while(!f->eof_reached()) { + while (!f->eof_reached()) { - CharType c=get_char(); - if (c=='>') { + CharType c = get_char(); + if (c == '>') { if (r_value.size()) { r_value.push_back(0); String str; str.parse_utf8(r_value.get_data()); - tag.args[name]=str; + tag.args[name] = str; if (r_order) r_order->push_back(name); } break; - } else if ( ((!reading_value && (c<33)) || c=='=' || c=='"' || c=='\'') && tag.name.length()) { + } else if (((!reading_value && (c < 33)) || c == '=' || c == '"' || c == '\'') && tag.name.length()) { if (!reading_value && name.length()) { - reading_value=true; + reading_value = true; } else if (reading_value && r_value.size()) { r_value.push_back(0); String str; str.parse_utf8(r_value.get_data()); - tag.args[name]=str; + tag.args[name] = str; if (r_order) r_order->push_back(name); - name=""; + name = ""; r_value.clear(); - reading_value=false; + reading_value = false; } } else if (reading_value) { @@ -138,7 +137,7 @@ ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool r_value.push_back(c); } else { - name+=c; + name += c; } } @@ -151,18 +150,17 @@ ResourceInteractiveLoaderXML::Tag* ResourceInteractiveLoaderXML::parse_tag(bool return &tag_stack.back()->get(); } +Error ResourceInteractiveLoaderXML::close_tag(const String &p_name) { -Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { - - int level=0; - bool inside_tag=false; + int level = 0; + bool inside_tag = false; - while(true) { + while (true) { if (f->eof_reached()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": EOF found while attempting to find </"+p_name+">"); - ERR_FAIL_COND_V( f->eof_reached(), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": EOF found while attempting to find </" + p_name + ">"); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); } uint8_t c = get_char(); @@ -170,10 +168,10 @@ Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { if (c == '<') { if (inside_tag) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Malformed XML. Already inside Tag."); - ERR_FAIL_COND_V(inside_tag,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Malformed XML. Already inside Tag."); + ERR_FAIL_COND_V(inside_tag, ERR_FILE_CORRUPT); } - inside_tag=true; + inside_tag = true; c = get_char(); if (c == '/') { @@ -185,10 +183,10 @@ Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { } else if (c == '>') { if (!inside_tag) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Malformed XML. Already outside Tag"); - ERR_FAIL_COND_V(!inside_tag,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Malformed XML. Already outside Tag"); + ERR_FAIL_COND_V(!inside_tag, ERR_FILE_CORRUPT); } - inside_tag=false; + inside_tag = false; if (level == -1) { tag_stack.pop_back(); return OK; @@ -199,10 +197,9 @@ Error ResourceInteractiveLoaderXML::close_tag(const String& p_name) { return OK; } -void ResourceInteractiveLoaderXML::unquote(String& p_str) { - +void ResourceInteractiveLoaderXML::unquote(String &p_str) { - p_str=p_str.strip_edges().replace("\"","").xml_unescape(); + p_str = p_str.strip_edges().replace("\"", "").xml_unescape(); /*p_str=p_str.strip_edges(); p_str=p_str.replace("\"",""); @@ -218,40 +215,37 @@ void ResourceInteractiveLoaderXML::unquote(String& p_str) { p_str=p_str.replace("&","&"); */ //p_str.parse_utf8( p_str.ascii(true).get_data() ); - } Error ResourceInteractiveLoaderXML::goto_end_of_tag() { uint8_t c; - while(true) { + while (true) { - c=get_char(); - if (c=='>') //closetag + c = get_char(); + if (c == '>') //closetag break; if (f->eof_reached()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": EOF found while attempting to find close tag."); - ERR_FAIL_COND_V( f->eof_reached(), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": EOF found while attempting to find close tag."); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); } - } tag_stack.pop_back(); return OK; } - Error ResourceInteractiveLoaderXML::parse_property_data(String &r_data) { - r_data=""; + r_data = ""; CharString cs; - while(true) { + while (true) { - CharType c=get_char(); - if (c=='<') + CharType c = get_char(); + if (c == '<') break; - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); cs.push_back(c); } @@ -259,51 +253,50 @@ Error ResourceInteractiveLoaderXML::parse_property_data(String &r_data) { r_data.parse_utf8(cs.get_data()); - while(get_char()!='>' && !f->eof_reached()) {} + while (get_char() != '>' && !f->eof_reached()) { + } if (f->eof_reached()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Malformed XML."); - ERR_FAIL_COND_V( f->eof_reached(), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Malformed XML."); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); } - r_data=r_data.strip_edges(); + r_data = r_data.strip_edges(); tag_stack.pop_back(); return OK; } - -Error ResourceInteractiveLoaderXML::_parse_array_element(Vector<char> &buff,bool p_number_only,FileAccess *f,bool *end) { +Error ResourceInteractiveLoaderXML::_parse_array_element(Vector<char> &buff, bool p_number_only, FileAccess *f, bool *end) { if (buff.empty()) buff.resize(32); // optimi - int buff_max=buff.size(); - int buff_size=0; - *end=false; - char *buffptr=&buff[0]; - bool found=false; - bool quoted=false; + int buff_max = buff.size(); + int buff_size = 0; + *end = false; + char *buffptr = &buff[0]; + bool found = false; + bool quoted = false; - while(true) { + while (true) { - char c=get_char(); + char c = get_char(); - if (c==0) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": File corrupt (zero found)."); + if (c == 0) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": File corrupt (zero found)."); ERR_FAIL_V(ERR_FILE_CORRUPT); - } else if (c=='"') { - quoted=!quoted; - } else if ((!quoted && ((p_number_only && c<33) || c==',')) || c=='<') { + } else if (c == '"') { + quoted = !quoted; + } else if ((!quoted && ((p_number_only && c < 33) || c == ',')) || c == '<') { - - if (c=='<') { - *end=true; + if (c == '<') { + *end = true; break; } - if (c<32 && f->eof_reached()) { - *end=true; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": File corrupt (unexpected EOF)."); + if (c < 32 && f->eof_reached()) { + *end = true; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": File corrupt (unexpected EOF)."); ERR_FAIL_V(ERR_FILE_CORRUPT); } @@ -312,34 +305,32 @@ Error ResourceInteractiveLoaderXML::_parse_array_element(Vector<char> &buff,bool } else { - found=true; - if (buff_size>=buff_max) { + found = true; + if (buff_size >= buff_max) { buff_max++; buff.resize(buff_max); - buffptr=buff.ptr(); - + buffptr = buff.ptr(); } - buffptr[buff_size]=c; + buffptr[buff_size] = c; buff_size++; } } - if (buff_size>=buff_max) { + if (buff_size >= buff_max) { buff_max++; buff.resize(buff_max); - } - buff[buff_size]=0; + buff[buff_size] = 0; buff_size++; return OK; } -Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, bool p_for_export_data) { +Error ResourceInteractiveLoaderXML::parse_property(Variant &r_v, String &r_name, bool p_for_export_data) { bool exit; Tag *tag = parse_tag(&exit); @@ -347,33 +338,32 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, if (!tag) { if (exit) // shouldn't have exited return ERR_FILE_EOF; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": File corrupt (No Property Tag)."); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": File corrupt (No Property Tag)."); ERR_FAIL_V(ERR_FILE_CORRUPT); } - r_v=Variant(); - r_name=""; - + r_v = Variant(); + r_name = ""; //ERR_FAIL_COND_V(tag->name!="property",ERR_FILE_CORRUPT); //ERR_FAIL_COND_V(!tag->args.has("name"),ERR_FILE_CORRUPT); -// ERR_FAIL_COND_V(!tag->args.has("type"),ERR_FILE_CORRUPT); + // ERR_FAIL_COND_V(!tag->args.has("type"),ERR_FILE_CORRUPT); //String name=tag->args["name"]; //ERR_FAIL_COND_V(name=="",ERR_FILE_CORRUPT); - String type=tag->name; - String name=tag->args["name"]; + String type = tag->name; + String name = tag->args["name"]; - if (type=="") { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": 'type' field is empty."); - ERR_FAIL_COND_V(type=="",ERR_FILE_CORRUPT); + if (type == "") { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": 'type' field is empty."); + ERR_FAIL_COND_V(type == "", ERR_FILE_CORRUPT); } - if (type=="dictionary") { + if (type == "dictionary") { - Dictionary d( tag->args.has("shared") && (String(tag->args["shared"])=="true" || String(tag->args["shared"])=="1")); + Dictionary d(tag->args.has("shared") && (String(tag->args["shared"]) == "true" || String(tag->args["shared"]) == "1")); - while(true) { + while (true) { Error err; String tagname; @@ -381,46 +371,43 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, int dictline = get_current_line(); + err = parse_property(key, tagname, p_for_export_data); - err=parse_property(key,tagname,p_for_export_data); - - if (err && err!=ERR_FILE_EOF) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error parsing dictionary: "+name+" (from line "+itos(dictline)+")"); - ERR_FAIL_COND_V(err && err!=ERR_FILE_EOF,err); + if (err && err != ERR_FILE_EOF) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error parsing dictionary: " + name + " (from line " + itos(dictline) + ")"); + ERR_FAIL_COND_V(err && err != ERR_FILE_EOF, err); } //ERR_FAIL_COND_V(tagname!="key",ERR_FILE_CORRUPT); if (err) break; Variant value; - err=parse_property(value,tagname,p_for_export_data); + err = parse_property(value, tagname, p_for_export_data); if (err) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error parsing dictionary: "+name+" (from line "+itos(dictline)+")"); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error parsing dictionary: " + name + " (from line " + itos(dictline) + ")"); } - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); //ERR_FAIL_COND_V(tagname!="value",ERR_FILE_CORRUPT); - d[key]=value; + d[key] = value; } - //err=parse_property_data(name); // skip the rest //ERR_FAIL_COND_V(err,err); - r_name=name; - r_v=d; + r_name = name; + r_v = d; return OK; - } else if (type=="array") { + } else if (type == "array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - - int len=tag->args["len"].to_int(); - bool shared = tag->args.has("shared") && (String(tag->args["shared"])=="true" || String(tag->args["shared"])=="1"); + int len = tag->args["len"].to_int(); + bool shared = tag->args.has("shared") && (String(tag->args["shared"]) == "true" || String(tag->args["shared"]) == "1"); Array array(shared); array.resize(len); @@ -428,230 +415,220 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Error err; Variant v; String tagname; - int idx=0; - while( (err=parse_property(v,tagname,p_for_export_data))==OK ) { + int idx = 0; + while ((err = parse_property(v, tagname, p_for_export_data)) == OK) { - ERR_CONTINUE( idx <0 || idx >=len ); + ERR_CONTINUE(idx < 0 || idx >= len); - array.set(idx,v); + array.set(idx, v); idx++; } - if (idx!=len) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array (size mismatch): "+name); - ERR_FAIL_COND_V(idx!=len,err); + if (idx != len) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array (size mismatch): " + name); + ERR_FAIL_COND_V(idx != len, err); } - if (err!=ERR_FILE_EOF) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array: "+name); - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,err); + if (err != ERR_FILE_EOF) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array: " + name); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, err); } //err=parse_property_data(name); // skip the rest //ERR_FAIL_COND_V(err,err); - r_name=name; - r_v=array; + r_name = name; + r_v = array; return OK; - } else if (type=="resource") { + } else if (type == "resource") { if (tag->args.has("path")) { - String path=tag->args["path"]; + String path = tag->args["path"]; String hint; if (tag->args.has("resource_type")) - hint=tag->args["resource_type"]; + hint = tag->args["resource_type"]; if (p_for_export_data) { String prop; if (path.begins_with("local://")) { - prop="@RESLOCAL:"+itos(path.replace("local://","").to_int()); + prop = "@RESLOCAL:" + itos(path.replace("local://", "").to_int()); } - r_v=prop; + r_v = prop; return OK; } if (path.begins_with("local://")) - path=path.replace("local://",local_path+"::"); - else if (path.find("://")==-1 && path.is_rel_path()) { + path = path.replace("local://", local_path + "::"); + else if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); - + path = Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } //take advantage of the resource loader cache. The resource is cached on it, even if - RES res=ResourceLoader::load(path,hint); - + RES res = ResourceLoader::load(path, hint); if (res.is_null()) { - WARN_PRINT(String("Couldn't load resource: "+path).ascii().get_data()); + WARN_PRINT(String("Couldn't load resource: " + path).ascii().get_data()); } - r_v=res.get_ref_ptr(); + r_v = res.get_ref_ptr(); } else if (tag->args.has("external")) { int index = tag->args["external"].to_int(); - if (p_for_export_data) { String prop; - prop="@RESEXTERNAL:"+itos(index); + prop = "@RESEXTERNAL:" + itos(index); - r_v=prop; + r_v = prop; return OK; } if (ext_resources.has(index)) { - String path=ext_resources[index].path; - String type=ext_resources[index].type; + String path = ext_resources[index].path; + String type = ext_resources[index].type; //take advantage of the resource loader cache. The resource is cached on it, even if - RES res=ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { - WARN_PRINT(String("Couldn't load externalresource: "+path).ascii().get_data()); + WARN_PRINT(String("Couldn't load externalresource: " + path).ascii().get_data()); } - r_v=res.get_ref_ptr(); + r_v = res.get_ref_ptr(); } else { - WARN_PRINT(String("Invalid external resource index: "+itos(index)).ascii().get_data()); - + WARN_PRINT(String("Invalid external resource index: " + itos(index)).ascii().get_data()); } } - - - - Error err=goto_end_of_tag(); + Error err = goto_end_of_tag(); if (err) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error closing <resource> tag."); - ERR_FAIL_COND_V(err,err); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error closing <resource> tag."); + ERR_FAIL_COND_V(err, err); } - - r_name=name; + r_name = name; return OK; - } else if (type=="image") { + } else if (type == "image") { if (!tag->args.has("encoding")) { //empty image - r_v=Image(); + r_v = Image(); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); + Error err = parse_property_data(sdfsdfg); return OK; } - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'encoding' field."); - ERR_FAIL_COND_V( !tag->args.has("encoding"), ERR_FILE_CORRUPT ); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'width' field."); - ERR_FAIL_COND_V( !tag->args.has("width"), ERR_FILE_CORRUPT ); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'height' field."); - ERR_FAIL_COND_V( !tag->args.has("height"), ERR_FILE_CORRUPT ); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Image missing 'format' field."); - ERR_FAIL_COND_V( !tag->args.has("format"), ERR_FILE_CORRUPT ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'encoding' field."); + ERR_FAIL_COND_V(!tag->args.has("encoding"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'width' field."); + ERR_FAIL_COND_V(!tag->args.has("width"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'height' field."); + ERR_FAIL_COND_V(!tag->args.has("height"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Image missing 'format' field."); + ERR_FAIL_COND_V(!tag->args.has("format"), ERR_FILE_CORRUPT); - String encoding=tag->args["encoding"]; + String encoding = tag->args["encoding"]; - if (encoding=="raw") { - String width=tag->args["width"]; - String height=tag->args["height"]; - String format=tag->args["format"]; - int mipmaps=tag->args.has("mipmaps")?int(tag->args["mipmaps"].to_int()):int(0); - int custom_size = tag->args.has("custom_size")?int(tag->args["custom_size"].to_int()):int(0); + if (encoding == "raw") { + String width = tag->args["width"]; + String height = tag->args["height"]; + String format = tag->args["format"]; + int mipmaps = tag->args.has("mipmaps") ? int(tag->args["mipmaps"].to_int()) : int(0); + int custom_size = tag->args.has("custom_size") ? int(tag->args["custom_size"].to_int()) : int(0); - r_name=name; + r_name = name; Image::Format imgformat; - - if (format=="grayscale") { - imgformat=Image::FORMAT_GRAYSCALE; - } else if (format=="intensity") { - imgformat=Image::FORMAT_INTENSITY; - } else if (format=="grayscale_alpha") { - imgformat=Image::FORMAT_GRAYSCALE_ALPHA; - } else if (format=="rgb") { - imgformat=Image::FORMAT_RGB; - } else if (format=="rgba") { - imgformat=Image::FORMAT_RGBA; - } else if (format=="indexed") { - imgformat=Image::FORMAT_INDEXED; - } else if (format=="indexed_alpha") { - imgformat=Image::FORMAT_INDEXED_ALPHA; - } else if (format=="bc1") { - imgformat=Image::FORMAT_BC1; - } else if (format=="bc2") { - imgformat=Image::FORMAT_BC2; - } else if (format=="bc3") { - imgformat=Image::FORMAT_BC3; - } else if (format=="bc4") { - imgformat=Image::FORMAT_BC4; - } else if (format=="bc5") { - imgformat=Image::FORMAT_BC5; - } else if (format=="pvrtc2") { - imgformat=Image::FORMAT_PVRTC2; - } else if (format=="pvrtc2a") { - imgformat=Image::FORMAT_PVRTC2_ALPHA; - } else if (format=="pvrtc4") { - imgformat=Image::FORMAT_PVRTC4; - } else if (format=="pvrtc4a") { - imgformat=Image::FORMAT_PVRTC4_ALPHA; - } else if (format=="etc") { - imgformat=Image::FORMAT_ETC; - } else if (format=="atc") { - imgformat=Image::FORMAT_ATC; - } else if (format=="atcai") { - imgformat=Image::FORMAT_ATC_ALPHA_INTERPOLATED; - } else if (format=="atcae") { - imgformat=Image::FORMAT_ATC_ALPHA_EXPLICIT; - } else if (format=="custom") { - imgformat=Image::FORMAT_CUSTOM; + if (format == "grayscale") { + imgformat = Image::FORMAT_GRAYSCALE; + } else if (format == "intensity") { + imgformat = Image::FORMAT_INTENSITY; + } else if (format == "grayscale_alpha") { + imgformat = Image::FORMAT_GRAYSCALE_ALPHA; + } else if (format == "rgb") { + imgformat = Image::FORMAT_RGB; + } else if (format == "rgba") { + imgformat = Image::FORMAT_RGBA; + } else if (format == "indexed") { + imgformat = Image::FORMAT_INDEXED; + } else if (format == "indexed_alpha") { + imgformat = Image::FORMAT_INDEXED_ALPHA; + } else if (format == "bc1") { + imgformat = Image::FORMAT_BC1; + } else if (format == "bc2") { + imgformat = Image::FORMAT_BC2; + } else if (format == "bc3") { + imgformat = Image::FORMAT_BC3; + } else if (format == "bc4") { + imgformat = Image::FORMAT_BC4; + } else if (format == "bc5") { + imgformat = Image::FORMAT_BC5; + } else if (format == "pvrtc2") { + imgformat = Image::FORMAT_PVRTC2; + } else if (format == "pvrtc2a") { + imgformat = Image::FORMAT_PVRTC2_ALPHA; + } else if (format == "pvrtc4") { + imgformat = Image::FORMAT_PVRTC4; + } else if (format == "pvrtc4a") { + imgformat = Image::FORMAT_PVRTC4_ALPHA; + } else if (format == "etc") { + imgformat = Image::FORMAT_ETC; + } else if (format == "atc") { + imgformat = Image::FORMAT_ATC; + } else if (format == "atcai") { + imgformat = Image::FORMAT_ATC_ALPHA_INTERPOLATED; + } else if (format == "atcae") { + imgformat = Image::FORMAT_ATC_ALPHA_EXPLICIT; + } else if (format == "custom") { + imgformat = Image::FORMAT_CUSTOM; } else { - ERR_FAIL_V( ERR_FILE_CORRUPT ); + ERR_FAIL_V(ERR_FILE_CORRUPT); } - int datasize; - int w=width.to_int(); - int h=height.to_int(); + int w = width.to_int(); + int h = height.to_int(); if (w == 0 && h == 0) { //r_v = Image(w, h, imgformat); - r_v=Image(); + r_v = Image(); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); + Error err = parse_property_data(sdfsdfg); return OK; }; - if (imgformat==Image::FORMAT_CUSTOM) { + if (imgformat == Image::FORMAT_CUSTOM) { - datasize=custom_size; + datasize = custom_size; } else { - datasize = Image::get_image_data_size(h,w,imgformat,mipmaps); + datasize = Image::get_image_data_size(h, w, imgformat, mipmaps); } - if (datasize==0) { + if (datasize == 0) { //r_v = Image(w, h, imgformat); - r_v=Image(); + r_v = Image(); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); + Error err = parse_property_data(sdfsdfg); return OK; }; @@ -659,101 +636,100 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, pixels.resize(datasize); DVector<uint8_t>::Write wb = pixels.write(); - int idx=0; + int idx = 0; uint8_t byte; - while( idx<datasize*2) { + while (idx < datasize * 2) { - CharType c=get_char(); + CharType c = get_char(); - ERR_FAIL_COND_V(c=='<',ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(c == '<', ERR_FILE_CORRUPT); - if ( (c>='0' && c<='9') || (c>='A' && c<='F') || (c>='a' && c<='f') ) { + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { - if (idx&1) { + if (idx & 1) { - byte|=HEX2CHR(c); - wb[idx>>1]=byte; + byte |= HEX2CHR(c); + wb[idx >> 1] = byte; } else { - byte=HEX2CHR(c)<<4; + byte = HEX2CHR(c) << 4; } idx++; } - } - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); - wb=DVector<uint8_t>::Write(); + wb = DVector<uint8_t>::Write(); - r_v=Image(w,h,mipmaps,imgformat,pixels); + r_v = Image(w, h, mipmaps, imgformat, pixels); String sdfsdfg; - Error err=parse_property_data(sdfsdfg); - ERR_FAIL_COND_V(err,err); + Error err = parse_property_data(sdfsdfg); + ERR_FAIL_COND_V(err, err); return OK; } ERR_FAIL_V(ERR_FILE_CORRUPT); - } else if (type=="raw_array") { + } else if (type == "raw_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": RawArray missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": RawArray missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int(); + int len = tag->args["len"].to_int(); DVector<uint8_t> bytes; bytes.resize(len); - DVector<uint8_t>::Write w=bytes.write(); - uint8_t *bytesptr=w.ptr(); - int idx=0; + DVector<uint8_t>::Write w = bytes.write(); + uint8_t *bytesptr = w.ptr(); + int idx = 0; uint8_t byte; - while( idx<len*2) { + while (idx < len * 2) { - CharType c=get_char(); - if (c<=32) + CharType c = get_char(); + if (c <= 32) continue; - if (idx&1) { + if (idx & 1) { - byte|=HEX2CHR(c); - bytesptr[idx>>1]=byte; + byte |= HEX2CHR(c); + bytesptr[idx >> 1] = byte; //printf("%x\n",int(byte)); } else { - byte=HEX2CHR(c)<<4; + byte = HEX2CHR(c) << 4; } idx++; } - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); - w=DVector<uint8_t>::Write(); - r_v=bytes; + w = DVector<uint8_t>::Write(); + r_v = bytes; String sdfsdfg; - Error err=parse_property_data(sdfsdfg); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = parse_property_data(sdfsdfg); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="int_array") { + } else if (type == "int_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int(); + int len = tag->args["len"].to_int(); DVector<int> ints; ints.resize(len); - DVector<int>::Write w=ints.write(); - int *intsptr=w.ptr(); - int idx=0; + DVector<int>::Write w = ints.write(); + int *intsptr = w.ptr(); + int idx = 0; String str; #if 0 while( idx<len ) { @@ -788,44 +764,43 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Vector<char> tmpdata; - while( idx<len ) { + while (idx < len) { - bool end=false; - Error err = _parse_array_element(tmpdata,true,f,&end); - ERR_FAIL_COND_V(err,err); + bool end = false; + Error err = _parse_array_element(tmpdata, true, f, &end); + ERR_FAIL_COND_V(err, err); - intsptr[idx]=String::to_int(&tmpdata[0]); + intsptr[idx] = String::to_int(&tmpdata[0]); idx++; if (end) break; - } #endif - w=DVector<int>::Write(); + w = DVector<int>::Write(); - r_v=ints; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + r_v = ints; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="real_array") { + } else if (type == "real_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector<real_t> reals; reals.resize(len); - DVector<real_t>::Write w=reals.write(); - real_t *realsptr=w.ptr(); - int idx=0; + DVector<real_t>::Write w = reals.write(); + real_t *realsptr = w.ptr(); + int idx = 0; String str; - #if 0 while( idx<len ) { @@ -858,17 +833,15 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, #else - - Vector<char> tmpdata; - while( idx<len ) { + while (idx < len) { - bool end=false; - Error err = _parse_array_element(tmpdata,true,f,&end); - ERR_FAIL_COND_V(err,err); + bool end = false; + Error err = _parse_array_element(tmpdata, true, f, &end); + ERR_FAIL_COND_V(err, err); - realsptr[idx]=String::to_double(&tmpdata[0]); + realsptr[idx] = String::to_double(&tmpdata[0]); idx++; if (end) @@ -877,15 +850,15 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, #endif - w=DVector<real_t>::Write(); - r_v=reals; + w = DVector<real_t>::Write(); + r_v = reals; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="string_array") { + } else if (type == "string_array") { #if 0 if (!tag->args.has("len")) { ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); @@ -946,12 +919,11 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, return OK; #endif if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": String Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": String Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - - int len=tag->args["len"].to_int(); + int len = tag->args["len"].to_int(); StringArray array; array.resize(len); @@ -960,48 +932,48 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Error err; Variant v; String tagname; - int idx=0; + int idx = 0; + while ((err = parse_property(v, tagname)) == OK) { - while( (err=parse_property(v,tagname))==OK ) { - - ERR_CONTINUE( idx <0 || idx >=len ); + ERR_CONTINUE(idx < 0 || idx >= len); String str = v; //convert back to string - w[idx]=str; + w[idx] = str; idx++; } - if (idx!=len) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array (size mismatch): "+name); - ERR_FAIL_COND_V(idx!=len,err); + if (idx != len) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array (size mismatch): " + name); + ERR_FAIL_COND_V(idx != len, err); } - if (err!=ERR_FILE_EOF) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Error loading array: "+name); - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,err); + if (err != ERR_FILE_EOF) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Error loading array: " + name); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, err); } //err=parse_property_data(name); // skip the rest //ERR_FAIL_COND_V(err,err); - r_name=name; - r_v=array; + r_name = name; + r_v = array; return OK; - } else if (type=="vector3_array") { + } else if (type == "vector3_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector<Vector3> vectors; vectors.resize(len); - DVector<Vector3>::Write w=vectors.write(); - Vector3 *vectorsptr=w.ptr(); - int idx=0; - int subidx=0; + DVector<Vector3>::Write w = vectors.write(); + Vector3 *vectorsptr = w.ptr(); + int idx = 0; + int subidx = 0; Vector3 auxvec; String str; @@ -1045,57 +1017,54 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Vector<char> tmpdata; - while( idx<len ) { - - bool end=false; - Error err = _parse_array_element(tmpdata,true,f,&end); - ERR_FAIL_COND_V(err,err); + while (idx < len) { + bool end = false; + Error err = _parse_array_element(tmpdata, true, f, &end); + ERR_FAIL_COND_V(err, err); - auxvec[subidx]=String::to_double(&tmpdata[0]); + auxvec[subidx] = String::to_double(&tmpdata[0]); subidx++; - if (subidx==3) { - vectorsptr[idx]=auxvec; + if (subidx == 3) { + vectorsptr[idx] = auxvec; idx++; - subidx=0; + subidx = 0; } if (end) break; } - - #endif - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Premature end of vector3 array"); - ERR_FAIL_COND_V(idx<len,ERR_FILE_CORRUPT); -// double time_taken = (OS::get_singleton()->get_ticks_usec() - tbegin)/1000000.0; - + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Premature end of vector3 array"); + ERR_FAIL_COND_V(idx < len, ERR_FILE_CORRUPT); + // double time_taken = (OS::get_singleton()->get_ticks_usec() - tbegin)/1000000.0; - w=DVector<Vector3>::Write(); - r_v=vectors; + w = DVector<Vector3>::Write(); + r_v = vectors; String sdfsdfg; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="vector2_array") { + } else if (type == "vector2_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector<Vector2> vectors; vectors.resize(len); - DVector<Vector2>::Write w=vectors.write(); - Vector2 *vectorsptr=w.ptr(); - int idx=0; - int subidx=0; + DVector<Vector2>::Write w = vectors.write(); + Vector2 *vectorsptr = w.ptr(); + int idx = 0; + int subidx = 0; Vector2 auxvec; String str; @@ -1139,278 +1108,250 @@ Error ResourceInteractiveLoaderXML::parse_property(Variant& r_v, String &r_name, Vector<char> tmpdata; - while( idx<len ) { - - bool end=false; - Error err = _parse_array_element(tmpdata,true,f,&end); - ERR_FAIL_COND_V(err,err); + while (idx < len) { + bool end = false; + Error err = _parse_array_element(tmpdata, true, f, &end); + ERR_FAIL_COND_V(err, err); - auxvec[subidx]=String::to_double(&tmpdata[0]); + auxvec[subidx] = String::to_double(&tmpdata[0]); subidx++; - if (subidx==2) { - vectorsptr[idx]=auxvec; + if (subidx == 2) { + vectorsptr[idx] = auxvec; idx++; - subidx=0; + subidx = 0; } if (end) break; } - - #endif - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Premature end of vector2 array"); - ERR_FAIL_COND_V(idx<len,ERR_FILE_CORRUPT); -// double time_taken = (OS::get_singleton()->get_ticks_usec() - tbegin)/1000000.0; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Premature end of vector2 array"); + ERR_FAIL_COND_V(idx < len, ERR_FILE_CORRUPT); + // double time_taken = (OS::get_singleton()->get_ticks_usec() - tbegin)/1000000.0; - - w=DVector<Vector2>::Write(); - r_v=vectors; + w = DVector<Vector2>::Write(); + r_v = vectors; String sdfsdfg; - Error err=goto_end_of_tag(); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = goto_end_of_tag(); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; - } else if (type=="color_array") { + } else if (type == "color_array") { if (!tag->args.has("len")) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Array missing 'len' field: "+name); - ERR_FAIL_COND_V(!tag->args.has("len"),ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Array missing 'len' field: " + name); + ERR_FAIL_COND_V(!tag->args.has("len"), ERR_FILE_CORRUPT); } - int len=tag->args["len"].to_int();; + int len = tag->args["len"].to_int(); + ; DVector<Color> colors; colors.resize(len); - DVector<Color>::Write w=colors.write(); - Color *colorsptr=w.ptr(); - int idx=0; - int subidx=0; + DVector<Color>::Write w = colors.write(); + Color *colorsptr = w.ptr(); + int idx = 0; + int subidx = 0; Color auxcol; String str; - while( idx<len ) { - + while (idx < len) { - CharType c=get_char(); - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + CharType c = get_char(); + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); - - if (c<33 || c==',' || c=='<') { + if (c < 33 || c == ',' || c == '<') { if (str.length()) { - auxcol[subidx]=str.to_double(); + auxcol[subidx] = str.to_double(); subidx++; - str=""; - if (subidx==4) { - colorsptr[idx]=auxcol; + str = ""; + if (subidx == 4) { + colorsptr[idx] = auxcol; idx++; - subidx=0; + subidx = 0; } } - if (c=='<') { + if (c == '<') { - while(get_char()!='>' && !f->eof_reached()) {} - ERR_FAIL_COND_V(f->eof_reached(),ERR_FILE_CORRUPT); + while (get_char() != '>' && !f->eof_reached()) { + } + ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_CORRUPT); break; } } else { - str+=c; + str += c; } } - w=DVector<Color>::Write(); - r_v=colors; + w = DVector<Color>::Write(); + r_v = colors; String sdfsdfg; - Error err=parse_property_data(sdfsdfg); - ERR_FAIL_COND_V(err,err); - r_name=name; + Error err = parse_property_data(sdfsdfg); + ERR_FAIL_COND_V(err, err); + r_name = name; return OK; } - String data; Error err = parse_property_data(data); - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); - if (type=="nil") { + if (type == "nil") { // uh do nothing - } else if (type=="bool") { + } else if (type == "bool") { // uh do nothing - if (data.nocasecmp_to("true")==0 || data.to_int()!=0) - r_v=true; + if (data.nocasecmp_to("true") == 0 || data.to_int() != 0) + r_v = true; else - r_v=false; - } else if (type=="int") { + r_v = false; + } else if (type == "int") { - r_v=data.to_int(); - } else if (type=="real") { + r_v = data.to_int(); + } else if (type == "real") { - r_v=data.to_double(); - } else if (type=="string") { + r_v = data.to_double(); + } else if (type == "string") { - String str=data; + String str = data; unquote(str); - r_v=str; - } else if (type=="vector3") { - - - r_v=Vector3( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double() - ); + r_v = str; + } else if (type == "vector3") { - } else if (type=="vector2") { + r_v = Vector3( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double()); + } else if (type == "vector2") { - r_v=Vector2( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double() - ); + r_v = Vector2( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double()); - } else if (type=="plane") { + } else if (type == "plane") { - r_v=Plane( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ); + r_v = Plane( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double()); - } else if (type=="quaternion") { + } else if (type == "quaternion") { - r_v=Quat( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ); + r_v = Quat( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double()); - } else if (type=="rect2") { + } else if (type == "rect2") { - r_v=Rect2( - Vector2( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double() - ), - Vector2( - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ) - ); + r_v = Rect2( + Vector2( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double()), + Vector2( + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double())); + } else if (type == "aabb") { - } else if (type=="aabb") { + r_v = AABB( + Vector3( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double()), + Vector3( + data.get_slicec(',', 3).to_double(), + data.get_slicec(',', 4).to_double(), + data.get_slicec(',', 5).to_double())); - r_v=AABB( - Vector3( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double() - ), - Vector3( - data.get_slicec(',',3).to_double(), - data.get_slicec(',',4).to_double(), - data.get_slicec(',',5).to_double() - ) - ); - - } else if (type=="matrix32") { + } else if (type == "matrix32") { Matrix32 m3; - for (int i=0;i<3;i++) { - for (int j=0;j<2;j++) { - m3.elements[i][j]=data.get_slicec(',',i*2+j).to_double(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + m3.elements[i][j] = data.get_slicec(',', i * 2 + j).to_double(); } } - r_v=m3; + r_v = m3; - } else if (type=="matrix3") { + } else if (type == "matrix3") { Matrix3 m3; - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { - m3.elements[i][j]=data.get_slicec(',',i*3+j).to_double(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + m3.elements[i][j] = data.get_slicec(',', i * 3 + j).to_double(); } } - r_v=m3; + r_v = m3; - } else if (type=="transform") { + } else if (type == "transform") { Transform tr; - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { - tr.basis.elements[i][j]=data.get_slicec(',',i*3+j).to_double(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + tr.basis.elements[i][j] = data.get_slicec(',', i * 3 + j).to_double(); } - } - tr.origin=Vector3( - data.get_slicec(',',9).to_double(), - data.get_slicec(',',10).to_double(), - data.get_slicec(',',11).to_double() - ); - r_v=tr; + tr.origin = Vector3( + data.get_slicec(',', 9).to_double(), + data.get_slicec(',', 10).to_double(), + data.get_slicec(',', 11).to_double()); + r_v = tr; - } else if (type=="color") { + } else if (type == "color") { - r_v=Color( - data.get_slicec(',',0).to_double(), - data.get_slicec(',',1).to_double(), - data.get_slicec(',',2).to_double(), - data.get_slicec(',',3).to_double() - ); + r_v = Color( + data.get_slicec(',', 0).to_double(), + data.get_slicec(',', 1).to_double(), + data.get_slicec(',', 2).to_double(), + data.get_slicec(',', 3).to_double()); - } else if (type=="node_path") { + } else if (type == "node_path") { - String str=data; + String str = data; unquote(str); - r_v=NodePath( str ); - } else if (type=="input_event") { + r_v = NodePath(str); + } else if (type == "input_event") { // ? } else { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Unrecognized tag in file: "+type); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Unrecognized tag in file: " + type); ERR_FAIL_V(ERR_FILE_CORRUPT); } - r_name=name; + r_name = name; return OK; } - - int ResourceInteractiveLoaderXML::get_current_line() const { return lines; } - uint8_t ResourceInteractiveLoaderXML::get_char() const { uint8_t c = f->get_8(); - if (c=='\n') + if (c == '\n') lines++; return c; - } - - - /// -void ResourceInteractiveLoaderXML::set_local_path(const String& p_local_path) { +void ResourceInteractiveLoaderXML::set_local_path(const String &p_local_path) { - res_path=p_local_path; + res_path = p_local_path; } Ref<Resource> ResourceInteractiveLoaderXML::get_resource() { @@ -1419,18 +1360,17 @@ Ref<Resource> ResourceInteractiveLoaderXML::get_resource() { } Error ResourceInteractiveLoaderXML::poll() { - if (error!=OK) + if (error != OK) return error; bool exit; Tag *tag = parse_tag(&exit); - if (!tag) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; if (!exit) // shouldn't have exited ERR_FAIL_V(error); - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; } @@ -1439,40 +1379,39 @@ Error ResourceInteractiveLoaderXML::poll() { bool main; - if (tag->name=="ext_resource") { + if (tag->name == "ext_resource") { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <ext_resource> missing 'path' field."); - ERR_FAIL_COND_V(!tag->args.has("path"),ERR_FILE_CORRUPT); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <ext_resource> missing 'path' field."); + ERR_FAIL_COND_V(!tag->args.has("path"), ERR_FILE_CORRUPT); - String type="Resource"; + String type = "Resource"; if (tag->args.has("type")) - type=tag->args["type"]; + type = tag->args["type"]; String path = tag->args["path"]; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <ext_resource> can't use a local path, this is a bug?."); + ERR_FAIL_COND_V(path.begins_with("local://"), ERR_FILE_CORRUPT); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <ext_resource> can't use a local path, this is a bug?."); - ERR_FAIL_COND_V(path.begins_with("local://"),ERR_FILE_CORRUPT); - - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); + path = Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } if (remaps.has(path)) { - path=remaps[path]; + path = remaps[path]; } - RES res = ResourceLoader::load(path,type); + RES res = ResourceLoader::load(path, type); if (res.is_null()) { if (ResourceLoader::get_abort_on_missing_resources()) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <ext_resource> referenced nonexistent resource at: "+path); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <ext_resource> referenced nonexistent resource at: " + path); ERR_FAIL_V(error); } else { - ResourceLoader::notify_dependency_error(local_path,path,type); + ResourceLoader::notify_dependency_error(local_path, path, type); } } else { @@ -1481,111 +1420,107 @@ Error ResourceInteractiveLoaderXML::poll() { if (tag->args.has("index")) { ExtResource er; - er.path=path; - er.type=type; - ext_resources[tag->args["index"].to_int()]=er; + er.path = path; + er.type = type; + ext_resources[tag->args["index"].to_int()] = er; } - Error err = close_tag("ext_resource"); if (err) return error; - - error=OK; + error = OK; resource_current++; return error; - } else if (tag->name=="resource") { + } else if (tag->name == "resource") { - main=false; - } else if (tag->name=="main_resource") { - main=true; + main = false; + } else if (tag->name == "main_resource") { + main = true; } else { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": unexpected main tag: "+tag->name); - error=ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": unexpected main tag: " + tag->name); + error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } - String type; String path; - int subres=0; + int subres = 0; if (!main) { //loading resource - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <resource> missing 'len' field."); - ERR_FAIL_COND_V(!tag->args.has("path"),ERR_FILE_CORRUPT); - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <resource> missing 'type' field."); - ERR_FAIL_COND_V(!tag->args.has("type"),ERR_FILE_CORRUPT); - path=tag->args["path"]; + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <resource> missing 'len' field."); + ERR_FAIL_COND_V(!tag->args.has("path"), ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <resource> missing 'type' field."); + ERR_FAIL_COND_V(!tag->args.has("type"), ERR_FILE_CORRUPT); + path = tag->args["path"]; - error=OK; + error = OK; if (path.begins_with("local://")) { //built-in resource (but really external) - path=path.replace("local://",""); - subres=path.to_int(); - path=local_path+"::"+path; + path = path.replace("local://", ""); + subres = path.to_int(); + path = local_path + "::" + path; } - if (ResourceCache::has(path)) { Error err = close_tag(tag->name); if (err) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; } - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Unable to close <resource> tag."); - ERR_FAIL_COND_V( err, err ); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Unable to close <resource> tag."); + ERR_FAIL_COND_V(err, err); resource_current++; - error=OK; + error = OK; return OK; } type = tag->args["type"]; } else { - type=resource_type; + type = resource_type; } Object *obj = ObjectTypeDB::instance(type); if (!obj) { - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Object of unrecognized type in file: "+type); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Object of unrecognized type in file: " + type); } - ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!obj, ERR_FILE_CORRUPT); Resource *r = obj->cast_to<Resource>(); if (!r) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; memdelete(obj); //bye - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": Object type in resource field not a resource, type is: "+obj->get_type()); - ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": Object type in resource field not a resource, type is: " + obj->get_type()); + ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT); } - res = RES( r ); - if (path!="") + res = RES(r); + if (path != "") r->set_path(path); r->set_subindex(subres); //load properties - while(true) { + while (true) { String name; Variant v; Error err; - err = parse_property(v,name); - if (err==ERR_FILE_EOF) //tag closed + err = parse_property(v, name); + if (err == ERR_FILE_EOF) //tag closed break; - if (err!=OK) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": XML Parsing aborted."); - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CORRUPT); + if (err != OK) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": XML Parsing aborted."); + ERR_FAIL_COND_V(err != OK, ERR_FILE_CORRUPT); } - obj->set(name,v); + obj->set(name, v); } #ifdef TOOLS_ENABLED res->set_edited(false); @@ -1594,15 +1529,14 @@ Error ResourceInteractiveLoaderXML::poll() { resource_current++; if (main) { f->close(); - resource=res; + resource = res; if (!ResourceCache::has(res_path)) { resource->set_path(res_path); } - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; - } - error=OK; + error = OK; return OK; } @@ -1612,7 +1546,7 @@ int ResourceInteractiveLoaderXML::get_stage() const { } int ResourceInteractiveLoaderXML::get_stage_count() const { - return resources_total;//+ext_resources; + return resources_total; //+ext_resources; } ResourceInteractiveLoaderXML::~ResourceInteractiveLoaderXML() { @@ -1620,51 +1554,49 @@ ResourceInteractiveLoaderXML::~ResourceInteractiveLoaderXML() { memdelete(f); } -void ResourceInteractiveLoaderXML::get_dependencies(FileAccess *f,List<String> *p_dependencies,bool p_add_types) { - +void ResourceInteractiveLoaderXML::get_dependencies(FileAccess *f, List<String> *p_dependencies, bool p_add_types) { open(f); - ERR_FAIL_COND(error!=OK); + ERR_FAIL_COND(error != OK); - while(true) { + while (true) { bool exit; Tag *tag = parse_tag(&exit); - if (!tag) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; ERR_FAIL_COND(!exit); - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return; } - if (tag->name!="ext_resource") { + if (tag->name != "ext_resource") { return; } - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <ext_resource> missing 'path' field."); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <ext_resource> missing 'path' field."); ERR_FAIL_COND(!tag->args.has("path")); String path = tag->args["path"]; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <ext_resource> can't use a local path, this is a bug?."); + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <ext_resource> can't use a local path, this is a bug?."); ERR_FAIL_COND(path.begins_with("local://")); - if (path.find("://")==-1 && path.is_rel_path()) { + if (path.find("://") == -1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path - path=Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); + path = Globals::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } if (path.ends_with("*")) { ERR_FAIL_COND(!tag->args.has("type")); String type = tag->args["type"]; - path = ResourceLoader::guess_full_filename(path,type); + path = ResourceLoader::guess_full_filename(path, type); } if (p_add_types && tag->args.has("type")) { - path+="::"+tag->args["type"]; + path += "::" + tag->args["type"]; } p_dependencies->push_back(path); @@ -1673,275 +1605,254 @@ void ResourceInteractiveLoaderXML::get_dependencies(FileAccess *f,List<String> * if (err) return; - error=OK; + error = OK; } - } -Error ResourceInteractiveLoaderXML::get_export_data(FileAccess *p_f,ExportData& r_export_data) { +Error ResourceInteractiveLoaderXML::get_export_data(FileAccess *p_f, ExportData &r_export_data) { open(p_f); - ERR_FAIL_COND_V(error!=OK,error); - - + ERR_FAIL_COND_V(error != OK, error); while (true) { bool exit; Tag *tag = parse_tag(&exit); if (!tag) { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; if (!exit) // shouldn't have exited ERR_FAIL_V(error); - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; } - bool main; - if (tag->name=="ext_resource") { + if (tag->name == "ext_resource") { ExportData::Dependency dep; - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": <ext_resource> missing 'path' field."); - ERR_FAIL_COND_V(!tag->args.has("path"),ERR_FILE_CORRUPT); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": <ext_resource> missing 'path' field."); + ERR_FAIL_COND_V(!tag->args.has("path"), ERR_FILE_CORRUPT); - String type="Resource"; + String type = "Resource"; if (tag->args.has("type")) - type=tag->args["type"]; + type = tag->args["type"]; String path = tag->args["path"]; - dep.path=path; - dep.type=type; - + dep.path = path; + dep.type = type; if (tag->args.has("index")) { ExtResource er; - er.path=path; - er.type=type; - r_export_data.dependencies[tag->args["index"].to_int()]=dep; + er.path = path; + er.type = type; + r_export_data.dependencies[tag->args["index"].to_int()] = dep; } else { int index = r_export_data.dependencies.size(); - r_export_data.dependencies[index]=dep; - + r_export_data.dependencies[index] = dep; } - - Error err = close_tag("ext_resource"); if (err) return error; continue; - } else if (tag->name=="resource") { + } else if (tag->name == "resource") { - main=false; - } else if (tag->name=="main_resource") { - main=true; + main = false; + } else if (tag->name == "main_resource") { + main = true; } else { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": unexpected main tag: "+tag->name); - error=ERR_FILE_CORRUPT; + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": unexpected main tag: " + tag->name); + error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } - r_export_data.resources.resize( r_export_data.resources.size()+1 ); - - ExportData::ResourceData &res_data=r_export_data.resources[ r_export_data.resources.size()-1 ]; + r_export_data.resources.resize(r_export_data.resources.size() + 1); + ExportData::ResourceData &res_data = r_export_data.resources[r_export_data.resources.size() - 1]; - res_data.index=-1; + res_data.index = -1; if (!main) { //loading resource + String path = tag->args["path"]; - String path=tag->args["path"]; - - error=OK; + error = OK; if (path.begins_with("local://")) { //built-in resource (but really external) - path=path.replace("local://",""); - res_data.index=path.to_int(); + path = path.replace("local://", ""); + res_data.index = path.to_int(); } - res_data.type= tag->args["type"]; + res_data.type = tag->args["type"]; } else { - res_data.type=resource_type; - - + res_data.type = resource_type; } //load properties - while(true) { + while (true) { String name; Variant v; Error err; - err = parse_property(v,name); + err = parse_property(v, name); - if (err==ERR_FILE_EOF) //tag closed + if (err == ERR_FILE_EOF) //tag closed break; - - if (err!=OK) { - ERR_EXPLAIN(local_path+":"+itos(get_current_line())+": XML Parsing aborted."); - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CORRUPT); + if (err != OK) { + ERR_EXPLAIN(local_path + ":" + itos(get_current_line()) + ": XML Parsing aborted."); + ERR_FAIL_COND_V(err != OK, ERR_FILE_CORRUPT); } ExportData::PropertyData prop; - prop.name=name; - prop.value=v; + prop.name = name; + prop.value = v; res_data.properties.push_back(prop); - } if (main) { return OK; - } } return OK; } - -Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const String &p_path,const Map<String,String>& p_map) { +Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) { open(p_f); - ERR_FAIL_COND_V(error!=OK,error); + ERR_FAIL_COND_V(error != OK, error); //FileAccess - bool old_format=false; + bool old_format = false; FileAccess *fw = NULL; - String base_path=local_path.get_base_dir(); + String base_path = local_path.get_base_dir(); - while(true) { + while (true) { bool exit; List<String> order; - Tag *tag = parse_tag(&exit,true,&order); + Tag *tag = parse_tag(&exit, true, &order); - bool done=false; + bool done = false; if (!tag) { if (fw) { memdelete(fw); } - error=ERR_FILE_CORRUPT; - ERR_FAIL_COND_V(!exit,error); - error=ERR_FILE_EOF; + error = ERR_FILE_CORRUPT; + ERR_FAIL_COND_V(!exit, error); + error = ERR_FILE_EOF; return error; } - if (tag->name=="ext_resource") { + if (tag->name == "ext_resource") { if (!tag->args.has("index") || !tag->args.has("path") || !tag->args.has("type")) { - old_format=true; + old_format = true; break; } if (!fw) { - fw=FileAccess::open(p_path+".depren",FileAccess::WRITE); + fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); fw->store_line("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); //no escape - fw->store_line("<resource_file type=\""+resource_type+"\" subresource_count=\""+itos(resources_total)+"\" version=\""+itos(VERSION_MAJOR)+"."+itos(VERSION_MINOR)+"\" version_name=\""+VERSION_FULL_NAME+"\">"); - + fw->store_line("<resource_file type=\"" + resource_type + "\" subresource_count=\"" + itos(resources_total) + "\" version=\"" + itos(VERSION_MAJOR) + "." + itos(VERSION_MINOR) + "\" version_name=\"" + VERSION_FULL_NAME + "\">"); } String path = tag->args["path"]; String index = tag->args["index"]; String type = tag->args["type"]; - - bool relative=false; + bool relative = false; if (!path.begins_with("res://")) { - path=base_path.plus_file(path).simplify_path(); - relative=true; + path = base_path.plus_file(path).simplify_path(); + relative = true; } - if (p_map.has(path)) { - String np=p_map[path]; - path=np; + String np = p_map[path]; + path = np; } if (relative) { //restore relative - path=base_path.path_to_file(path); + path = base_path.path_to_file(path); } - tag->args["path"]=path; - tag->args["index"]=index; - tag->args["type"]=type; + tag->args["path"] = path; + tag->args["index"] = index; + tag->args["type"] = type; } else { - done=true; + done = true; } - String tagt="\t<"; + String tagt = "\t<"; if (exit) - tagt+="/"; - tagt+=tag->name; + tagt += "/"; + tagt += tag->name; - for(List<String>::Element *E=order.front();E;E=E->next()) { - tagt+=" "+E->get()+"=\""+tag->args[E->get()]+"\""; + for (List<String>::Element *E = order.front(); E; E = E->next()) { + tagt += " " + E->get() + "=\"" + tag->args[E->get()] + "\""; } - tagt+=">"; + tagt += ">"; fw->store_line(tagt); if (done) break; close_tag("ext_resource"); fw->store_line("\t</ext_resource>"); - } - if (old_format) { if (fw) memdelete(fw); DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - da->remove(p_path+".depren"); + da->remove(p_path + ".depren"); memdelete(da); //fuck it, use the old approach; - WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: "+p_path).utf8().get_data()); + WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path).utf8().get_data()); Error err; - FileAccess *f2 = FileAccess::open(p_path,FileAccess::READ,&err); - if (err!=OK) { - ERR_FAIL_COND_V(err!=OK,ERR_FILE_CANT_OPEN); + FileAccess *f2 = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { + ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN); } - Ref<ResourceInteractiveLoaderXML> ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - ria->remaps=p_map; - // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderXML> ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + ria->remaps = p_map; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f2); err = ria->poll(); - while(err==OK) { - err=ria->poll(); + while (err == OK) { + err = ria->poll(); } - ERR_FAIL_COND_V(err!=ERR_FILE_EOF,ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(err != ERR_FILE_EOF, ERR_FILE_CORRUPT); RES res = ria->get_resource(); - ERR_FAIL_COND_V(!res.is_valid(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(!res.is_valid(), ERR_FILE_CORRUPT); - return ResourceFormatSaverXML::singleton->save(p_path,res); + return ResourceFormatSaverXML::singleton->save(p_path, res); } if (!fw) { @@ -1949,14 +1860,14 @@ Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const S return OK; //nothing to rename, do nothing } - uint8_t c=f->get_8(); - while(!f->eof_reached()) { + uint8_t c = f->get_8(); + while (!f->eof_reached()) { fw->store_8(c); - c=f->get_8(); + c = f->get_8(); } f->close(); - bool all_ok = fw->get_error()==OK; + bool all_ok = fw->get_error() == OK; memdelete(fw); @@ -1966,28 +1877,25 @@ Error ResourceInteractiveLoaderXML::rename_dependencies(FileAccess *p_f, const S DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); - da->rename(p_path+".depren",p_path); + da->rename(p_path + ".depren", p_path); memdelete(da); return OK; - } - void ResourceInteractiveLoaderXML::open(FileAccess *p_f) { - error=OK; - - lines=1; - f=p_f; + error = OK; + lines = 1; + f = p_f; ResourceInteractiveLoaderXML::Tag *tag = parse_tag(); - if (!tag || tag->name!="?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"]!="UTF-8") { + if (!tag || tag->name != "?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"] != "UTF-8") { - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; ResourceLoader::notify_load_error("XML is invalid (missing header tags)"); - ERR_EXPLAIN("Not a XML:UTF-8 File: "+local_path); + ERR_EXPLAIN("Not a XML:UTF-8 File: " + local_path); ERR_FAIL(); } @@ -1995,38 +1903,35 @@ void ResourceInteractiveLoaderXML::open(FileAccess *p_f) { tag = parse_tag(); + if (!tag || tag->name != "resource_file" || !tag->args.has("type") || !tag->args.has("version")) { - if (!tag || tag->name!="resource_file" || !tag->args.has("type") || !tag->args.has("version")) { - - ResourceLoader::notify_load_error(local_path+": XML is not a valid resource file."); - error=ERR_FILE_CORRUPT; - ERR_EXPLAIN("Unrecognized XML File: "+local_path); + ResourceLoader::notify_load_error(local_path + ": XML is not a valid resource file."); + error = ERR_FILE_CORRUPT; + ERR_EXPLAIN("Unrecognized XML File: " + local_path); ERR_FAIL(); } - if (tag->args.has("subresource_count")) - resources_total=tag->args["subresource_count"].to_int(); - resource_current=0; - resource_type=tag->args["type"]; + resources_total = tag->args["subresource_count"].to_int(); + resource_current = 0; + resource_type = tag->args["type"]; String version = tag->args["version"]; - if (version.get_slice_count(".")!=2) { + if (version.get_slice_count(".") != 2) { - error=ERR_FILE_CORRUPT; - ResourceLoader::notify_load_error(local_path+":XML version string is invalid: "+version); - ERR_EXPLAIN("Invalid Version String '"+version+"'' in file: "+local_path); + error = ERR_FILE_CORRUPT; + ResourceLoader::notify_load_error(local_path + ":XML version string is invalid: " + version); + ERR_EXPLAIN("Invalid Version String '" + version + "'' in file: " + local_path); ERR_FAIL(); } - int major = version.get_slicec('.',0).to_int(); - if (major>VERSION_MAJOR) { + int major = version.get_slicec('.', 0).to_int(); + if (major > VERSION_MAJOR) { - error=ERR_FILE_UNRECOGNIZED; - ResourceLoader::notify_load_error(local_path+": File Format '"+version+"' is too new. Please upgrade to a newer engine version."); - ERR_EXPLAIN("File Format '"+version+"' is too new! Please upgrade to a a new engine version: "+local_path); + error = ERR_FILE_UNRECOGNIZED; + ResourceLoader::notify_load_error(local_path + ": File Format '" + version + "' is too new. Please upgrade to a newer engine version."); + ERR_EXPLAIN("File Format '" + version + "' is too new! Please upgrade to a a new engine version: " + local_path); ERR_FAIL(); - } /* @@ -2042,19 +1947,17 @@ void ResourceInteractiveLoaderXML::open(FileAccess *p_f) { print_line(local_path+" - EXTERNAL RESOURCES: "+itos(ext_resources.size())); } */ - } String ResourceInteractiveLoaderXML::recognize(FileAccess *p_f) { - error=OK; + error = OK; - lines=1; - f=p_f; + lines = 1; + f = p_f; ResourceInteractiveLoaderXML::Tag *tag = parse_tag(); - if (!tag || tag->name!="?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"]!="UTF-8") { - + if (!tag || tag->name != "?xml" || !tag->args.has("version") || !tag->args.has("encoding") || tag->args["encoding"] != "UTF-8") { return ""; //unrecognized } @@ -2063,13 +1966,12 @@ String ResourceInteractiveLoaderXML::recognize(FileAccess *p_f) { tag = parse_tag(); - if (!tag || tag->name!="resource_file" || !tag->args.has("type") || !tag->args.has("version")) { + if (!tag || tag->name != "resource_file" || !tag->args.has("type") || !tag->args.has("version")) { return ""; //unrecognized } return tag->args["type"]; - } ///////////////////// @@ -2077,141 +1979,132 @@ String ResourceInteractiveLoaderXML::recognize(FileAccess *p_f) { Ref<ResourceInteractiveLoader> ResourceFormatLoaderXML::load_interactive(const String &p_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; Error err; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err != OK) { - if (err!=OK) { - - ERR_FAIL_COND_V(err!=OK,Ref<ResourceInteractiveLoader>()); + ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>()); } - Ref<ResourceInteractiveLoaderXML> ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderXML> ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); ria->open(f); return ria; } -void ResourceFormatLoaderXML::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { +void ResourceFormatLoaderXML::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="") { + if (p_type == "") { get_recognized_extensions(p_extensions); return; } List<String> extensions; - ObjectTypeDB::get_extensions_for_type(p_type,&extensions); + ObjectTypeDB::get_extensions_for_type(p_type, &extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); - if (ext=="res") + if (ext == "res") continue; - p_extensions->push_back("x"+ext); + p_extensions->push_back("x" + ext); } p_extensions->push_back("xml"); - - } -void ResourceFormatLoaderXML::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatLoaderXML::get_recognized_extensions(List<String> *p_extensions) const { List<String> extensions; ObjectTypeDB::get_resource_base_extensions(&extensions); extensions.sort(); - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { String ext = E->get().to_lower(); - if (ext=="res") + if (ext == "res") continue; - p_extensions->push_back("x"+ext); + p_extensions->push_back("x" + ext); } p_extensions->push_back("xml"); } -bool ResourceFormatLoaderXML::handles_type(const String& p_type) const{ +bool ResourceFormatLoaderXML::handles_type(const String &p_type) const { return true; } -String ResourceFormatLoaderXML::get_resource_type(const String &p_path) const{ +String ResourceFormatLoaderXML::get_resource_type(const String &p_path) const { - - String ext=p_path.extension().to_lower(); + String ext = p_path.extension().to_lower(); if (!ext.begins_with("x")) //a lie but.. return ""; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ""; //could not rwead } - Ref<ResourceInteractiveLoaderXML> ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + Ref<ResourceInteractiveLoaderXML> ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); String r = ria->recognize(f); return r; } +void ResourceFormatLoaderXML::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { -void ResourceFormatLoaderXML::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types) { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { ERR_FAIL(); } - Ref<ResourceInteractiveLoaderXML> ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); - ria->get_dependencies(f,p_dependencies,p_add_types); - - + Ref<ResourceInteractiveLoaderXML> ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + ria->get_dependencies(f, p_dependencies, p_add_types); } -Error ResourceFormatLoaderXML::get_export_data(const String& p_path,ExportData& r_export_data) { +Error ResourceFormatLoaderXML::get_export_data(const String &p_path, ExportData &r_export_data) { - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { ERR_FAIL_V(ERR_CANT_OPEN); } - Ref<ResourceInteractiveLoaderXML> ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; - - return ria->get_export_data(f,r_export_data); + Ref<ResourceInteractiveLoaderXML> ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + return ria->get_export_data(f, r_export_data); } +Error ResourceFormatLoaderXML::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { -Error ResourceFormatLoaderXML::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { ERR_FAIL_V(ERR_CANT_OPEN); } - Ref<ResourceInteractiveLoaderXML> ria = memnew( ResourceInteractiveLoaderXML ); - ria->local_path=Globals::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; -// ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); - return ria->rename_dependencies(f,p_path,p_map); + Ref<ResourceInteractiveLoaderXML> ria = memnew(ResourceInteractiveLoaderXML); + ria->local_path = Globals::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; + // ria->set_local_path( Globals::get_singleton()->localize_path(p_path) ); + return ria->rename_dependencies(f, p_path, p_map); } -ResourceFormatLoaderXML *ResourceFormatLoaderXML::singleton=NULL; +ResourceFormatLoaderXML *ResourceFormatLoaderXML::singleton = NULL; /****************************************************************************************/ /****************************************************************************************/ @@ -2227,41 +2120,38 @@ ResourceFormatLoaderXML *ResourceFormatLoaderXML::singleton=NULL; /****************************************************************************************/ /****************************************************************************************/ +void ResourceFormatSaverXMLInstance::escape(String &p_str) { + p_str = p_str.replace("&", "&"); + p_str = p_str.replace("<", "<"); + p_str = p_str.replace(">", ">"); + p_str = p_str.replace("'", "'"); + p_str = p_str.replace("\"", """); + for (char i = 1; i < 32; i++) { -void ResourceFormatSaverXMLInstance::escape(String& p_str) { - - p_str=p_str.replace("&","&"); - p_str=p_str.replace("<","<"); - p_str=p_str.replace(">",">"); - p_str=p_str.replace("'","'"); - p_str=p_str.replace("\"","""); - for (char i=1;i<32;i++) { - - char chr[2]={i,0}; - const char hexn[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; - const char hex[8]={'&','#','0','0',hexn[i>>4],hexn[i&0xf],';',0}; + char chr[2] = { i, 0 }; + const char hexn[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + const char hex[8] = { '&', '#', '0', '0', hexn[i >> 4], hexn[i & 0xf], ';', 0 }; - p_str=p_str.replace(chr,hex); + p_str = p_str.replace(chr, hex); } - - } void ResourceFormatSaverXMLInstance::write_tabs(int p_diff) { - for (int i=0;i<depth+p_diff;i++) { + for (int i = 0; i < depth + p_diff; i++) { f->store_8('\t'); } } -void ResourceFormatSaverXMLInstance::write_string(String p_str,bool p_escape) { +void ResourceFormatSaverXMLInstance::write_string(String p_str, bool p_escape) { /* write an UTF8 string */ if (p_escape) escape(p_str); - f->store_string(p_str);; + f->store_string(p_str); + ; /* CharString cs=p_str.utf8(); const char *data=cs.get_data(); @@ -2270,42 +2160,38 @@ void ResourceFormatSaverXMLInstance::write_string(String p_str,bool p_escape) { f->store_8(*data); data++; }*/ - - } -void ResourceFormatSaverXMLInstance::enter_tag(const char* p_tag,const String& p_args) { +void ResourceFormatSaverXMLInstance::enter_tag(const char *p_tag, const String &p_args) { f->store_8('<'); int cc = 0; - const char *c=p_tag; - while(*c) { + const char *c = p_tag; + while (*c) { cc++; c++; } - f->store_buffer((const uint8_t*)p_tag,cc); + f->store_buffer((const uint8_t *)p_tag, cc); if (p_args.length()) { f->store_8(' '); f->store_string(p_args); } f->store_8('>'); depth++; - } -void ResourceFormatSaverXMLInstance::exit_tag(const char* p_tag) { +void ResourceFormatSaverXMLInstance::exit_tag(const char *p_tag) { depth--; f->store_8('<'); f->store_8('/'); int cc = 0; - const char *c=p_tag; - while(*c) { + const char *c = p_tag; + while (*c) { cc++; c++; } - f->store_buffer((const uint8_t*)p_tag,cc); + f->store_buffer((const uint8_t *)p_tag, cc); f->store_8('>'); - } /* @@ -2322,142 +2208,170 @@ static bool _check_type(const Variant& p_property) { return true; }*/ -void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const Variant& p_property,bool *r_ok) { +void ResourceFormatSaverXMLInstance::write_property(const String &p_name, const Variant &p_property, bool *r_ok) { if (r_ok) - *r_ok=false; + *r_ok = false; - const char* type; + const char *type; String params; - bool oneliner=true; + bool oneliner = true; - switch( p_property.get_type() ) { + switch (p_property.get_type()) { - case Variant::NIL: type="nil"; break; - case Variant::BOOL: type="bool"; break; - case Variant::INT: type="int"; break; - case Variant::REAL: type="real"; break; - case Variant::STRING: type="string"; break; - case Variant::VECTOR2: type="vector2"; break; - case Variant::RECT2: type="rect2"; break; - case Variant::VECTOR3: type="vector3"; break; - case Variant::PLANE: type="plane"; break; - case Variant::_AABB: type="aabb"; break; - case Variant::QUAT: type="quaternion"; break; - case Variant::MATRIX32: type="matrix32"; break; - case Variant::MATRIX3: type="matrix3"; break; - case Variant::TRANSFORM: type="transform"; break; - case Variant::COLOR: type="color"; break; + case Variant::NIL: type = "nil"; break; + case Variant::BOOL: type = "bool"; break; + case Variant::INT: type = "int"; break; + case Variant::REAL: type = "real"; break; + case Variant::STRING: type = "string"; break; + case Variant::VECTOR2: type = "vector2"; break; + case Variant::RECT2: type = "rect2"; break; + case Variant::VECTOR3: type = "vector3"; break; + case Variant::PLANE: type = "plane"; break; + case Variant::_AABB: type = "aabb"; break; + case Variant::QUAT: type = "quaternion"; break; + case Variant::MATRIX32: type = "matrix32"; break; + case Variant::MATRIX3: type = "matrix3"; break; + case Variant::TRANSFORM: type = "transform"; break; + case Variant::COLOR: type = "color"; break; case Variant::IMAGE: { - type="image"; - Image img=p_property; + type = "image"; + Image img = p_property; if (img.empty()) { write_tabs(); - enter_tag(type,"name=\""+p_name+"\""); + enter_tag(type, "name=\"" + p_name + "\""); exit_tag(type); if (r_ok) - *r_ok=true; + *r_ok = true; return; } - params+="encoding=\"raw\""; - params+=" width=\""+itos(img.get_width())+"\""; - params+=" height=\""+itos(img.get_height())+"\""; - params+=" mipmaps=\""+itos(img.get_mipmaps())+"\""; + params += "encoding=\"raw\""; + params += " width=\"" + itos(img.get_width()) + "\""; + params += " height=\"" + itos(img.get_height()) + "\""; + params += " mipmaps=\"" + itos(img.get_mipmaps()) + "\""; - switch(img.get_format()) { + switch (img.get_format()) { - case Image::FORMAT_GRAYSCALE: params+=" format=\"grayscale\""; break; - case Image::FORMAT_INTENSITY: params+=" format=\"intensity\""; break; - case Image::FORMAT_GRAYSCALE_ALPHA: params+=" format=\"grayscale_alpha\""; break; - case Image::FORMAT_RGB: params+=" format=\"rgb\""; break; - case Image::FORMAT_RGBA: params+=" format=\"rgba\""; break; - case Image::FORMAT_INDEXED : params+=" format=\"indexed\""; break; - case Image::FORMAT_INDEXED_ALPHA: params+=" format=\"indexed_alpha\""; break; - case Image::FORMAT_BC1: params+=" format=\"bc1\""; break; - case Image::FORMAT_BC2: params+=" format=\"bc2\""; break; - case Image::FORMAT_BC3: params+=" format=\"bc3\""; break; - case Image::FORMAT_BC4: params+=" format=\"bc4\""; break; - case Image::FORMAT_BC5: params+=" format=\"bc5\""; break; - case Image::FORMAT_PVRTC2: params+=" format=\"pvrtc2\""; break; - case Image::FORMAT_PVRTC2_ALPHA: params+=" format=\"pvrtc2a\""; break; - case Image::FORMAT_PVRTC4: params+=" format=\"pvrtc4\""; break; - case Image::FORMAT_PVRTC4_ALPHA: params+=" format=\"pvrtc4a\""; break; - case Image::FORMAT_ETC: params+=" format=\"etc\""; break; - case Image::FORMAT_ATC: params+=" format=\"atc\""; break; - case Image::FORMAT_ATC_ALPHA_EXPLICIT: params+=" format=\"atcae\""; break; - case Image::FORMAT_ATC_ALPHA_INTERPOLATED: params+=" format=\"atcai\""; break; - case Image::FORMAT_CUSTOM: params+=" format=\"custom\" custom_size=\""+itos(img.get_data().size())+"\""; break; + case Image::FORMAT_GRAYSCALE: params += " format=\"grayscale\""; break; + case Image::FORMAT_INTENSITY: params += " format=\"intensity\""; break; + case Image::FORMAT_GRAYSCALE_ALPHA: params += " format=\"grayscale_alpha\""; break; + case Image::FORMAT_RGB: params += " format=\"rgb\""; break; + case Image::FORMAT_RGBA: params += " format=\"rgba\""; break; + case Image::FORMAT_INDEXED: params += " format=\"indexed\""; break; + case Image::FORMAT_INDEXED_ALPHA: params += " format=\"indexed_alpha\""; break; + case Image::FORMAT_BC1: params += " format=\"bc1\""; break; + case Image::FORMAT_BC2: params += " format=\"bc2\""; break; + case Image::FORMAT_BC3: params += " format=\"bc3\""; break; + case Image::FORMAT_BC4: params += " format=\"bc4\""; break; + case Image::FORMAT_BC5: params += " format=\"bc5\""; break; + case Image::FORMAT_PVRTC2: params += " format=\"pvrtc2\""; break; + case Image::FORMAT_PVRTC2_ALPHA: params += " format=\"pvrtc2a\""; break; + case Image::FORMAT_PVRTC4: params += " format=\"pvrtc4\""; break; + case Image::FORMAT_PVRTC4_ALPHA: params += " format=\"pvrtc4a\""; break; + case Image::FORMAT_ETC: params += " format=\"etc\""; break; + case Image::FORMAT_ATC: params += " format=\"atc\""; break; + case Image::FORMAT_ATC_ALPHA_EXPLICIT: params += " format=\"atcae\""; break; + case Image::FORMAT_ATC_ALPHA_INTERPOLATED: params += " format=\"atcai\""; break; + case Image::FORMAT_CUSTOM: params += " format=\"custom\" custom_size=\"" + itos(img.get_data().size()) + "\""; break; default: {} } } break; - case Variant::NODE_PATH: type="node_path"; break; - case Variant::OBJECT: { - type="resource"; + case Variant::NODE_PATH: type = "node_path"; break; + case Variant::OBJECT: { + type = "resource"; RES res = p_property; if (res.is_null()) { write_tabs(); - enter_tag(type,"name=\""+p_name+"\""); + enter_tag(type, "name=\"" + p_name + "\""); exit_tag(type); if (r_ok) - *r_ok=true; + *r_ok = true; return; // don't save it } if (external_resources.has(res)) { - params="external=\""+itos(external_resources[res])+"\""; + params = "external=\"" + itos(external_resources[res]) + "\""; } else { - params="resource_type=\""+res->get_save_type()+"\""; - + params = "resource_type=\"" + res->get_save_type() + "\""; - if (res->get_path().length() && res->get_path().find("::")==-1) { + if (res->get_path().length() && res->get_path().find("::") == -1) { //external resource - String path=relative_paths?local_path.path_to_file(res->get_path()):res->get_path(); + String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path(); escape(path); - params+=" path=\""+path+"\""; + params += " path=\"" + path + "\""; } else { //internal resource ERR_EXPLAIN("Resource was not pre cached for the resource section, bug?"); ERR_FAIL_COND(!resource_set.has(res)); - params+=" path=\"local://"+itos(res->get_subindex())+"\""; + params += " path=\"local://" + itos(res->get_subindex()) + "\""; } } } break; - case Variant::INPUT_EVENT: type="input_event"; break; - case Variant::DICTIONARY: type="dictionary"; params="shared=\""+String(p_property.is_shared()?"true":"false")+"\""; oneliner=false; break; - case Variant::ARRAY: type="array"; params="len=\""+itos(p_property.operator Array().size())+"\" shared=\""+String(p_property.is_shared()?"true":"false")+"\""; oneliner=false; break; + case Variant::INPUT_EVENT: type = "input_event"; break; + case Variant::DICTIONARY: + type = "dictionary"; + params = "shared=\"" + String(p_property.is_shared() ? "true" : "false") + "\""; + oneliner = false; + break; + case Variant::ARRAY: + type = "array"; + params = "len=\"" + itos(p_property.operator Array().size()) + "\" shared=\"" + String(p_property.is_shared() ? "true" : "false") + "\""; + oneliner = false; + break; - case Variant::RAW_ARRAY: type="raw_array"; params="len=\""+itos(p_property.operator DVector < uint8_t >().size())+"\""; break; - case Variant::INT_ARRAY: type="int_array"; params="len=\""+itos(p_property.operator DVector < int >().size())+"\""; break; - case Variant::REAL_ARRAY: type="real_array"; params="len=\""+itos(p_property.operator DVector < real_t >().size())+"\""; break; - case Variant::STRING_ARRAY: oneliner=false; type="string_array"; params="len=\""+itos(p_property.operator DVector < String >().size())+"\""; break; - case Variant::VECTOR2_ARRAY: type="vector2_array"; params="len=\""+itos(p_property.operator DVector < Vector2 >().size())+"\""; break; - case Variant::VECTOR3_ARRAY: type="vector3_array"; params="len=\""+itos(p_property.operator DVector < Vector3 >().size())+"\""; break; - case Variant::COLOR_ARRAY: type="color_array"; params="len=\""+itos(p_property.operator DVector < Color >().size())+"\""; break; + case Variant::RAW_ARRAY: + type = "raw_array"; + params = "len=\"" + itos(p_property.operator DVector<uint8_t>().size()) + "\""; + break; + case Variant::INT_ARRAY: + type = "int_array"; + params = "len=\"" + itos(p_property.operator DVector<int>().size()) + "\""; + break; + case Variant::REAL_ARRAY: + type = "real_array"; + params = "len=\"" + itos(p_property.operator DVector<real_t>().size()) + "\""; + break; + case Variant::STRING_ARRAY: + oneliner = false; + type = "string_array"; + params = "len=\"" + itos(p_property.operator DVector<String>().size()) + "\""; + break; + case Variant::VECTOR2_ARRAY: + type = "vector2_array"; + params = "len=\"" + itos(p_property.operator DVector<Vector2>().size()) + "\""; + break; + case Variant::VECTOR3_ARRAY: + type = "vector3_array"; + params = "len=\"" + itos(p_property.operator DVector<Vector3>().size()) + "\""; + break; + case Variant::COLOR_ARRAY: + type = "color_array"; + params = "len=\"" + itos(p_property.operator DVector<Color>().size()) + "\""; + break; default: { ERR_PRINT("Unknown Variant type."); ERR_FAIL(); } - } write_tabs(); - if (p_name!="") { + if (p_name != "") { if (params.length()) - enter_tag(type,"name=\""+p_name+"\" "+params); + enter_tag(type, "name=\"" + p_name + "\" " + params); else - enter_tag(type,"name=\""+p_name+"\""); + enter_tag(type, "name=\"" + p_name + "\""); } else { if (params.length()) - enter_tag(type," "+params); + enter_tag(type, " " + params); else - enter_tag(type,String()); + enter_tag(type, String()); } if (!oneliner) @@ -2465,75 +2379,74 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V else f->store_8(' '); - - switch( p_property.get_type() ) { + switch (p_property.get_type()) { case Variant::NIL: { } break; case Variant::BOOL: { - write_string( p_property.operator bool() ? "True":"False" ); + write_string(p_property.operator bool() ? "True" : "False"); } break; case Variant::INT: { - write_string( itos(p_property.operator int()) ); + write_string(itos(p_property.operator int())); } break; case Variant::REAL: { - write_string( rtos(p_property.operator real_t()) ); + write_string(rtos(p_property.operator real_t())); } break; case Variant::STRING: { - String str=p_property; + String str = p_property; escape(str); - str="\""+str+"\""; - write_string( str,false ); + str = "\"" + str + "\""; + write_string(str, false); } break; case Variant::VECTOR2: { Vector2 v = p_property; - write_string( rtoss(v.x) +", "+rtoss(v.y) ); + write_string(rtoss(v.x) + ", " + rtoss(v.y)); } break; case Variant::RECT2: { Rect2 aabb = p_property; - write_string( rtoss(aabb.pos.x) +", "+rtoss(aabb.pos.y) +", "+rtoss(aabb.size.x) +", "+rtoss(aabb.size.y) ); + write_string(rtoss(aabb.pos.x) + ", " + rtoss(aabb.pos.y) + ", " + rtoss(aabb.size.x) + ", " + rtoss(aabb.size.y)); } break; case Variant::VECTOR3: { Vector3 v = p_property; - write_string( rtoss(v.x) +", "+rtoss(v.y)+", "+rtoss(v.z) ); + write_string(rtoss(v.x) + ", " + rtoss(v.y) + ", " + rtoss(v.z)); } break; case Variant::PLANE: { Plane p = p_property; - write_string( rtoss(p.normal.x) +", "+rtoss(p.normal.y)+", "+rtoss(p.normal.z)+", "+rtoss(p.d) ); + write_string(rtoss(p.normal.x) + ", " + rtoss(p.normal.y) + ", " + rtoss(p.normal.z) + ", " + rtoss(p.d)); } break; case Variant::_AABB: { AABB aabb = p_property; - write_string( rtoss(aabb.pos.x) +", "+rtoss(aabb.pos.y) +", "+rtoss(aabb.pos.z) +", "+rtoss(aabb.size.x) +", "+rtoss(aabb.size.y) +", "+rtoss(aabb.size.z) ); + write_string(rtoss(aabb.pos.x) + ", " + rtoss(aabb.pos.y) + ", " + rtoss(aabb.pos.z) + ", " + rtoss(aabb.size.x) + ", " + rtoss(aabb.size.y) + ", " + rtoss(aabb.size.z)); } break; case Variant::QUAT: { Quat quat = p_property; - write_string( rtoss(quat.x)+", "+rtoss(quat.y)+", "+rtoss(quat.z)+", "+rtoss(quat.w)+", "); + write_string(rtoss(quat.x) + ", " + rtoss(quat.y) + ", " + rtoss(quat.z) + ", " + rtoss(quat.w) + ", "); } break; case Variant::MATRIX32: { String s; Matrix32 m3 = p_property; - for (int i=0;i<3;i++) { - for (int j=0;j<2;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { - if (i!=0 || j!=0) - s+=", "; - s+=rtoss( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtoss(m3.elements[i][j]); } } @@ -2544,12 +2457,12 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V String s; Matrix3 m3 = p_property; - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - if (i!=0 || j!=0) - s+=", "; - s+=rtoss( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtoss(m3.elements[i][j]); } } @@ -2561,25 +2474,25 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V String s; Transform t = p_property; Matrix3 &m3 = t.basis; - for (int i=0;i<3;i++) { - for (int j=0;j<3;j++) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { - if (i!=0 || j!=0) - s+=", "; - s+=rtoss( m3.elements[i][j] ); + if (i != 0 || j != 0) + s += ", "; + s += rtoss(m3.elements[i][j]); } } - s=s+", "+rtoss(t.origin.x) +", "+rtoss(t.origin.y)+", "+rtoss(t.origin.z); + s = s + ", " + rtoss(t.origin.x) + ", " + rtoss(t.origin.y) + ", " + rtoss(t.origin.z); write_string(s); } break; - // misc types + // misc types case Variant::COLOR: { Color c = p_property; - write_string( rtoss(c.r) +", "+rtoss(c.g)+", "+rtoss(c.b)+", "+rtoss(c.a) ); + write_string(rtoss(c.r) + ", " + rtoss(c.g) + ", " + rtoss(c.b) + ", " + rtoss(c.a)); } break; case Variant::IMAGE: { @@ -2589,23 +2502,24 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector<uint8_t> data = img.get_data(); int len = data.size(); DVector<uint8_t>::Read r = data.read(); - const uint8_t *ptr=r.ptr();; - for (int i=0;i<len;i++) { + const uint8_t *ptr = r.ptr(); + ; + for (int i = 0; i < len; i++) { uint8_t byte = ptr[i]; - const char hex[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; - char str[3]={ hex[byte>>4], hex[byte&0xF], 0}; - s+=str; + const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + char str[3] = { hex[byte >> 4], hex[byte & 0xF], 0 }; + s += str; } write_string(s); } break; case Variant::NODE_PATH: { - String str=p_property; + String str = p_property; escape(str); - str="\""+str+"\""; - write_string( str,false); + str = "\"" + str + "\""; + write_string(str, false); } break; @@ -2627,42 +2541,37 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V } break; case Variant::INPUT_EVENT: { - write_string( p_property.operator String() ); + write_string(p_property.operator String()); } break; case Variant::DICTIONARY: { Dictionary dict = p_property; - List<Variant> keys; dict.get_key_list(&keys); keys.sort(); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { //if (!_check_type(dict[E->get()])) // continue; bool ok; - write_property("",E->get(),&ok); + write_property("", E->get(), &ok); ERR_CONTINUE(!ok); - write_property("",dict[E->get()],&ok); + write_property("", dict[E->get()], &ok); if (!ok) - write_property("",Variant()); //at least make the file consistent.. + write_property("", Variant()); //at least make the file consistent.. } - - - } break; case Variant::ARRAY: { Array array = p_property; - int len=array.size(); - for (int i=0;i<len;i++) { - - write_property("",array[i]); + int len = array.size(); + for (int i = 0; i < len; i++) { + write_property("", array[i]); } } break; @@ -2673,16 +2582,17 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector<uint8_t> data = p_property; int len = data.size(); DVector<uint8_t>::Read r = data.read(); - const uint8_t *ptr=r.ptr();; - for (int i=0;i<len;i++) { + const uint8_t *ptr = r.ptr(); + ; + for (int i = 0; i < len; i++) { uint8_t byte = ptr[i]; - const char hex[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; - char str[3]={ hex[byte>>4], hex[byte&0xF], 0}; - s+=str; + const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + char str[3] = { hex[byte >> 4], hex[byte & 0xF], 0 }; + s += str; } - write_string(s,false); + write_string(s, false); } break; case Variant::INT_ARRAY: { @@ -2690,55 +2600,53 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector<int> data = p_property; int len = data.size(); DVector<int>::Read r = data.read(); - const int *ptr=r.ptr();; + const int *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - write_string(", ",false); + if (i > 0) + write_string(", ", false); - write_string(itos(ptr[i]),false); + write_string(itos(ptr[i]), false); } - - } break; case Variant::REAL_ARRAY: { DVector<real_t> data = p_property; int len = data.size(); DVector<real_t>::Read r = data.read(); - const real_t *ptr=r.ptr();; + const real_t *ptr = r.ptr(); + ; write_tabs(); - String cm=", " ; + String cm = ", "; - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - write_string(cm,false); - write_string(rtoss(ptr[i]),false); + if (i > 0) + write_string(cm, false); + write_string(rtoss(ptr[i]), false); } - } break; case Variant::STRING_ARRAY: { DVector<String> data = p_property; int len = data.size(); DVector<String>::Read r = data.read(); - const String *ptr=r.ptr();; + const String *ptr = r.ptr(); + ; String s; //write_string("\n"); - - - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { write_tabs(0); - String str=ptr[i]; + String str = ptr[i]; escape(str); - write_string("<string> \""+str+"\" </string>\n",false); + write_string("<string> \"" + str + "\" </string>\n", false); } } break; case Variant::VECTOR2_ARRAY: { @@ -2746,63 +2654,60 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V DVector<Vector2> data = p_property; int len = data.size(); DVector<Vector2>::Read r = data.read(); - const Vector2 *ptr=r.ptr();; + const Vector2 *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i<len;i++) { - - if (i>0) - write_string(", ",false); - write_string(rtoss(ptr[i].x),false); - write_string(", "+rtoss(ptr[i].y),false); + for (int i = 0; i < len; i++) { + if (i > 0) + write_string(", ", false); + write_string(rtoss(ptr[i].x), false); + write_string(", " + rtoss(ptr[i].y), false); } - } break; case Variant::VECTOR3_ARRAY: { DVector<Vector3> data = p_property; int len = data.size(); DVector<Vector3>::Read r = data.read(); - const Vector3 *ptr=r.ptr();; + const Vector3 *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i<len;i++) { - - if (i>0) - write_string(", ",false); - write_string(rtoss(ptr[i].x),false); - write_string(", "+rtoss(ptr[i].y),false); - write_string(", "+rtoss(ptr[i].z),false); + for (int i = 0; i < len; i++) { + if (i > 0) + write_string(", ", false); + write_string(rtoss(ptr[i].x), false); + write_string(", " + rtoss(ptr[i].y), false); + write_string(", " + rtoss(ptr[i].z), false); } - } break; case Variant::COLOR_ARRAY: { DVector<Color> data = p_property; int len = data.size(); DVector<Color>::Read r = data.read(); - const Color *ptr=r.ptr();; + const Color *ptr = r.ptr(); + ; write_tabs(); - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i>0) - write_string(", ",false); - - write_string(rtoss(ptr[i].r),false); - write_string(", "+rtoss(ptr[i].g),false); - write_string(", "+rtoss(ptr[i].b),false); - write_string(", "+rtoss(ptr[i].a),false); + if (i > 0) + write_string(", ", false); + write_string(rtoss(ptr[i].r), false); + write_string(", " + rtoss(ptr[i].g), false); + write_string(", " + rtoss(ptr[i].b), false); + write_string(", " + rtoss(ptr[i].a), false); } } break; default: {} - } if (oneliner) f->store_8(' '); @@ -2813,26 +2718,22 @@ void ResourceFormatSaverXMLInstance::write_property(const String& p_name,const V f->store_8('\n'); if (r_ok) - *r_ok=true; - + *r_ok = true; } +void ResourceFormatSaverXMLInstance::_find_resources(const Variant &p_variant, bool p_main) { -void ResourceFormatSaverXMLInstance::_find_resources(const Variant& p_variant,bool p_main) { - - - switch(p_variant.get_type()) { + switch (p_variant.get_type()) { case Variant::OBJECT: { - RES res = p_variant.operator RefPtr(); if (res.is_null() || external_resources.has(res)) return; - if (!p_main && (!bundle_resources ) && res->get_path().length() && res->get_path().find("::") == -1 ) { + if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) { int index = external_resources.size(); - external_resources[res]=index; + external_resources[res] = index; return; } @@ -2841,45 +2742,45 @@ void ResourceFormatSaverXMLInstance::_find_resources(const Variant& p_variant,bo List<PropertyInfo> property_list; - res->get_property_list( &property_list ); + res->get_property_list(&property_list); property_list.sort(); - List<PropertyInfo>::Element *I=property_list.front(); + List<PropertyInfo>::Element *I = property_list.front(); - while(I) { + while (I) { - PropertyInfo pi=I->get(); + PropertyInfo pi = I->get(); - if (pi.usage&PROPERTY_USAGE_STORAGE || (bundle_resources && pi.usage&PROPERTY_USAGE_BUNDLE)) { + if (pi.usage & PROPERTY_USAGE_STORAGE || (bundle_resources && pi.usage & PROPERTY_USAGE_BUNDLE)) { - Variant v=res->get(I->get().name); + Variant v = res->get(I->get().name); _find_resources(v); } - I=I->next(); + I = I->next(); } - resource_set.insert( res ); //saved after, so the childs it needs are available when loaded + resource_set.insert(res); //saved after, so the childs it needs are available when loaded saved_resources.push_back(res); } break; case Variant::ARRAY: { - Array varray=p_variant; - int len=varray.size(); - for(int i=0;i<len;i++) { + Array varray = p_variant; + int len = varray.size(); + for (int i = 0; i < len; i++) { - Variant v=varray.get(i); + Variant v = varray.get(i); _find_resources(v); } } break; case Variant::DICTIONARY: { - Dictionary d=p_variant; + Dictionary d = p_variant; List<Variant> keys; d.get_key_list(&keys); - for(List<Variant>::Element *E=keys.front();E;E=E->next()) { + for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { Variant v = d[E->get()]; _find_resources(v); @@ -2887,57 +2788,54 @@ void ResourceFormatSaverXMLInstance::_find_resources(const Variant& p_variant,bo } break; default: {} } - } - - -Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverXMLInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Error err; - f = FileAccess::open(p_path, FileAccess::WRITE,&err); - ERR_FAIL_COND_V( err, ERR_CANT_OPEN ); + f = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V(err, ERR_CANT_OPEN); FileAccessRef _fref(f); local_path = Globals::get_singleton()->localize_path(p_path); - 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; - takeover_paths=p_flags&ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; + 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; + takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; if (!p_path.begins_with("res://")) { - takeover_paths=false; + takeover_paths = false; } - depth=0; + depth = 0; // save resources - _find_resources(p_resource,true); + _find_resources(p_resource, true); - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); - write_string("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",false); //no escape - write_string("\n",false); - enter_tag("resource_file","type=\""+p_resource->get_type()+"\" subresource_count=\""+itos(saved_resources.size()+external_resources.size())+"\" version=\""+itos(VERSION_MAJOR)+"."+itos(VERSION_MINOR)+"\" version_name=\""+VERSION_FULL_NAME+"\""); - write_string("\n",false); + write_string("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", false); //no escape + write_string("\n", false); + enter_tag("resource_file", "type=\"" + p_resource->get_type() + "\" subresource_count=\"" + itos(saved_resources.size() + external_resources.size()) + "\" version=\"" + itos(VERSION_MAJOR) + "." + itos(VERSION_MINOR) + "\" version_name=\"" + VERSION_FULL_NAME + "\""); + write_string("\n", false); - for(Map<RES,int>::Element *E=external_resources.front();E;E=E->next()) { + for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) { write_tabs(); String p = E->key()->get_path(); - enter_tag("ext_resource","path=\""+p+"\" type=\""+E->key()->get_save_type()+"\" index=\""+itos(E->get())+"\""); //bundled + enter_tag("ext_resource", "path=\"" + p + "\" type=\"" + E->key()->get_save_type() + "\" index=\"" + itos(E->get()) + "\""); //bundled exit_tag("ext_resource"); //bundled - write_string("\n",false); + write_string("\n", false); } Set<int> used_indices; - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { RES res = E->get(); - if (E->next() && (res->get_path()=="" || res->get_path().find("::") != -1 )) { + if (E->next() && (res->get_path() == "" || res->get_path().find("::") != -1)) { - if (res->get_subindex()!=0) { + if (res->get_subindex() != 0) { if (used_indices.has(res->get_subindex())) { res->set_subindex(0); //repeated } else { @@ -2947,24 +2845,24 @@ Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_res } } - for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) { + for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) { RES res = E->get(); ERR_CONTINUE(!resource_set.has(res)); - bool main = (E->next()==NULL); + bool main = (E->next() == NULL); write_tabs(); if (main) - enter_tag("main_resource",""); //bundled - else if (res->get_path().length() && res->get_path().find("::") == -1 ) - enter_tag("resource","type=\""+res->get_type()+"\" path=\""+res->get_path()+"\""); //bundled + enter_tag("main_resource", ""); //bundled + else if (res->get_path().length() && res->get_path().find("::") == -1) + enter_tag("resource", "type=\"" + res->get_type() + "\" path=\"" + res->get_path() + "\""); //bundled else { - if (res->get_subindex()==0) { - int new_subindex=1; + if (res->get_subindex() == 0) { + int new_subindex = 1; if (used_indices.size()) { - new_subindex=used_indices.back()->get()+1; + new_subindex = used_indices.back()->get() + 1; } res->set_subindex(new_subindex); @@ -2972,52 +2870,45 @@ Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_res } int idx = res->get_subindex(); - enter_tag("resource","type=\""+res->get_type()+"\" path=\"local://"+itos(idx)+"\""); + enter_tag("resource", "type=\"" + res->get_type() + "\" path=\"local://" + itos(idx) + "\""); if (takeover_paths) { - res->set_path(p_path+"::"+itos(idx),true); + res->set_path(p_path + "::" + itos(idx), true); } - } - write_string("\n",false); - + write_string("\n", false); List<PropertyInfo> property_list; res->get_property_list(&property_list); -// property_list.sort(); - for(List<PropertyInfo>::Element *PE = property_list.front();PE;PE=PE->next()) { - + // property_list.sort(); + for (List<PropertyInfo>::Element *PE = property_list.front(); PE; PE = PE->next()) { if (skip_editor && PE->get().name.begins_with("__editor")) continue; - if (PE->get().usage&PROPERTY_USAGE_STORAGE || (bundle_resources && PE->get().usage&PROPERTY_USAGE_BUNDLE)) { + if (PE->get().usage & PROPERTY_USAGE_STORAGE || (bundle_resources && PE->get().usage & PROPERTY_USAGE_BUNDLE)) { String name = PE->get().name; Variant value = res->get(name); - - if ((PE->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && value.is_zero())||(PE->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && value.is_one()) ) + if ((PE->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO && value.is_zero()) || (PE->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && value.is_one())) continue; - - write_property(name,value); + write_property(name, value); } - - } - write_string("\n",false); + write_string("\n", false); write_tabs(-1); if (main) exit_tag("main_resource"); else exit_tag("resource"); - write_string("\n",false); + write_string("\n", false); } exit_tag("resource_file"); - if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) { + if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { f->close(); return ERR_CANT_CREATE; } @@ -3028,34 +2919,28 @@ Error ResourceFormatSaverXMLInstance::save(const String &p_path,const RES& p_res return OK; } - - -Error ResourceFormatSaverXML::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverXML::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { ResourceFormatSaverXMLInstance saver; - return saver.save(p_path,p_resource,p_flags); - + return saver.save(p_path, p_resource, p_flags); } -bool ResourceFormatSaverXML::recognize(const RES& p_resource) const { - +bool ResourceFormatSaverXML::recognize(const RES &p_resource) const { return true; // all recognized! } -void ResourceFormatSaverXML::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { - +void ResourceFormatSaverXML::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { //here comes the sun, lalalala String base = p_resource->get_base_extension().to_lower(); p_extensions->push_back("xml"); - if (base!="res") { + if (base != "res") { - p_extensions->push_back("x"+base); + p_extensions->push_back("x" + base); } - } -ResourceFormatSaverXML* ResourceFormatSaverXML::singleton=NULL; +ResourceFormatSaverXML *ResourceFormatSaverXML::singleton = NULL; ResourceFormatSaverXML::ResourceFormatSaverXML() { - singleton=this; + singleton = this; } diff --git a/core/io/resource_format_xml.h b/core/io/resource_format_xml.h index 5923817b6..482c954bc 100644 --- a/core/io/resource_format_xml.h +++ b/core/io/resource_format_xml.h @@ -33,8 +33,6 @@ #include "io/resource_saver.h" #include "os/file_access.h" - - class ResourceInteractiveLoaderXML : public ResourceInteractiveLoader { String local_path; @@ -45,22 +43,19 @@ class ResourceInteractiveLoaderXML : public ResourceInteractiveLoader { struct Tag { String name; - HashMap<String,String> args; - + HashMap<String, String> args; }; - _FORCE_INLINE_ Error _parse_array_element(Vector<char> &buff,bool p_number_only,FileAccess *f,bool *end); - + _FORCE_INLINE_ Error _parse_array_element(Vector<char> &buff, bool p_number_only, FileAccess *f, bool *end); struct ExtResource { String path; String type; }; + Map<String, String> remaps; - Map<String,String> remaps; - - Map<int,ExtResource> ext_resources; + Map<int, ExtResource> ext_resources; int resources_total; int resource_current; @@ -70,24 +65,23 @@ class ResourceInteractiveLoaderXML : public ResourceInteractiveLoader { uint8_t get_char() const; int get_current_line() const; -friend class ResourceFormatLoaderXML; + friend class ResourceFormatLoaderXML; List<Tag> tag_stack; List<RES> resource_cache; - Tag* parse_tag(bool* r_exit=NULL,bool p_printerr=true,List<String> *r_order=NULL); - Error close_tag(const String& p_name); - _FORCE_INLINE_ void unquote(String& p_str); + Tag *parse_tag(bool *r_exit = NULL, bool p_printerr = true, List<String> *r_order = NULL); + Error close_tag(const String &p_name); + _FORCE_INLINE_ void unquote(String &p_str); Error goto_end_of_tag(); Error parse_property_data(String &r_data); - Error parse_property(Variant& r_v, String &r_name,bool p_for_export_data=false); + Error parse_property(Variant &r_v, String &r_name, bool p_for_export_data = false); Error error; RES resource; public: - - virtual void set_local_path(const String& p_local_path); + virtual void set_local_path(const String &p_local_path); virtual Ref<Resource> get_resource(); virtual Error poll(); virtual int get_stage() const; @@ -96,41 +90,34 @@ public: void open(FileAccess *p_f); String recognize(FileAccess *p_f); void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); - Error rename_dependencies(FileAccess *p_f, const String &p_path,const Map<String,String>& p_map); + Error rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map); - Error get_export_data(FileAccess *p_f,ExportData& r_export_data); + Error get_export_data(FileAccess *p_f, ExportData &r_export_data); ~ResourceInteractiveLoaderXML(); - }; class ResourceFormatLoaderXML : public ResourceFormatLoader { public: - static ResourceFormatLoaderXML *singleton; - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - virtual void get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types=false); - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - virtual Error get_export_data(const String& p_path,ExportData& r_export_data); - - ResourceFormatLoaderXML() { singleton=this; } + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); + virtual Error get_export_data(const String &p_path, ExportData &r_export_data); + ResourceFormatLoaderXML() { singleton = this; } }; - //////////////////////////////////////////////////////////////////////////////////////////// - -class ResourceFormatSaverXMLInstance { +class ResourceFormatSaverXMLInstance { String local_path; - - bool takeover_paths; bool relative_paths; bool bundle_resources; @@ -139,36 +126,30 @@ class ResourceFormatSaverXMLInstance { int depth; Set<RES> resource_set; List<RES> saved_resources; - Map<RES,int> external_resources; - - void enter_tag(const char* p_tag,const String& p_args=String()); - void exit_tag(const char* p_tag); - - void _find_resources(const Variant& p_variant,bool p_main=false); - void write_property(const String& p_name,const Variant& p_property,bool *r_ok=NULL); + Map<RES, int> external_resources; + void enter_tag(const char *p_tag, const String &p_args = String()); + void exit_tag(const char *p_tag); - void escape(String& p_str); - void write_tabs(int p_diff=0); - void write_string(String p_str,bool p_escape=true); + void _find_resources(const Variant &p_variant, bool p_main = false); + void write_property(const String &p_name, const Variant &p_property, bool *r_ok = NULL); + void escape(String &p_str); + void write_tabs(int p_diff = 0); + void write_string(String p_str, bool p_escape = true); public: - - Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - - + Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); }; class ResourceFormatSaverXML : public ResourceFormatSaver { public: - static ResourceFormatSaverXML* singleton; - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - virtual bool recognize(const RES& p_resource) const; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const; + static ResourceFormatSaverXML *singleton; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual bool recognize(const RES &p_resource) const; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; ResourceFormatSaverXML(); }; - #endif // RESOURCE_FORMAT_XML_H diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp index 2fa3a996c..4f663eaa1 100644 --- a/core/io/resource_loader.cpp +++ b/core/io/resource_loader.cpp @@ -27,72 +27,69 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "resource_loader.h" -#include "print_string.h" #include "globals.h" -#include "path_remap.h" #include "os/file_access.h" #include "os/os.h" +#include "path_remap.h" +#include "print_string.h" ResourceFormatLoader *ResourceLoader::loader[MAX_LOADERS]; -int ResourceLoader::loader_count=0; - +int ResourceLoader::loader_count = 0; Error ResourceInteractiveLoader::wait() { Error err = poll(); - while (err==OK) { - err=poll(); + while (err == OK) { + err = poll(); } return err; } - -bool ResourceFormatLoader::recognize(const String& p_extension) const { - +bool ResourceFormatLoader::recognize(const String &p_extension) const { List<String> extensions; get_recognized_extensions(&extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(p_extension.extension())==0) + if (E->get().nocasecmp_to(p_extension.extension()) == 0) return true; } return false; } -void ResourceFormatLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { +void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const { - if (p_type=="" || handles_type(p_type)) + if (p_type == "" || handles_type(p_type)) get_recognized_extensions(p_extensions); } -void ResourceLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) { +void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) { - for (int i=0;i<loader_count;i++) { - loader[i]->get_recognized_extensions_for_type(p_type,p_extensions); + for (int i = 0; i < loader_count; i++) { + loader[i]->get_recognized_extensions_for_type(p_type, p_extensions); } - } void ResourceInteractiveLoader::_bind_methods() { - ObjectTypeDB::bind_method(_MD("get_resource"),&ResourceInteractiveLoader::get_resource); - ObjectTypeDB::bind_method(_MD("poll"),&ResourceInteractiveLoader::poll); - ObjectTypeDB::bind_method(_MD("wait"),&ResourceInteractiveLoader::wait); - ObjectTypeDB::bind_method(_MD("get_stage"),&ResourceInteractiveLoader::get_stage); - ObjectTypeDB::bind_method(_MD("get_stage_count"),&ResourceInteractiveLoader::get_stage_count); + ObjectTypeDB::bind_method(_MD("get_resource"), &ResourceInteractiveLoader::get_resource); + ObjectTypeDB::bind_method(_MD("poll"), &ResourceInteractiveLoader::poll); + ObjectTypeDB::bind_method(_MD("wait"), &ResourceInteractiveLoader::wait); + ObjectTypeDB::bind_method(_MD("get_stage"), &ResourceInteractiveLoader::get_stage); + ObjectTypeDB::bind_method(_MD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count); } class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader { - OBJ_TYPE( ResourceInteractiveLoaderDefault, ResourceInteractiveLoader ); -public: + OBJ_TYPE(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader); +public: Ref<Resource> resource; - virtual void set_local_path(const String& p_local_path) { /*scene->set_filename(p_local_path);*/ } + virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/ + } virtual Ref<Resource> get_resource() { return resource; } virtual Error poll() { return ERR_FILE_EOF; } virtual int get_stage() const { return 1; } @@ -101,98 +98,92 @@ public: ResourceInteractiveLoaderDefault() {} }; - - Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, Error *r_error) { //either this - Ref<Resource> res = load(p_path,p_path,r_error); + Ref<Resource> res = load(p_path, p_path, r_error); if (res.is_null()) return Ref<ResourceInteractiveLoader>(); - Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>( memnew( ResourceInteractiveLoaderDefault )); - ril->resource=res; + Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault)); + ril->resource = res; return ril; } -RES ResourceFormatLoader::load(const String &p_path, const String& p_original_path, Error *r_error) { - +RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) { - String path=p_path; + String path = p_path; //or this must be implemented - Ref<ResourceInteractiveLoader> ril = load_interactive(p_path,r_error); + Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, r_error); if (!ril.is_valid()) return RES(); ril->set_local_path(p_original_path); - while(true) { + while (true) { Error err = ril->poll(); - if (err==ERR_FILE_EOF) { + if (err == ERR_FILE_EOF) { if (r_error) - *r_error=OK; + *r_error = OK; return ril->get_resource(); } if (r_error) - *r_error=err; + *r_error = err; - ERR_FAIL_COND_V(err!=OK,RES()); + ERR_FAIL_COND_V(err != OK, RES()); } return RES(); - } -void ResourceFormatLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) { +void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { //do nothing by default } - /////////////////////////////////// - -RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p_no_cache, Error *r_error) { +RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); - local_path=find_complete_path(local_path,p_type_hint); - ERR_FAIL_COND_V(local_path=="",RES()); + local_path = find_complete_path(local_path, p_type_hint); + ERR_FAIL_COND_V(local_path == "", RES()); if (!p_no_cache && ResourceCache::has(local_path)) { if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path+" (cached)"); + print_line("load resource: " + local_path + " (cached)"); - return RES( ResourceCache::get(local_path ) ); + return RES(ResourceCache::get(local_path)); } String remapped_path = PathRemap::get_singleton()->get_remap(local_path); if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+remapped_path); + print_line("load resource: " + remapped_path); - String extension=remapped_path.extension(); - bool found=false; + String extension = remapped_path.extension(); + bool found = false; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; - if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) + if (p_type_hint != "" && !loader[i]->handles_type(p_type_hint)) continue; - found=true; - RES res = loader[i]->load(remapped_path,local_path,r_error); + found = true; + RES res = loader[i]->load(remapped_path, local_path, r_error); if (res.is_null()) continue; if (!p_no_cache) @@ -211,46 +202,39 @@ RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p } if (found) { - ERR_EXPLAIN("Failed loading resource: "+p_path); + ERR_EXPLAIN("Failed loading resource: " + p_path); } else { - ERR_EXPLAIN("No loader found for resource: "+p_path); + ERR_EXPLAIN("No loader found for resource: " + p_path); } ERR_FAIL_V(RES()); return RES(); } - Ref<ResourceImportMetadata> ResourceLoader::load_import_metadata(const String &p_path) { - - String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); - String extension=p_path.extension(); + String extension = p_path.extension(); Ref<ResourceImportMetadata> ret; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; - Error err = loader[i]->load_import_metadata(local_path,ret); - if (err==OK) + Error err = loader[i]->load_import_metadata(local_path, ret); + if (err == OK) break; } - return ret; - } - - -String ResourceLoader::find_complete_path(const String& p_path,const String& p_type) { +String ResourceLoader::find_complete_path(const String &p_path, const String &p_type) { //this is an old vestige when the engine saved files without extension. //remains here for compatibility with old projects and only because it //can be sometimes nice to open files using .* from a script and have it guess @@ -260,32 +244,30 @@ String ResourceLoader::find_complete_path(const String& p_path,const String& p_t if (local_path.ends_with("*")) { //find the extension for resource that ends with * - local_path = local_path.substr(0,local_path.length()-1); + local_path = local_path.substr(0, local_path.length() - 1); List<String> extensions; - get_recognized_extensions_for_type(p_type,&extensions); + get_recognized_extensions_for_type(p_type, &extensions); List<String> candidates; - for(List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - String path = local_path+E->get(); + String path = local_path + E->get(); if (PathRemap::get_singleton()->has_remap(path) || FileAccess::exists(path)) { candidates.push_back(path); } - } - - if (candidates.size()==0) { + if (candidates.size() == 0) { return ""; - } else if (candidates.size()==1 || p_type=="") { + } else if (candidates.size() == 1 || p_type == "") { return candidates.front()->get(); } else { - for(List<String>::Element *E=candidates.front();E;E=E->next()) { + for (List<String>::Element *E = candidates.front(); E; E = E->next()) { String rt = get_resource_type(E->get()); - if (ObjectTypeDB::is_type(rt,p_type)) { + if (ObjectTypeDB::is_type(rt, p_type)) { return E->get(); } } @@ -297,27 +279,24 @@ String ResourceLoader::find_complete_path(const String& p_path,const String& p_t return local_path; } -Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) { - +Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; + *r_error = ERR_CANT_OPEN; String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); - local_path=find_complete_path(local_path,p_type_hint); - ERR_FAIL_COND_V(local_path=="",Ref<ResourceInteractiveLoader>()); - - + local_path = find_complete_path(local_path, p_type_hint); + ERR_FAIL_COND_V(local_path == "", Ref<ResourceInteractiveLoader>()); if (!p_no_cache && ResourceCache::has(local_path)) { if (OS::get_singleton()->is_stdout_verbose()) - print_line("load resource: "+local_path+" (cached)"); + print_line("load resource: " + local_path + " (cached)"); Ref<Resource> res_cached = ResourceCache::get(local_path); Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault)); @@ -331,17 +310,17 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_ String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); - bool found=false; + String extension = remapped_path.extension(); + bool found = false; - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; - if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) + if (p_type_hint != "" && !loader[i]->handles_type(p_type_hint)) continue; - found=true; - Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(remapped_path,r_error); + found = true; + Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(remapped_path, r_error); if (ril.is_null()) continue; if (!p_no_cache) @@ -351,150 +330,137 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_ } if (found) { - ERR_EXPLAIN("Failed loading resource: "+p_path); + ERR_EXPLAIN("Failed loading resource: " + p_path); } else { - ERR_EXPLAIN("No loader found for resource: "+p_path); + ERR_EXPLAIN("No loader found for resource: " + p_path); } ERR_FAIL_V(Ref<ResourceInteractiveLoader>()); return Ref<ResourceInteractiveLoader>(); - } void ResourceLoader::add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front) { - ERR_FAIL_COND( loader_count >= MAX_LOADERS ); + ERR_FAIL_COND(loader_count >= MAX_LOADERS); if (p_at_front) { - for(int i=loader_count;i>0;i--) { - loader[i]=loader[i-1]; + for (int i = loader_count; i > 0; i--) { + loader[i] = loader[i - 1]; } - loader[0]=p_format_loader; + loader[0] = p_format_loader; loader_count++; } else { - loader[loader_count++]=p_format_loader; + loader[loader_count++] = p_format_loader; } } -void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) { - +void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; //if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) // continue; - loader[i]->get_dependencies(remapped_path,p_dependencies,p_add_types); - + loader[i]->get_dependencies(remapped_path, p_dependencies, p_add_types); } } -Error ResourceLoader::get_export_data(const String& p_path,ExportData& r_export_data) { - +Error ResourceLoader::get_export_data(const String &p_path, ExportData &r_export_data) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; //if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) // continue; - return loader[i]->get_export_data(p_path,r_export_data); - + return loader[i]->get_export_data(p_path, r_export_data); } return ERR_UNAVAILABLE; - } -Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { - +Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { if (!loader[i]->recognize(extension)) continue; //if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint)) // continue; - return loader[i]->rename_dependencies(p_path,p_map); - + return loader[i]->rename_dependencies(p_path, p_map); } return OK; // ?? - } - -String ResourceLoader::guess_full_filename(const String &p_path,const String& p_type) { +String ResourceLoader::guess_full_filename(const String &p_path, const String &p_type) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); - return find_complete_path(local_path,p_type); - + return find_complete_path(local_path, p_type); } String ResourceLoader::get_resource_type(const String &p_path) { String local_path; if (p_path.is_rel_path()) - local_path="res://"+p_path; + local_path = "res://" + p_path; else local_path = Globals::get_singleton()->localize_path(p_path); String remapped_path = PathRemap::get_singleton()->get_remap(local_path); - String extension=remapped_path.extension(); + String extension = remapped_path.extension(); - for (int i=0;i<loader_count;i++) { + for (int i = 0; i < loader_count; i++) { String result = loader[i]->get_resource_type(local_path); - if (result!="") + if (result != "") return result; } return ""; - } -ResourceLoadErrorNotify ResourceLoader::err_notify=NULL; -void *ResourceLoader::err_notify_ud=NULL; - -DependencyErrorNotify ResourceLoader::dep_err_notify=NULL; -void *ResourceLoader::dep_err_notify_ud=NULL; +ResourceLoadErrorNotify ResourceLoader::err_notify = NULL; +void *ResourceLoader::err_notify_ud = NULL; -bool ResourceLoader::abort_on_missing_resource=true; -bool ResourceLoader::timestamp_on_load=false; +DependencyErrorNotify ResourceLoader::dep_err_notify = NULL; +void *ResourceLoader::dep_err_notify_ud = NULL; +bool ResourceLoader::abort_on_missing_resource = true; +bool ResourceLoader::timestamp_on_load = false; diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h index 14a7ee83d..012b22dd9 100644 --- a/core/io/resource_loader.h +++ b/core/io/resource_loader.h @@ -29,99 +29,102 @@ #ifndef RESOURCE_LOADER_H #define RESOURCE_LOADER_H -#include "resource.h" #include "export_data.h" +#include "resource.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class ResourceInteractiveLoader : public Reference { - OBJ_TYPE(ResourceInteractiveLoader,Reference); -protected: + OBJ_TYPE(ResourceInteractiveLoader, Reference); +protected: static void _bind_methods(); -public: - virtual void set_local_path(const String& p_local_path)=0; - virtual Ref<Resource> get_resource()=0; - virtual Error poll()=0; - virtual int get_stage() const=0; - virtual int get_stage_count() const=0; +public: + virtual void set_local_path(const String &p_local_path) = 0; + virtual Ref<Resource> get_resource() = 0; + virtual Error poll() = 0; + virtual int get_stage() const = 0; + virtual int get_stage_count() const = 0; virtual Error wait(); ResourceInteractiveLoader() {} }; - class ResourceFormatLoader { public: - - virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL); - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); - virtual void get_recognized_extensions(List<String> *p_extensions) const=0; - virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const; - bool recognize(const String& p_extension) const; - virtual bool handles_type(const String& p_type) const=0; - virtual String get_resource_type(const String &p_path) const=0; - virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); - virtual Error load_import_metadata(const String &p_path, Ref<ResourceImportMetadata>& r_var) const { return ERR_UNAVAILABLE; } - virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map) { return OK; } - virtual Error get_export_data(const String& p_path,ExportData& r_export_data) { return ERR_UNAVAILABLE; } + virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); + virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; + virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const; + bool recognize(const String &p_extension) const; + virtual bool handles_type(const String &p_type) const = 0; + virtual String get_resource_type(const String &p_path) const = 0; + virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + virtual Error load_import_metadata(const String &p_path, Ref<ResourceImportMetadata> &r_var) const { return ERR_UNAVAILABLE; } + virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map) { return OK; } + virtual Error get_export_data(const String &p_path, ExportData &r_export_data) { return ERR_UNAVAILABLE; } virtual ~ResourceFormatLoader() {} }; - -typedef void (*ResourceLoadErrorNotify)(void *p_ud,const String& p_text); -typedef void (*DependencyErrorNotify)(void *p_ud,const String& p_loading,const String& p_which,const String& p_type); - +typedef void (*ResourceLoadErrorNotify)(void *p_ud, const String &p_text); +typedef void (*DependencyErrorNotify)(void *p_ud, const String &p_loading, const String &p_which, const String &p_type); class ResourceLoader { enum { - MAX_LOADERS=64 + MAX_LOADERS = 64 }; static ResourceFormatLoader *loader[MAX_LOADERS]; static int loader_count; static bool timestamp_on_load; - static void* err_notify_ud; + static void *err_notify_ud; static ResourceLoadErrorNotify err_notify; - static void* dep_err_notify_ud; + static void *dep_err_notify_ud; static DependencyErrorNotify dep_err_notify; static bool abort_on_missing_resource; - static String find_complete_path(const String& p_path,const String& p_type); -public: - + static String find_complete_path(const String &p_path, const String &p_type); - - static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL); - static RES load(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL); +public: + static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); + static RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL); static Ref<ResourceImportMetadata> load_import_metadata(const String &p_path); - static void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions); - static void add_resource_format_loader(ResourceFormatLoader *p_format_loader,bool p_at_front=false); + static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions); + static void add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front = false); static String get_resource_type(const String &p_path); - static void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false); - static Error rename_dependencies(const String &p_path,const Map<String,String>& p_map); - - static Error get_export_data(const String& p_path,ExportData& r_export_data); + static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false); + static Error rename_dependencies(const String &p_path, const Map<String, String> &p_map); - static String guess_full_filename(const String &p_path,const String& p_type); + static Error get_export_data(const String &p_path, ExportData &r_export_data); - static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load=p_timestamp; } + static String guess_full_filename(const String &p_path, const String &p_type); - static void notify_load_error(const String& p_err) { if (err_notify) err_notify(err_notify_ud,p_err); } - static void set_error_notify_func(void* p_ud,ResourceLoadErrorNotify p_err_notify) { err_notify=p_err_notify; err_notify_ud=p_ud;} + static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; } - static void notify_dependency_error(const String& p_path,const String& p_dependency,const String& p_type) { if (dep_err_notify) dep_err_notify(dep_err_notify_ud,p_path,p_dependency,p_type); } - static void set_dependency_error_notify_func(void* p_ud,DependencyErrorNotify p_err_notify) { dep_err_notify=p_err_notify; dep_err_notify_ud=p_ud;} + static void notify_load_error(const String &p_err) { + if (err_notify) err_notify(err_notify_ud, p_err); + } + static void set_error_notify_func(void *p_ud, ResourceLoadErrorNotify p_err_notify) { + err_notify = p_err_notify; + err_notify_ud = p_ud; + } + static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) { + if (dep_err_notify) dep_err_notify(dep_err_notify_ud, p_path, p_dependency, p_type); + } + static void set_dependency_error_notify_func(void *p_ud, DependencyErrorNotify p_err_notify) { + dep_err_notify = p_err_notify; + dep_err_notify_ud = p_ud; + } - static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource=p_abort; } + static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; } static bool get_abort_on_missing_resources() { return abort_on_missing_resource; } }; diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp index 704603f9f..610e21427 100644 --- a/core/io/resource_saver.cpp +++ b/core/io/resource_saver.cpp @@ -29,62 +29,61 @@ #include "resource_saver.h" #include "globals.h" #include "os/file_access.h" -#include "script_language.h" #include "resource_loader.h" +#include "script_language.h" ResourceFormatSaver *ResourceSaver::saver[MAX_SAVERS]; -int ResourceSaver::saver_count=0; -bool ResourceSaver::timestamp_on_save=false; -ResourceSavedCallback ResourceSaver::save_callback=0; +int ResourceSaver::saver_count = 0; +bool ResourceSaver::timestamp_on_save = false; +ResourceSavedCallback ResourceSaver::save_callback = 0; -Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - String extension=p_path.extension(); - Error err=ERR_FILE_UNRECOGNIZED; + String extension = p_path.extension(); + Error err = ERR_FILE_UNRECOGNIZED; - for (int i=0;i<saver_count;i++) { + for (int i = 0; i < saver_count; i++) { if (!saver[i]->recognize(p_resource)) continue; List<String> extensions; - bool recognized=false; - saver[i]->get_recognized_extensions(p_resource,&extensions); + bool recognized = false; + saver[i]->get_recognized_extensions(p_resource, &extensions); - for (List<String>::Element *E=extensions.front();E;E=E->next()) { + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { - if (E->get().nocasecmp_to(extension.extension())==0) - recognized=true; + if (E->get().nocasecmp_to(extension.extension()) == 0) + recognized = true; } if (!recognized) continue; - String old_path=p_resource->get_path(); + String old_path = p_resource->get_path(); - - String local_path=Globals::get_singleton()->localize_path(p_path); + String local_path = Globals::get_singleton()->localize_path(p_path); RES rwcopy = p_resource; - if (p_flags&FLAG_CHANGE_PATH) + if (p_flags & FLAG_CHANGE_PATH) rwcopy->set_path(local_path); - err = saver[i]->save(p_path,p_resource,p_flags); + err = saver[i]->save(p_path, p_resource, p_flags); - if (err == OK ) { + if (err == OK) { #ifdef TOOLS_ENABLED - ((Resource*)p_resource.ptr())->set_edited(false); + ((Resource *)p_resource.ptr())->set_edited(false); if (timestamp_on_save) { uint64_t mt = FileAccess::get_modified_time(p_path); - ((Resource*)p_resource.ptr())->set_last_modified_time(mt); + ((Resource *)p_resource.ptr())->set_last_modified_time(mt); } #endif - if (p_flags&FLAG_CHANGE_PATH) + if (p_flags & FLAG_CHANGE_PATH) rwcopy->set_path(old_path); if (save_callback && p_path.begins_with("res://")) @@ -92,46 +91,36 @@ Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_ return OK; } else { - } } return err; } - void ResourceSaver::set_save_callback(ResourceSavedCallback p_callback) { - save_callback=p_callback; + save_callback = p_callback; } +void ResourceSaver::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) { -void ResourceSaver::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) { - - - for (int i=0;i<saver_count;i++) { + for (int i = 0; i < saver_count; i++) { - saver[i]->get_recognized_extensions(p_resource,p_extensions); + saver[i]->get_recognized_extensions(p_resource, p_extensions); } - } void ResourceSaver::add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front) { - ERR_FAIL_COND( saver_count >= MAX_SAVERS ); + ERR_FAIL_COND(saver_count >= MAX_SAVERS); if (p_at_front) { - for(int i=saver_count;i>0;i--) { - saver[i]=saver[i-1]; + for (int i = saver_count; i > 0; i--) { + saver[i] = saver[i - 1]; } - saver[0]=p_format_saver; + saver[0] = p_format_saver; saver_count++; } else { - saver[saver_count++]=p_format_saver; + saver[saver_count++] = p_format_saver; } - } - - - - diff --git a/core/io/resource_saver.h b/core/io/resource_saver.h index f00f07409..b9bb2aafa 100644 --- a/core/io/resource_saver.h +++ b/core/io/resource_saver.h @@ -35,27 +35,21 @@ @author Juan Linietsky <reduzio@gmail.com> */ - - - - - class ResourceFormatSaver { public: - - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0)=0; - virtual bool recognize(const RES& p_resource) const=0; - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const=0; + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0) = 0; + virtual bool recognize(const RES &p_resource) const = 0; + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const = 0; virtual ~ResourceFormatSaver() {} }; -typedef void (*ResourceSavedCallback)(const String& p_path); +typedef void (*ResourceSavedCallback)(const String &p_path); class ResourceSaver { enum { - MAX_SAVERS=64 + MAX_SAVERS = 64 }; static ResourceFormatSaver *saver[MAX_SAVERS]; @@ -63,31 +57,24 @@ class ResourceSaver { static bool timestamp_on_save; static ResourceSavedCallback save_callback; - public: - enum SaverFlags { - FLAG_RELATIVE_PATHS=1, - FLAG_BUNDLE_RESOURCES=2, - FLAG_CHANGE_PATH=4, - FLAG_OMIT_EDITOR_PROPERTIES=8, - FLAG_SAVE_BIG_ENDIAN=16, - FLAG_COMPRESS=32, - FLAG_REPLACE_SUBRESOURCE_PATHS=64, + FLAG_RELATIVE_PATHS = 1, + FLAG_BUNDLE_RESOURCES = 2, + FLAG_CHANGE_PATH = 4, + FLAG_OMIT_EDITOR_PROPERTIES = 8, + FLAG_SAVE_BIG_ENDIAN = 16, + FLAG_COMPRESS = 32, + FLAG_REPLACE_SUBRESOURCE_PATHS = 64, }; + static Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + static void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions); + static void add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front = false); - static Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - static void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions); - static void add_resource_format_saver(ResourceFormatSaver *p_format_saver,bool p_at_front=false); - - static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save=p_timestamp; } + static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save = p_timestamp; } static void set_save_callback(ResourceSavedCallback p_callback); - - - }; - #endif diff --git a/core/io/stream_peer.cpp b/core/io/stream_peer.cpp index d9ef6137c..72e649526 100644 --- a/core/io/stream_peer.cpp +++ b/core/io/stream_peer.cpp @@ -29,21 +29,21 @@ #include "stream_peer.h" #include "io/marshalls.h" -Error StreamPeer::_put_data(const DVector<uint8_t>& p_data) { +Error StreamPeer::_put_data(const DVector<uint8_t> &p_data) { int len = p_data.size(); - if (len==0) + if (len == 0) return OK; DVector<uint8_t>::Read r = p_data.read(); - return put_data(&r[0],len); + return put_data(&r[0], len); } -Array StreamPeer::_put_partial_data(const DVector<uint8_t>& p_data) { +Array StreamPeer::_put_partial_data(const DVector<uint8_t> &p_data) { Array ret; int len = p_data.size(); - if (len==0) { + if (len == 0) { ret.push_back(OK); ret.push_back(0); return ret; @@ -51,24 +51,23 @@ Array StreamPeer::_put_partial_data(const DVector<uint8_t>& p_data) { DVector<uint8_t>::Read r = p_data.read(); int sent; - Error err = put_partial_data(&r[0],len,sent); + Error err = put_partial_data(&r[0], len, sent); - if (err!=OK) { - sent=0; + if (err != OK) { + sent = 0; } ret.push_back(err); ret.push_back(sent); return ret; } - Array StreamPeer::_get_data(int p_bytes) { Array ret; DVector<uint8_t> data; data.resize(p_bytes); - if (data.size()!=p_bytes) { + if (data.size() != p_bytes) { ret.push_back(ERR_OUT_OF_MEMORY); ret.push_back(DVector<uint8_t>()); @@ -76,12 +75,11 @@ Array StreamPeer::_get_data(int p_bytes) { } DVector<uint8_t>::Write w = data.write(); - Error err = get_data(&w[0],p_bytes); + Error err = get_data(&w[0], p_bytes); w = DVector<uint8_t>::Write(); ret.push_back(err); ret.push_back(data); return ret; - } Array StreamPeer::_get_partial_data(int p_bytes) { @@ -90,7 +88,7 @@ Array StreamPeer::_get_partial_data(int p_bytes) { DVector<uint8_t> data; data.resize(p_bytes); - if (data.size()!=p_bytes) { + if (data.size() != p_bytes) { ret.push_back(ERR_OUT_OF_MEMORY); ret.push_back(DVector<uint8_t>()); @@ -99,12 +97,12 @@ Array StreamPeer::_get_partial_data(int p_bytes) { DVector<uint8_t>::Write w = data.write(); int received; - Error err = get_partial_data(&w[0],p_bytes,received); + Error err = get_partial_data(&w[0], p_bytes, received); w = DVector<uint8_t>::Write(); - if (err!=OK) { + if (err != OK) { data.resize(0); - } else if (received!=data.size()) { + } else if (received != data.size()) { data.resize(received); } @@ -112,12 +110,11 @@ Array StreamPeer::_get_partial_data(int p_bytes) { ret.push_back(err); ret.push_back(data); return ret; - } void StreamPeer::set_big_endian(bool p_enable) { - big_endian=p_enable; + big_endian = p_enable; } bool StreamPeer::is_big_endian_enabled() const { @@ -125,298 +122,274 @@ bool StreamPeer::is_big_endian_enabled() const { return big_endian; } - void StreamPeer::put_u8(uint8_t p_val) { - put_data((const uint8_t*)&p_val,1); - + put_data((const uint8_t *)&p_val, 1); } -void StreamPeer::put_8(int8_t p_val){ +void StreamPeer::put_8(int8_t p_val) { - put_data((const uint8_t*)&p_val,1); + put_data((const uint8_t *)&p_val, 1); } -void StreamPeer::put_u16(uint16_t p_val){ +void StreamPeer::put_u16(uint16_t p_val) { if (big_endian) { - p_val=BSWAP16(p_val); + p_val = BSWAP16(p_val); } uint8_t buf[2]; - encode_uint16(p_val,buf); - put_data(buf,2); - + encode_uint16(p_val, buf); + put_data(buf, 2); } -void StreamPeer::put_16(int16_t p_val){ +void StreamPeer::put_16(int16_t p_val) { if (big_endian) { - p_val=BSWAP16(p_val); + p_val = BSWAP16(p_val); } uint8_t buf[2]; - encode_uint16(p_val,buf); - put_data(buf,2); - + encode_uint16(p_val, buf); + put_data(buf, 2); } -void StreamPeer::put_u32(uint32_t p_val){ +void StreamPeer::put_u32(uint32_t p_val) { if (big_endian) { - p_val=BSWAP32(p_val); + p_val = BSWAP32(p_val); } uint8_t buf[4]; - encode_uint32(p_val,buf); - put_data(buf,4); - + encode_uint32(p_val, buf); + put_data(buf, 4); } -void StreamPeer::put_32(int32_t p_val){ +void StreamPeer::put_32(int32_t p_val) { if (big_endian) { - p_val=BSWAP32(p_val); + p_val = BSWAP32(p_val); } uint8_t buf[4]; - encode_uint32(p_val,buf); - put_data(buf,4); - + encode_uint32(p_val, buf); + put_data(buf, 4); } -void StreamPeer::put_u64(uint64_t p_val){ +void StreamPeer::put_u64(uint64_t p_val) { if (big_endian) { - p_val=BSWAP64(p_val); + p_val = BSWAP64(p_val); } uint8_t buf[8]; - encode_uint64(p_val,buf); - put_data(buf,8); - + encode_uint64(p_val, buf); + put_data(buf, 8); } -void StreamPeer::put_64(int64_t p_val){ +void StreamPeer::put_64(int64_t p_val) { if (big_endian) { - p_val=BSWAP64(p_val); + p_val = BSWAP64(p_val); } uint8_t buf[8]; - encode_uint64(p_val,buf); - put_data(buf,8); - + encode_uint64(p_val, buf); + put_data(buf, 8); } -void StreamPeer::put_float(float p_val){ +void StreamPeer::put_float(float p_val) { uint8_t buf[4]; - encode_float(p_val,buf); + encode_float(p_val, buf); if (big_endian) { - uint32_t *p32=(uint32_t *)buf; - *p32=BSWAP32(*p32); + uint32_t *p32 = (uint32_t *)buf; + *p32 = BSWAP32(*p32); } - put_data(buf,4); - + put_data(buf, 4); } -void StreamPeer::put_double(double p_val){ +void StreamPeer::put_double(double p_val) { uint8_t buf[8]; - encode_double(p_val,buf); + encode_double(p_val, buf); if (big_endian) { - uint64_t *p64=(uint64_t *)buf; - *p64=BSWAP64(*p64); + uint64_t *p64 = (uint64_t *)buf; + *p64 = BSWAP64(*p64); } - put_data(buf,8); - + put_data(buf, 8); } -void StreamPeer::put_utf8_string(const String& p_string) { - - CharString cs=p_string.utf8(); - put_data((const uint8_t*)cs.get_data(),cs.length()); +void StreamPeer::put_utf8_string(const String &p_string) { + CharString cs = p_string.utf8(); + put_data((const uint8_t *)cs.get_data(), cs.length()); } -void StreamPeer::put_var(const Variant& p_variant){ +void StreamPeer::put_var(const Variant &p_variant) { - int len=0; + int len = 0; Vector<uint8_t> buf; - encode_variant(p_variant,NULL,len); + encode_variant(p_variant, NULL, len); buf.resize(len); put_32(len); - encode_variant(p_variant,buf.ptr(),len); - put_data(buf.ptr(),buf.size()); - - + encode_variant(p_variant, buf.ptr(), len); + put_data(buf.ptr(), buf.size()); } -uint8_t StreamPeer::get_u8(){ +uint8_t StreamPeer::get_u8() { uint8_t buf[1]; - get_data(buf,1); + get_data(buf, 1); return buf[0]; } -int8_t StreamPeer::get_8(){ +int8_t StreamPeer::get_8() { uint8_t buf[1]; - get_data(buf,1); + get_data(buf, 1); return buf[0]; - } -uint16_t StreamPeer::get_u16(){ +uint16_t StreamPeer::get_u16() { uint8_t buf[2]; - get_data(buf,2); + get_data(buf, 2); uint16_t r = decode_uint16(buf); if (big_endian) { - r=BSWAP16(r); + r = BSWAP16(r); } return r; - } -int16_t StreamPeer::get_16(){ +int16_t StreamPeer::get_16() { uint8_t buf[2]; - get_data(buf,2); + get_data(buf, 2); uint16_t r = decode_uint16(buf); if (big_endian) { - r=BSWAP16(r); + r = BSWAP16(r); } return r; - } -uint32_t StreamPeer::get_u32(){ +uint32_t StreamPeer::get_u32() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); uint32_t r = decode_uint32(buf); if (big_endian) { - r=BSWAP32(r); + r = BSWAP32(r); } return r; - } -int32_t StreamPeer::get_32(){ +int32_t StreamPeer::get_32() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); uint32_t r = decode_uint32(buf); if (big_endian) { - r=BSWAP32(r); + r = BSWAP32(r); } return r; - } -uint64_t StreamPeer::get_u64(){ +uint64_t StreamPeer::get_u64() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); uint64_t r = decode_uint64(buf); if (big_endian) { - r=BSWAP64(r); + r = BSWAP64(r); } return r; - } -int64_t StreamPeer::get_64(){ +int64_t StreamPeer::get_64() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); uint64_t r = decode_uint64(buf); if (big_endian) { - r=BSWAP64(r); + r = BSWAP64(r); } return r; - } -float StreamPeer::get_float(){ +float StreamPeer::get_float() { uint8_t buf[4]; - get_data(buf,4); + get_data(buf, 4); if (big_endian) { - uint32_t *p32=(uint32_t *)buf; - *p32=BSWAP32(*p32); + uint32_t *p32 = (uint32_t *)buf; + *p32 = BSWAP32(*p32); } return decode_float(buf); } -float StreamPeer::get_double(){ +float StreamPeer::get_double() { uint8_t buf[8]; - get_data(buf,8); + get_data(buf, 8); if (big_endian) { - uint64_t *p64=(uint64_t *)buf; - *p64=BSWAP64(*p64); + uint64_t *p64 = (uint64_t *)buf; + *p64 = BSWAP64(*p64); } return decode_double(buf); - } -String StreamPeer::get_string(int p_bytes){ +String StreamPeer::get_string(int p_bytes) { - ERR_FAIL_COND_V(p_bytes<0,String()); + ERR_FAIL_COND_V(p_bytes < 0, String()); Vector<char> buf; - buf.resize(p_bytes+1); - get_data((uint8_t*)&buf[0],p_bytes); - buf[p_bytes]=0; + buf.resize(p_bytes + 1); + get_data((uint8_t *)&buf[0], p_bytes); + buf[p_bytes] = 0; return buf.ptr(); - } -String StreamPeer::get_utf8_string(int p_bytes){ +String StreamPeer::get_utf8_string(int p_bytes) { - ERR_FAIL_COND_V(p_bytes<0,String()); + ERR_FAIL_COND_V(p_bytes < 0, String()); Vector<uint8_t> buf; buf.resize(p_bytes); - get_data(buf.ptr(),p_bytes); + get_data(buf.ptr(), p_bytes); String ret; - ret.parse_utf8((const char*)buf.ptr(),buf.size()); + ret.parse_utf8((const char *)buf.ptr(), buf.size()); return ret; - } -Variant StreamPeer::get_var(){ +Variant StreamPeer::get_var() { int len = get_32(); Vector<uint8_t> var; var.resize(len); - get_data(var.ptr(),len); + get_data(var.ptr(), len); Variant ret; - decode_variant(ret,var.ptr(),len); + decode_variant(ret, var.ptr(), len); return ret; } - void StreamPeer::_bind_methods() { - ObjectTypeDB::bind_method(_MD("put_data","data"),&StreamPeer::_put_data); - ObjectTypeDB::bind_method(_MD("put_partial_data","data"),&StreamPeer::_put_partial_data); + ObjectTypeDB::bind_method(_MD("put_data", "data"), &StreamPeer::_put_data); + ObjectTypeDB::bind_method(_MD("put_partial_data", "data"), &StreamPeer::_put_partial_data); - ObjectTypeDB::bind_method(_MD("get_data","bytes"),&StreamPeer::_get_data); - ObjectTypeDB::bind_method(_MD("get_partial_data","bytes"),&StreamPeer::_get_partial_data); + ObjectTypeDB::bind_method(_MD("get_data", "bytes"), &StreamPeer::_get_data); + ObjectTypeDB::bind_method(_MD("get_partial_data", "bytes"), &StreamPeer::_get_partial_data); - ObjectTypeDB::bind_method(_MD("get_available_bytes"),&StreamPeer::get_available_bytes); + ObjectTypeDB::bind_method(_MD("get_available_bytes"), &StreamPeer::get_available_bytes); - ObjectTypeDB::bind_method(_MD("set_big_endian","enable"),&StreamPeer::set_big_endian); - ObjectTypeDB::bind_method(_MD("is_big_endian_enabled"),&StreamPeer::is_big_endian_enabled); + ObjectTypeDB::bind_method(_MD("set_big_endian", "enable"), &StreamPeer::set_big_endian); + ObjectTypeDB::bind_method(_MD("is_big_endian_enabled"), &StreamPeer::is_big_endian_enabled); - ObjectTypeDB::bind_method(_MD("put_8","val"),&StreamPeer::put_8); - ObjectTypeDB::bind_method(_MD("put_u8","val"),&StreamPeer::put_u8); - ObjectTypeDB::bind_method(_MD("put_16","val"),&StreamPeer::put_16); - ObjectTypeDB::bind_method(_MD("put_u16","val"),&StreamPeer::put_u16); - ObjectTypeDB::bind_method(_MD("put_32","val"),&StreamPeer::put_32); - ObjectTypeDB::bind_method(_MD("put_u32","val"),&StreamPeer::put_u32); - ObjectTypeDB::bind_method(_MD("put_64","val"),&StreamPeer::put_64); - ObjectTypeDB::bind_method(_MD("put_u64","val"),&StreamPeer::put_u64); - ObjectTypeDB::bind_method(_MD("put_float","val"),&StreamPeer::put_float); - ObjectTypeDB::bind_method(_MD("put_double","val"),&StreamPeer::put_double); - ObjectTypeDB::bind_method(_MD("put_utf8_string","val"),&StreamPeer::put_utf8_string); - ObjectTypeDB::bind_method(_MD("put_var","val:Variant"),&StreamPeer::put_var); + ObjectTypeDB::bind_method(_MD("put_8", "val"), &StreamPeer::put_8); + ObjectTypeDB::bind_method(_MD("put_u8", "val"), &StreamPeer::put_u8); + ObjectTypeDB::bind_method(_MD("put_16", "val"), &StreamPeer::put_16); + ObjectTypeDB::bind_method(_MD("put_u16", "val"), &StreamPeer::put_u16); + ObjectTypeDB::bind_method(_MD("put_32", "val"), &StreamPeer::put_32); + ObjectTypeDB::bind_method(_MD("put_u32", "val"), &StreamPeer::put_u32); + ObjectTypeDB::bind_method(_MD("put_64", "val"), &StreamPeer::put_64); + ObjectTypeDB::bind_method(_MD("put_u64", "val"), &StreamPeer::put_u64); + ObjectTypeDB::bind_method(_MD("put_float", "val"), &StreamPeer::put_float); + ObjectTypeDB::bind_method(_MD("put_double", "val"), &StreamPeer::put_double); + ObjectTypeDB::bind_method(_MD("put_utf8_string", "val"), &StreamPeer::put_utf8_string); + ObjectTypeDB::bind_method(_MD("put_var", "val:Variant"), &StreamPeer::put_var); - ObjectTypeDB::bind_method(_MD("get_8"),&StreamPeer::get_8); - ObjectTypeDB::bind_method(_MD("get_u8"),&StreamPeer::get_u8); - ObjectTypeDB::bind_method(_MD("get_16"),&StreamPeer::get_16); - ObjectTypeDB::bind_method(_MD("get_u16"),&StreamPeer::get_u16); - ObjectTypeDB::bind_method(_MD("get_32"),&StreamPeer::get_32); - ObjectTypeDB::bind_method(_MD("get_u32"),&StreamPeer::get_u32); - ObjectTypeDB::bind_method(_MD("get_64"),&StreamPeer::get_64); - ObjectTypeDB::bind_method(_MD("get_u64"),&StreamPeer::get_u64); - ObjectTypeDB::bind_method(_MD("get_float"),&StreamPeer::get_float); - ObjectTypeDB::bind_method(_MD("get_double"),&StreamPeer::get_double); - ObjectTypeDB::bind_method(_MD("get_string","bytes"),&StreamPeer::get_string); - ObjectTypeDB::bind_method(_MD("get_utf8_string","bytes"),&StreamPeer::get_utf8_string); - ObjectTypeDB::bind_method(_MD("get_var:Variant"),&StreamPeer::get_var); + ObjectTypeDB::bind_method(_MD("get_8"), &StreamPeer::get_8); + ObjectTypeDB::bind_method(_MD("get_u8"), &StreamPeer::get_u8); + ObjectTypeDB::bind_method(_MD("get_16"), &StreamPeer::get_16); + ObjectTypeDB::bind_method(_MD("get_u16"), &StreamPeer::get_u16); + ObjectTypeDB::bind_method(_MD("get_32"), &StreamPeer::get_32); + ObjectTypeDB::bind_method(_MD("get_u32"), &StreamPeer::get_u32); + ObjectTypeDB::bind_method(_MD("get_64"), &StreamPeer::get_64); + ObjectTypeDB::bind_method(_MD("get_u64"), &StreamPeer::get_u64); + ObjectTypeDB::bind_method(_MD("get_float"), &StreamPeer::get_float); + ObjectTypeDB::bind_method(_MD("get_double"), &StreamPeer::get_double); + ObjectTypeDB::bind_method(_MD("get_string", "bytes"), &StreamPeer::get_string); + ObjectTypeDB::bind_method(_MD("get_utf8_string", "bytes"), &StreamPeer::get_utf8_string); + ObjectTypeDB::bind_method(_MD("get_var:Variant"), &StreamPeer::get_var); } diff --git a/core/io/stream_peer.h b/core/io/stream_peer.h index 264c5c795..ac66813e1 100644 --- a/core/io/stream_peer.h +++ b/core/io/stream_peer.h @@ -32,14 +32,15 @@ #include "reference.h" class StreamPeer : public Reference { - OBJ_TYPE( StreamPeer, Reference ); + OBJ_TYPE(StreamPeer, Reference); OBJ_CATEGORY("Networking"); + protected: static void _bind_methods(); //bind helpers - Error _put_data(const DVector<uint8_t>& p_data); - Array _put_partial_data(const DVector<uint8_t>& p_data); + Error _put_data(const DVector<uint8_t> &p_data); + Array _put_partial_data(const DVector<uint8_t> &p_data); Array _get_data(int p_bytes); Array _get_partial_data(int p_bytes); @@ -47,14 +48,13 @@ protected: bool big_endian; public: + virtual Error put_data(const uint8_t *p_data, int p_bytes) = 0; ///< put a whole chunk of data, blocking until it sent + virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) = 0; ///< put as much data as possible, without blocking. - virtual Error put_data(const uint8_t* p_data,int p_bytes)=0; ///< put a whole chunk of data, blocking until it sent - virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent)=0; ///< put as much data as possible, without blocking. - - virtual Error get_data(uint8_t* p_buffer, int p_bytes)=0; ///< read p_bytes of data, if p_bytes > available, it will block - virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received)=0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received + virtual Error get_data(uint8_t *p_buffer, int p_bytes) = 0; ///< read p_bytes of data, if p_bytes > available, it will block + virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) = 0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received - virtual int get_available_bytes() const=0; + virtual int get_available_bytes() const = 0; void set_big_endian(bool p_enable); bool is_big_endian_enabled() const; @@ -69,8 +69,8 @@ public: void put_u64(uint64_t p_val); void put_float(float p_val); void put_double(double p_val); - void put_utf8_string(const String& p_string); - void put_var(const Variant& p_variant); + void put_utf8_string(const String &p_string); + void put_var(const Variant &p_variant); uint8_t get_u8(); int8_t get_8(); @@ -86,9 +86,7 @@ public: String get_utf8_string(int p_bytes); Variant get_var(); - - - StreamPeer() { big_endian=false; } + StreamPeer() { big_endian = false; } }; #endif // STREAM_PEER_H diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp index a93679156..68df54e13 100644 --- a/core/io/stream_peer_ssl.cpp +++ b/core/io/stream_peer_ssl.cpp @@ -28,24 +28,18 @@ /*************************************************************************/ #include "stream_peer_ssl.h" - -StreamPeerSSL* (*StreamPeerSSL::_create)()=NULL; - - - +StreamPeerSSL *(*StreamPeerSSL::_create)() = NULL; StreamPeerSSL *StreamPeerSSL::create() { return _create(); } +StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func = NULL; +bool StreamPeerSSL::available = false; +bool StreamPeerSSL::initialize_certs = true; - -StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func=NULL; -bool StreamPeerSSL::available=false; -bool StreamPeerSSL::initialize_certs=true; - -void StreamPeerSSL::load_certs_from_memory(const ByteArray& p_memory) { +void StreamPeerSSL::load_certs_from_memory(const ByteArray &p_memory) { if (load_certs_func) load_certs_func(p_memory); } @@ -56,18 +50,15 @@ bool StreamPeerSSL::is_available() { void StreamPeerSSL::_bind_methods() { - - ObjectTypeDB::bind_method(_MD("accept:Error","stream:StreamPeer"),&StreamPeerSSL::accept); - ObjectTypeDB::bind_method(_MD("connect:Error","stream:StreamPeer","validate_certs","for_hostname"),&StreamPeerSSL::connect,DEFVAL(false),DEFVAL(String())); - ObjectTypeDB::bind_method(_MD("get_status"),&StreamPeerSSL::get_status); - ObjectTypeDB::bind_method(_MD("disconnect"),&StreamPeerSSL::disconnect); - BIND_CONSTANT( STATUS_DISCONNECTED ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR_NO_CERTIFICATE ); - BIND_CONSTANT( STATUS_ERROR_HOSTNAME_MISMATCH ); - + ObjectTypeDB::bind_method(_MD("accept:Error", "stream:StreamPeer"), &StreamPeerSSL::accept); + ObjectTypeDB::bind_method(_MD("connect:Error", "stream:StreamPeer", "validate_certs", "for_hostname"), &StreamPeerSSL::connect, DEFVAL(false), DEFVAL(String())); + ObjectTypeDB::bind_method(_MD("get_status"), &StreamPeerSSL::get_status); + ObjectTypeDB::bind_method(_MD("disconnect"), &StreamPeerSSL::disconnect); + BIND_CONSTANT(STATUS_DISCONNECTED); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR_NO_CERTIFICATE); + BIND_CONSTANT(STATUS_ERROR_HOSTNAME_MISMATCH); } -StreamPeerSSL::StreamPeerSSL() -{ +StreamPeerSSL::StreamPeerSSL() { } diff --git a/core/io/stream_peer_ssl.h b/core/io/stream_peer_ssl.h index 2e9ba5264..baa37d1e9 100644 --- a/core/io/stream_peer_ssl.h +++ b/core/io/stream_peer_ssl.h @@ -32,24 +32,22 @@ #include "io/stream_peer.h" class StreamPeerSSL : public StreamPeer { - OBJ_TYPE(StreamPeerSSL,StreamPeer); + OBJ_TYPE(StreamPeerSSL, StreamPeer); + public: + typedef void (*LoadCertsFromMemory)(const ByteArray &p_certs); - typedef void (*LoadCertsFromMemory)(const ByteArray& p_certs); protected: - static StreamPeerSSL* (*_create)(); + static StreamPeerSSL *(*_create)(); static void _bind_methods(); static LoadCertsFromMemory load_certs_func; static bool available; - -friend class Main; + friend class Main; static bool initialize_certs; public: - - enum Status { STATUS_DISCONNECTED, STATUS_CONNECTED, @@ -57,20 +55,20 @@ public: STATUS_ERROR_HOSTNAME_MISMATCH }; - virtual Error accept(Ref<StreamPeer> p_base)=0; - virtual Error connect(Ref<StreamPeer> p_base,bool p_validate_certs=false,const String& p_for_hostname=String())=0; - virtual Status get_status() const=0; + virtual Error accept(Ref<StreamPeer> p_base) = 0; + virtual Error connect(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0; + virtual Status get_status() const = 0; - virtual void disconnect()=0; + virtual void disconnect() = 0; - static StreamPeerSSL* create(); + static StreamPeerSSL *create(); - static void load_certs_from_memory(const ByteArray& p_memory); + static void load_certs_from_memory(const ByteArray &p_memory); static bool is_available(); StreamPeerSSL(); }; -VARIANT_ENUM_CAST( StreamPeerSSL::Status ); +VARIANT_ENUM_CAST(StreamPeerSSL::Status); #endif // STREAM_PEER_SSL_H diff --git a/core/io/stream_peer_tcp.cpp b/core/io/stream_peer_tcp.cpp index 52cc11a4a..753d66734 100644 --- a/core/io/stream_peer_tcp.cpp +++ b/core/io/stream_peer_tcp.cpp @@ -28,20 +28,20 @@ /*************************************************************************/ #include "stream_peer_tcp.h" -StreamPeerTCP* (*StreamPeerTCP::_create)()=NULL; +StreamPeerTCP *(*StreamPeerTCP::_create)() = NULL; -Error StreamPeerTCP::_connect(const String& p_address,int p_port) { +Error StreamPeerTCP::_connect(const String &p_address, int p_port) { IP_Address ip; if (p_address.is_valid_ip_address()) { - ip=p_address; + ip = p_address; } else { - ip=IP::get_singleton()->resolve_hostname(p_address, ip_type); - if (ip==IP_Address()) + ip = IP::get_singleton()->resolve_hostname(p_address, ip_type); + if (ip == IP_Address()) return ERR_CANT_RESOLVE; } - connect(ip,p_port); + connect(ip, p_port); return OK; } @@ -52,19 +52,18 @@ void StreamPeerTCP::set_ip_type(IP::Type p_type) { void StreamPeerTCP::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&StreamPeerTCP::set_ip_type); - ObjectTypeDB::bind_method(_MD("connect","host","port"),&StreamPeerTCP::_connect); - ObjectTypeDB::bind_method(_MD("is_connected"),&StreamPeerTCP::is_connected); - ObjectTypeDB::bind_method(_MD("get_status"),&StreamPeerTCP::get_status); - ObjectTypeDB::bind_method(_MD("get_connected_host"),&StreamPeerTCP::get_connected_host); - ObjectTypeDB::bind_method(_MD("get_connected_port"),&StreamPeerTCP::get_connected_port); - ObjectTypeDB::bind_method(_MD("disconnect"),&StreamPeerTCP::disconnect); - - BIND_CONSTANT( STATUS_NONE ); - BIND_CONSTANT( STATUS_CONNECTING ); - BIND_CONSTANT( STATUS_CONNECTED ); - BIND_CONSTANT( STATUS_ERROR ); + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &StreamPeerTCP::set_ip_type); + ObjectTypeDB::bind_method(_MD("connect", "host", "port"), &StreamPeerTCP::_connect); + ObjectTypeDB::bind_method(_MD("is_connected"), &StreamPeerTCP::is_connected); + ObjectTypeDB::bind_method(_MD("get_status"), &StreamPeerTCP::get_status); + ObjectTypeDB::bind_method(_MD("get_connected_host"), &StreamPeerTCP::get_connected_host); + ObjectTypeDB::bind_method(_MD("get_connected_port"), &StreamPeerTCP::get_connected_port); + ObjectTypeDB::bind_method(_MD("disconnect"), &StreamPeerTCP::disconnect); + BIND_CONSTANT(STATUS_NONE); + BIND_CONSTANT(STATUS_CONNECTING); + BIND_CONSTANT(STATUS_CONNECTED); + BIND_CONSTANT(STATUS_ERROR); } Ref<StreamPeerTCP> StreamPeerTCP::create_ref() { @@ -74,7 +73,7 @@ Ref<StreamPeerTCP> StreamPeerTCP::create_ref() { return Ref<StreamPeerTCP>(_create()); } -StreamPeerTCP* StreamPeerTCP::create() { +StreamPeerTCP *StreamPeerTCP::create() { if (!_create) return NULL; @@ -86,7 +85,6 @@ StreamPeerTCP::StreamPeerTCP() { ip_type = IP::TYPE_ANY; } -StreamPeerTCP::~StreamPeerTCP() { +StreamPeerTCP::~StreamPeerTCP(){ }; - diff --git a/core/io/stream_peer_tcp.h b/core/io/stream_peer_tcp.h index abc5947ff..a97f42937 100644 --- a/core/io/stream_peer_tcp.h +++ b/core/io/stream_peer_tcp.h @@ -31,16 +31,15 @@ #include "stream_peer.h" -#include "ip_address.h" #include "io/ip.h" +#include "ip_address.h" class StreamPeerTCP : public StreamPeer { - OBJ_TYPE( StreamPeerTCP, StreamPeer ); + OBJ_TYPE(StreamPeerTCP, StreamPeer); OBJ_CATEGORY("Networking"); public: - enum Status { STATUS_NONE, @@ -50,34 +49,32 @@ public: }; protected: - IP::Type ip_type; - virtual Error _connect(const String& p_address, int p_port); - static StreamPeerTCP* (*_create)(); + virtual Error _connect(const String &p_address, int p_port); + static StreamPeerTCP *(*_create)(); static void _bind_methods(); public: - virtual void set_ip_type(IP::Type p_type); - virtual Error connect(const IP_Address& p_host, uint16_t p_port)=0; + virtual Error connect(const IP_Address &p_host, uint16_t p_port) = 0; //read/write from streampeer - virtual bool is_connected() const=0; - virtual Status get_status() const=0; - virtual void disconnect()=0; - virtual IP_Address get_connected_host() const=0; - virtual uint16_t get_connected_port() const=0; - virtual void set_nodelay(bool p_enabled)=0; + virtual bool is_connected() const = 0; + virtual Status get_status() const = 0; + virtual void disconnect() = 0; + virtual IP_Address get_connected_host() const = 0; + virtual uint16_t get_connected_port() const = 0; + virtual void set_nodelay(bool p_enabled) = 0; static Ref<StreamPeerTCP> create_ref(); - static StreamPeerTCP* create(); + static StreamPeerTCP *create(); StreamPeerTCP(); ~StreamPeerTCP(); }; -VARIANT_ENUM_CAST( StreamPeerTCP::Status ); +VARIANT_ENUM_CAST(StreamPeerTCP::Status); #endif diff --git a/core/io/tcp_server.cpp b/core/io/tcp_server.cpp index 431b17321..2b4206ba3 100644 --- a/core/io/tcp_server.cpp +++ b/core/io/tcp_server.cpp @@ -28,7 +28,7 @@ /*************************************************************************/ #include "tcp_server.h" -TCP_Server* (*TCP_Server::_create)()=NULL; +TCP_Server *(*TCP_Server::_create)() = NULL; Ref<TCP_Server> TCP_Server::create_ref() { @@ -37,7 +37,7 @@ Ref<TCP_Server> TCP_Server::create_ref() { return Ref<TCP_Server>(_create()); } -TCP_Server* TCP_Server::create() { +TCP_Server *TCP_Server::create() { if (!_create) return NULL; @@ -47,11 +47,10 @@ TCP_Server* TCP_Server::create() { Error TCP_Server::_listen(uint16_t p_port, DVector<String> p_accepted_hosts) { List<String> hosts; - for(int i=0;i<p_accepted_hosts.size();i++) + for (int i = 0; i < p_accepted_hosts.size(); i++) hosts.push_back(p_accepted_hosts.get(i)); - return listen(p_port, hosts.size()?&hosts:NULL); - + return listen(p_port, hosts.size() ? &hosts : NULL); } void TCP_Server::set_ip_type(IP::Type p_type) { @@ -61,16 +60,13 @@ void TCP_Server::set_ip_type(IP::Type p_type) { void TCP_Server::_bind_methods() { - ObjectTypeDB::bind_method(_MD("set_ip_type","ip_type"),&TCP_Server::set_ip_type); - ObjectTypeDB::bind_method(_MD("listen","port","accepted_hosts"),&TCP_Server::_listen,DEFVAL(DVector<String>())); - ObjectTypeDB::bind_method(_MD("is_connection_available"),&TCP_Server::is_connection_available); - ObjectTypeDB::bind_method(_MD("take_connection"),&TCP_Server::take_connection); - ObjectTypeDB::bind_method(_MD("stop"),&TCP_Server::stop); - + ObjectTypeDB::bind_method(_MD("set_ip_type", "ip_type"), &TCP_Server::set_ip_type); + ObjectTypeDB::bind_method(_MD("listen", "port", "accepted_hosts"), &TCP_Server::_listen, DEFVAL(DVector<String>())); + ObjectTypeDB::bind_method(_MD("is_connection_available"), &TCP_Server::is_connection_available); + ObjectTypeDB::bind_method(_MD("take_connection"), &TCP_Server::take_connection); + ObjectTypeDB::bind_method(_MD("stop"), &TCP_Server::stop); } - -TCP_Server::TCP_Server() -{ +TCP_Server::TCP_Server() { ip_type = IP::TYPE_ANY; } diff --git a/core/io/tcp_server.h b/core/io/tcp_server.h index 14153a332..481945b6d 100644 --- a/core/io/tcp_server.h +++ b/core/io/tcp_server.h @@ -29,33 +29,33 @@ #ifndef TCP_SERVER_H #define TCP_SERVER_H -#include "io/stream_peer.h" #include "io/ip.h" +#include "io/stream_peer.h" #include "stream_peer_tcp.h" class TCP_Server : public Reference { - OBJ_TYPE( TCP_Server, Reference ); -protected: + OBJ_TYPE(TCP_Server, Reference); +protected: IP::Type ip_type; - static TCP_Server* (*_create)(); + static TCP_Server *(*_create)(); //bind helper - Error _listen(uint16_t p_port, DVector<String> p_accepted_hosts=DVector<String>()); + Error _listen(uint16_t p_port, DVector<String> p_accepted_hosts = DVector<String>()); static void _bind_methods(); -public: +public: virtual void set_ip_type(IP::Type p_type); - virtual Error listen(uint16_t p_port, const List<String> *p_accepted_hosts=NULL)=0; - virtual bool is_connection_available() const=0; - virtual Ref<StreamPeerTCP> take_connection()=0; + virtual Error listen(uint16_t p_port, const List<String> *p_accepted_hosts = NULL) = 0; + virtual bool is_connection_available() const = 0; + virtual Ref<StreamPeerTCP> take_connection() = 0; - virtual void stop()=0; //stop listening + virtual void stop() = 0; //stop listening static Ref<TCP_Server> create_ref(); - static TCP_Server* create(); + static TCP_Server *create(); TCP_Server(); }; diff --git a/core/io/translation_loader_po.cpp b/core/io/translation_loader_po.cpp index 8c4c1c818..731a056e3 100644 --- a/core/io/translation_loader_po.cpp +++ b/core/io/translation_loader_po.cpp @@ -30,7 +30,6 @@ #include "os/file_access.h" #include "translation.h" - RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) { enum Status { @@ -40,175 +39,169 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S STATUS_READING_STRING, }; - Status status=STATUS_NONE; + Status status = STATUS_NONE; String msg_id; String msg_str; String config; if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; - Ref<Translation> translation = Ref<Translation>( memnew( Translation )); + Ref<Translation> translation = Ref<Translation>(memnew(Translation)); int line = 1; - while(true) { + while (true) { String l = f->get_line(); if (f->eof_reached()) { - if ( status == STATUS_READING_STRING) { + if (status == STATUS_READING_STRING) { - if (msg_id!="") - translation->add_message(msg_id,msg_str); - else if (config=="") - config=msg_str; + if (msg_id != "") + translation->add_message(msg_id, msg_str); + else if (config == "") + config = msg_str; break; - } else if ( status==STATUS_NONE) + } else if (status == STATUS_NONE) break; memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected EOF while reading 'msgid' at file: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: "); ERR_FAIL_V(RES()); } - l=l.strip_edges(); + l = l.strip_edges(); if (l.begins_with("msgid")) { - if (status==STATUS_READING_ID) { + if (status == STATUS_READING_ID) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgid', was expecting 'msgstr' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: "); ERR_FAIL_V(RES()); } - if (msg_id!="") - translation->add_message(msg_id,msg_str); - else if (config=="") - config=msg_str; + if (msg_id != "") + 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=""; + l = l.substr(5, l.length()).strip_edges(); + status = STATUS_READING_ID; + msg_id = ""; + msg_str = ""; } if (l.begins_with("msgstr")) { - if (status!=STATUS_READING_ID) { + if (status != STATUS_READING_ID) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgstr', was expecting 'msgid' while parsing: "); + 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; + l = l.substr(6, l.length()).strip_edges(); + status = STATUS_READING_STRING; } - if (l=="" || l.begins_with("#")) { + if (l == "" || l.begins_with("#")) { line++; continue; //nothing to read or comment } - if (!l.begins_with("\"") || status==STATUS_NONE) { + if (!l.begins_with("\"") || status == STATUS_NONE) { //not a string? failure! - ERR_EXPLAIN(p_path+":"+itos(line)+" Invalid line '"+l+"' while parsing: "); + ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: "); ERR_FAIL_V(RES()); - } - l=l.substr(1,l.length()); + l = l.substr(1, l.length()); //find final quote - int end_pos=-1; - for(int i=0;i<l.length();i++) { + int end_pos = -1; + for (int i = 0; i < l.length(); i++) { - if (l[i]=='"' && (i==0 || l[i-1]!='\\')) { - end_pos=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: "); + 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(); - + l = l.substr(0, end_pos); + l = l.c_unescape(); - if (status==STATUS_READING_ID) - msg_id+=l; + if (status == STATUS_READING_ID) + msg_id += l; else - msg_str+=l; + msg_str += l; line++; } - f->close(); memdelete(f); - if (config=="") { - ERR_EXPLAIN("No config found in file: "+p_path); + 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++) { + for (int i = 0; i < configs.size(); i++) { String c = configs[i].strip_edges(); int p = c.find(":"); - if (p==-1) + if (p == -1) continue; - String prop = c.substr(0,p).strip_edges(); - String value = c.substr(p+1,c.length()).strip_edges(); + String prop = c.substr(0, p).strip_edges(); + String value = c.substr(p + 1, c.length()).strip_edges(); - if (prop=="X-Language") { + if (prop == "X-Language") { translation->set_locale(value); } } if (r_error) - *r_error=OK; + *r_error = OK; return translation; } -RES TranslationLoaderPO::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_CANT_OPEN; - - FileAccess *f=FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,RES()); - + *r_error = ERR_CANT_OPEN; - return load_translation(f,r_error); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, RES()); + return load_translation(f, r_error); } -void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const{ +void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("po"); //p_extensions->push_back("mo"); //mo in the future... } -bool TranslationLoaderPO::handles_type(const String& p_type) const{ +bool TranslationLoaderPO::handles_type(const String &p_type) const { - return (p_type=="Translation"); + return (p_type == "Translation"); } String TranslationLoaderPO::get_resource_type(const String &p_path) const { - if (p_path.extension().to_lower()=="po") + if (p_path.extension().to_lower() == "po") return "Translation"; return ""; } -TranslationLoaderPO::TranslationLoaderPO() -{ +TranslationLoaderPO::TranslationLoaderPO() { } diff --git a/core/io/translation_loader_po.h b/core/io/translation_loader_po.h index 127c8dafa..fe0440cb2 100644 --- a/core/io/translation_loader_po.h +++ b/core/io/translation_loader_po.h @@ -30,18 +30,16 @@ #define TRANSLATION_LOADER_PO_H #include "io/resource_loader.h" -#include "translation.h" #include "os/file_access.h" +#include "translation.h" class TranslationLoaderPO : public ResourceFormatLoader { public: - - static RES load_translation(FileAccess *f, Error *r_error,const String& p_path=String()); - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + static RES load_translation(FileAccess *f, Error *r_error, const String &p_path = String()); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - TranslationLoaderPO(); }; diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp index 9e194d105..a93e3b2cf 100644 --- a/core/io/xml_parser.cpp +++ b/core/io/xml_parser.cpp @@ -32,19 +32,18 @@ VARIANT_ENUM_CAST(XMLParser::NodeType); -static bool _equalsn(const CharType* str1, const CharType* str2, int len) { +static bool _equalsn(const CharType *str1, const CharType *str2, int len) { int i; - for(i=0; i < len && str1[i] && str2[i] ; ++i) - if (str1[i] != str2[i]) - return false; + for (i = 0; i < len && str1[i] && str2[i]; ++i) + if (str1[i] != str2[i]) + return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same lenght return (i == len) || (str1[i] == 0 && str2[i] == 0); } - -String XMLParser::_replace_special_characters(const String& origstr) { +String XMLParser::_replace_special_characters(const String &origstr) { int pos = origstr.find("&"); int oldPos = 0; @@ -54,30 +53,25 @@ String XMLParser::_replace_special_characters(const String& origstr) { String newstr; - while(pos != -1 && pos < origstr.length()-2) { + while (pos != -1 && pos < origstr.length() - 2) { // check if it is one of the special characters int specialChar = -1; - for (int i=0; i<(int)special_characters.size(); ++i) - { - const CharType* p = &origstr[pos]+1; + for (int i = 0; i < (int)special_characters.size(); ++i) { + const CharType *p = &origstr[pos] + 1; - if (_equalsn(&special_characters[i][1], p, special_characters[i].length()-1)) - { + if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) { specialChar = i; break; } } - if (specialChar != -1) - { - newstr+=(origstr.substr(oldPos, pos - oldPos)); - newstr+=(special_characters[specialChar][0]); + if (specialChar != -1) { + newstr += (origstr.substr(oldPos, pos - oldPos)); + newstr += (special_characters[specialChar][0]); pos += special_characters[specialChar].length(); - } - else - { - newstr+=(origstr.substr(oldPos, pos - oldPos + 1)); + } else { + newstr += (origstr.substr(oldPos, pos - oldPos + 1)); pos += 1; } @@ -86,27 +80,23 @@ String XMLParser::_replace_special_characters(const String& origstr) { pos = origstr.find("&", pos); } - if (oldPos < origstr.length()-1) - newstr+=(origstr.substr(oldPos, origstr.length()-oldPos)); + if (oldPos < origstr.length() - 1) + newstr += (origstr.substr(oldPos, origstr.length() - oldPos)); return newstr; } - -static inline bool _is_white_space(char c) -{ - return (c==' ' || c=='\t' || c=='\n' || c=='\r'); +static inline bool _is_white_space(char c) { + return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } - //! sets the state that text was found. Returns true if set should be set -bool XMLParser::_set_text(char* start, char* end) { +bool XMLParser::_set_text(char *start, char *end) { // check if text is more than 2 characters, and if not, check if there is // only white space, so that this text won't be reported - if (end - start < 3) - { - char* p = start; - for(; p != end; ++p) + if (end - start < 3) { + char *p = start; + for (; p != end; ++p) if (!_is_white_space(*p)) break; @@ -130,14 +120,14 @@ void XMLParser::_parse_closing_xml_element() { attributes.clear(); ++P; - const char* pBeginClose = P; + const char *pBeginClose = P; - while(*P != '>') + while (*P != '>') ++P; node_name = String::utf8(pBeginClose, (int)(P - pBeginClose)); #ifdef DEBUG_XML - print_line("XML CLOSE: "+node_name); + print_line("XML CLOSE: " + node_name); #endif ++P; } @@ -145,25 +135,24 @@ void XMLParser::_parse_closing_xml_element() { void XMLParser::_ignore_definition() { node_type = NODE_UNKNOWN; - char *F=P; + char *F = P; // move until end marked with '>' reached - while(*P != '>') + while (*P != '>') ++P; - node_name.parse_utf8(F,P-F); + node_name.parse_utf8(F, P - F); ++P; } bool XMLParser::_parse_cdata() { - if (*(P+1) != '[') + if (*(P + 1) != '[') return false; node_type = NODE_CDATA; // skip '<![CDATA[' - int count=0; - while( *P && count<8 ) - { + int count = 0; + while (*P && count < 8) { ++P; ++count; } @@ -175,23 +164,22 @@ bool XMLParser::_parse_cdata() { char *cDataEnd = 0; // find end of CDATA - while(*P && !cDataEnd) { + while (*P && !cDataEnd) { if (*P == '>' && - (*(P-1) == ']') && - (*(P-2) == ']')) - { + (*(P - 1) == ']') && + (*(P - 2) == ']')) { cDataEnd = P - 2; } ++P; } - if ( cDataEnd ) + if (cDataEnd) node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin)); else node_name = ""; #ifdef DEBUG_XML - print_line("XML CDATA: "+node_name); + print_line("XML CDATA: " + node_name); #endif return true; @@ -207,24 +195,21 @@ void XMLParser::_parse_comment() { int count = 1; // move until end of comment reached - while(count) - { + while (count) { if (*P == '>') --count; - else - if (*P == '<') + else if (*P == '<') ++count; ++P; } P -= 3; - node_name = String::utf8(pCommentBegin+2, (int)(P - pCommentBegin-2)); + node_name = String::utf8(pCommentBegin + 2, (int)(P - pCommentBegin - 2)); P += 3; #ifdef DEBUG_XML - print_line("XML COMMENT: "+node_name); + print_line("XML COMMENT: " + node_name); #endif - } void XMLParser::_parse_opening_xml_element() { @@ -234,37 +219,34 @@ void XMLParser::_parse_opening_xml_element() { attributes.clear(); // find name - const char* startName = P; + const char *startName = P; // find end of element - while(*P != '>' && !_is_white_space(*P)) + while (*P != '>' && !_is_white_space(*P)) ++P; - const char* endName = P; + const char *endName = P; // find attributes - while(*P != '>') - { + while (*P != '>') { if (_is_white_space(*P)) ++P; - else - { - if (*P != '/') - { + else { + if (*P != '/') { // we've got an attribute // read the attribute names - const char* attributeNameBegin = P; + const char *attributeNameBegin = P; - while(!_is_white_space(*P) && *P != '=') + while (!_is_white_space(*P) && *P != '=') ++P; - const char* attributeNameEnd = P; + const char *attributeNameEnd = P; ++P; // read the attribute value // check for quotes and single quotes, thx to murphy - while( (*P != '\"') && (*P != '\'') && *P) + while ((*P != '\"') && (*P != '\'') && *P) ++P; if (!*P) // malformatted xml file @@ -273,29 +255,27 @@ void XMLParser::_parse_opening_xml_element() { const char attributeQuoteChar = *P; ++P; - const char* attributeValueBegin = P; + const char *attributeValueBegin = P; - while(*P != attributeQuoteChar && *P) + while (*P != attributeQuoteChar && *P) ++P; if (!*P) // malformatted xml file return; - const char* attributeValueEnd = P; + const char *attributeValueEnd = P; ++P; Attribute attr; attr.name = String::utf8(attributeNameBegin, - (int)(attributeNameEnd - attributeNameBegin)); + (int)(attributeNameEnd - attributeNameBegin)); - String s =String::utf8(attributeValueBegin, - (int)(attributeValueEnd - attributeValueBegin)); + String s = String::utf8(attributeValueBegin, + (int)(attributeValueEnd - attributeValueBegin)); attr.value = _replace_special_characters(s); attributes.push_back(attr); - } - else - { + } else { // tag is closed directly ++P; node_empty = true; @@ -305,8 +285,7 @@ void XMLParser::_parse_opening_xml_element() { } // check if this tag is closing directly - if (endName > startName && *(endName-1) == '/') - { + if (endName > startName && *(endName - 1) == '/') { // directly closing tag node_empty = true; endName--; @@ -314,27 +293,25 @@ void XMLParser::_parse_opening_xml_element() { node_name = String::utf8(startName, (int)(endName - startName)); #ifdef DEBUG_XML - print_line("XML OPEN: "+node_name); + print_line("XML OPEN: " + node_name); #endif ++P; } - void XMLParser::_parse_current_node() { - char* start = P; + char *start = P; node_offset = P - data; // more forward until '<' found - while(*P != '<' && *P) + while (*P != '<' && *P) ++P; if (!*P) return; - if (P - start > 0) - { + if (P - start > 0) { // we found some text, store it if (_set_text(start, P)) return; @@ -343,25 +320,23 @@ void XMLParser::_parse_current_node() { ++P; // based on current token, parse and report next element - switch(*P) - { - case '/': - _parse_closing_xml_element(); - break; - case '?': - _ignore_definition(); - break; - case '!': - if (!_parse_cdata()) - _parse_comment(); - break; - default: - _parse_opening_xml_element(); - break; + switch (*P) { + case '/': + _parse_closing_xml_element(); + break; + case '?': + _ignore_definition(); + break; + case '!': + if (!_parse_cdata()) + _parse_comment(); + break; + default: + _parse_opening_xml_element(); + break; } } - uint64_t XMLParser::get_node_offset() const { return node_offset; @@ -379,41 +354,37 @@ Error XMLParser::seek(uint64_t p_pos) { void XMLParser::_bind_methods() { - ObjectTypeDB::bind_method(_MD("read"),&XMLParser::read); - ObjectTypeDB::bind_method(_MD("get_node_type"),&XMLParser::get_node_type); - ObjectTypeDB::bind_method(_MD("get_node_name"),&XMLParser::get_node_name); - ObjectTypeDB::bind_method(_MD("get_node_data"),&XMLParser::get_node_data); - ObjectTypeDB::bind_method(_MD("get_node_offset"),&XMLParser::get_node_offset); - ObjectTypeDB::bind_method(_MD("get_attribute_count"),&XMLParser::get_attribute_count); - ObjectTypeDB::bind_method(_MD("get_attribute_name","idx"),&XMLParser::get_attribute_name); - ObjectTypeDB::bind_method(_MD("get_attribute_value","idx"),(String (XMLParser::*)(int) const) &XMLParser::get_attribute_value); - ObjectTypeDB::bind_method(_MD("has_attribute","name"),&XMLParser::has_attribute); - ObjectTypeDB::bind_method(_MD("get_named_attribute_value","name"), (String (XMLParser::*)(const String&) const) &XMLParser::get_attribute_value); - ObjectTypeDB::bind_method(_MD("get_named_attribute_value_safe","name"), &XMLParser::get_attribute_value_safe); - ObjectTypeDB::bind_method(_MD("is_empty"),&XMLParser::is_empty); - ObjectTypeDB::bind_method(_MD("get_current_line"),&XMLParser::get_current_line); - ObjectTypeDB::bind_method(_MD("skip_section"),&XMLParser::skip_section); - ObjectTypeDB::bind_method(_MD("seek","pos"),&XMLParser::seek); - ObjectTypeDB::bind_method(_MD("open","file"),&XMLParser::open); - ObjectTypeDB::bind_method(_MD("open_buffer","buffer"),&XMLParser::open_buffer); - - BIND_CONSTANT( NODE_NONE ); - BIND_CONSTANT( NODE_ELEMENT ); - BIND_CONSTANT( NODE_ELEMENT_END ); - BIND_CONSTANT( NODE_TEXT ); - BIND_CONSTANT( NODE_COMMENT ); - BIND_CONSTANT( NODE_CDATA ); - BIND_CONSTANT( NODE_UNKNOWN ); + ObjectTypeDB::bind_method(_MD("read"), &XMLParser::read); + ObjectTypeDB::bind_method(_MD("get_node_type"), &XMLParser::get_node_type); + ObjectTypeDB::bind_method(_MD("get_node_name"), &XMLParser::get_node_name); + ObjectTypeDB::bind_method(_MD("get_node_data"), &XMLParser::get_node_data); + ObjectTypeDB::bind_method(_MD("get_node_offset"), &XMLParser::get_node_offset); + ObjectTypeDB::bind_method(_MD("get_attribute_count"), &XMLParser::get_attribute_count); + ObjectTypeDB::bind_method(_MD("get_attribute_name", "idx"), &XMLParser::get_attribute_name); + ObjectTypeDB::bind_method(_MD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value); + ObjectTypeDB::bind_method(_MD("has_attribute", "name"), &XMLParser::has_attribute); + ObjectTypeDB::bind_method(_MD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value); + ObjectTypeDB::bind_method(_MD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe); + ObjectTypeDB::bind_method(_MD("is_empty"), &XMLParser::is_empty); + ObjectTypeDB::bind_method(_MD("get_current_line"), &XMLParser::get_current_line); + ObjectTypeDB::bind_method(_MD("skip_section"), &XMLParser::skip_section); + ObjectTypeDB::bind_method(_MD("seek", "pos"), &XMLParser::seek); + ObjectTypeDB::bind_method(_MD("open", "file"), &XMLParser::open); + ObjectTypeDB::bind_method(_MD("open_buffer", "buffer"), &XMLParser::open_buffer); + BIND_CONSTANT(NODE_NONE); + BIND_CONSTANT(NODE_ELEMENT); + BIND_CONSTANT(NODE_ELEMENT_END); + BIND_CONSTANT(NODE_TEXT); + BIND_CONSTANT(NODE_COMMENT); + BIND_CONSTANT(NODE_CDATA); + BIND_CONSTANT(NODE_UNKNOWN); }; - - Error XMLParser::read() { // if not end reached, parse the node - if (P && (P - data) < length - 1 && *P != 0) - { + if (P && (P - data) < length - 1 && *P != 0) { _parse_current_node(); return OK; } @@ -427,12 +398,12 @@ XMLParser::NodeType XMLParser::get_node_type() { } String XMLParser::get_node_data() const { - ERR_FAIL_COND_V( node_type != NODE_TEXT, ""); + ERR_FAIL_COND_V(node_type != NODE_TEXT, ""); return node_name; } String XMLParser::get_node_name() const { - ERR_FAIL_COND_V( node_type == NODE_TEXT, ""); + ERR_FAIL_COND_V(node_type == NODE_TEXT, ""); return node_name; } int XMLParser::get_attribute_count() const { @@ -441,95 +412,91 @@ int XMLParser::get_attribute_count() const { } String XMLParser::get_attribute_name(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,attributes.size(),""); + ERR_FAIL_INDEX_V(p_idx, attributes.size(), ""); return attributes[p_idx].name; } String XMLParser::get_attribute_value(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,attributes.size(),""); + ERR_FAIL_INDEX_V(p_idx, attributes.size(), ""); return attributes[p_idx].value; } -bool XMLParser::has_attribute(const String& p_name) const { +bool XMLParser::has_attribute(const String &p_name) const { - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) return true; } return false; } -String XMLParser::get_attribute_value(const String& p_name) const { +String XMLParser::get_attribute_value(const String &p_name) const { - int idx=-1; - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) { + idx = i; break; } } - if (idx<0) { - ERR_EXPLAIN("Attribute not found: "+p_name); + if (idx < 0) { + ERR_EXPLAIN("Attribute not found: " + p_name); } - ERR_FAIL_COND_V(idx<0,""); + ERR_FAIL_COND_V(idx < 0, ""); return attributes[idx].value; - } -String XMLParser::get_attribute_value_safe(const String& p_name) const { +String XMLParser::get_attribute_value_safe(const String &p_name) const { - int idx=-1; - for(int i=0;i<attributes.size();i++) { - if (attributes[i].name==p_name) { - idx=i; + int idx = -1; + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].name == p_name) { + idx = i; break; } } - if (idx<0) + if (idx < 0) return ""; return attributes[idx].value; - } bool XMLParser::is_empty() const { return node_empty; } -Error XMLParser::open_buffer(const Vector<uint8_t>& p_buffer) { +Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) { - ERR_FAIL_COND_V(p_buffer.size()==0,ERR_INVALID_DATA); + ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA); length = p_buffer.size(); - data = memnew_arr( char, length+1); - copymem(data,p_buffer.ptr(),length); - data[length]=0; - P=data; + data = memnew_arr(char, length + 1); + copymem(data, p_buffer.ptr(), length); + data[length] = 0; + P = data; return OK; - } -Error XMLParser::open(const String& p_path) { +Error XMLParser::open(const String &p_path) { Error err; - FileAccess * file = FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); } length = file->get_len(); - ERR_FAIL_COND_V(length<1, ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT); - data = memnew_arr( char, length+1); - file->get_buffer((uint8_t*)data,length); - data[length]=0; - P=data; + data = memnew_arr(char, length + 1); + file->get_buffer((uint8_t *)data, length); + data[length] = 0; + P = data; memdelete(file); return OK; - } void XMLParser::skip_section() { @@ -541,29 +508,24 @@ void XMLParser::skip_section() { // read until we've reached the last element in this section int tagcount = 1; - while(tagcount && read()==OK) - { + while (tagcount && read() == OK) { if (get_node_type() == XMLParser::NODE_ELEMENT && - !is_empty()) - { + !is_empty()) { ++tagcount; - } - else - if (get_node_type() == XMLParser::NODE_ELEMENT_END) + } else if (get_node_type() == XMLParser::NODE_ELEMENT_END) --tagcount; } - } void XMLParser::close() { if (data) memdelete_arr(data); - data=NULL; - length=0; - P=NULL; - node_empty=false; - node_type=NODE_NONE; + data = NULL; + length = 0; + P = NULL; + node_empty = false; + node_type = NODE_NONE; node_offset = 0; } @@ -574,19 +536,16 @@ int XMLParser::get_current_line() const { XMLParser::XMLParser() { - data=NULL; + data = NULL; close(); special_characters.push_back("&"); special_characters.push_back("<lt;"); special_characters.push_back(">gt;"); special_characters.push_back("\"quot;"); special_characters.push_back("'apos;"); - - } XMLParser::~XMLParser() { - if (data) memdelete_arr(data); } diff --git a/core/io/xml_parser.h b/core/io/xml_parser.h index e1f059bf8..ad13360f9 100644 --- a/core/io/xml_parser.h +++ b/core/io/xml_parser.h @@ -29,10 +29,10 @@ #ifndef XML_PARSER_H #define XML_PARSER_H -#include "ustring.h" -#include "vector.h" #include "os/file_access.h" #include "reference.h" +#include "ustring.h" +#include "vector.h" /* Based on irrXML (see their zlib license). Added mainly for compatibility with their Collada loader. @@ -40,7 +40,8 @@ class XMLParser : public Reference { - OBJ_TYPE( XMLParser, Reference ); + OBJ_TYPE(XMLParser, Reference); + public: //! Enumeration of all supported source text file formats enum SourceFormat { @@ -63,11 +64,10 @@ public: }; private: - char *data; char *P; int length; - void unescape(String& p_str); + void unescape(String &p_str); Vector<String> special_characters; String node_name; bool node_empty; @@ -81,8 +81,8 @@ private: Vector<Attribute> attributes; - String _replace_special_characters(const String& origstr); - bool _set_text(char* start, char* end); + String _replace_special_characters(const String &origstr); + bool _set_text(char *start, char *end); void _parse_closing_xml_element(); void _ignore_definition(); bool _parse_cdata(); @@ -93,8 +93,6 @@ private: static void _bind_methods(); public: - - Error read(); NodeType get_node_type(); String get_node_name() const; @@ -103,17 +101,17 @@ public: int get_attribute_count() const; String get_attribute_name(int p_idx) const; String get_attribute_value(int p_idx) const; - bool has_attribute(const String& p_name) const; - String get_attribute_value(const String& p_name) const; - String get_attribute_value_safe(const String& p_name) const; // do not print error if doesn't exist + bool has_attribute(const String &p_name) const; + String get_attribute_value(const String &p_name) const; + String get_attribute_value_safe(const String &p_name) const; // do not print error if doesn't exist bool is_empty() const; int get_current_line() const; void skip_section(); Error seek(uint64_t p_pos); - Error open(const String& p_path); - Error open_buffer(const Vector<uint8_t>& p_buffer); + Error open(const String &p_path); + Error open_buffer(const Vector<uint8_t> &p_buffer); void close(); @@ -122,4 +120,3 @@ public: }; #endif - diff --git a/core/io/zip_io.h b/core/io/zip_io.h index c99459351..4da9fc9c8 100644 --- a/core/io/zip_io.h +++ b/core/io/zip_io.h @@ -29,69 +29,65 @@ #ifndef ZIP_IO_H #define ZIP_IO_H -#include "io/zip.h" #include "io/unzip.h" -#include "os/file_access.h" +#include "io/zip.h" #include "os/copymem.h" +#include "os/file_access.h" +static void *zipio_open(void *data, const char *p_fname, int mode) { -static void* zipio_open(void* data, const char* p_fname, int mode) { - - FileAccess *&f = *(FileAccess**)data; + FileAccess *&f = *(FileAccess **)data; String fname; fname.parse_utf8(p_fname); if (mode & ZLIB_FILEFUNC_MODE_WRITE) { - f = FileAccess::open(fname,FileAccess::WRITE); + f = FileAccess::open(fname, FileAccess::WRITE); } else { - f = FileAccess::open(fname,FileAccess::READ); + f = FileAccess::open(fname, FileAccess::READ); } if (!f) return NULL; return data; - }; -static uLong zipio_read(void* data, void* fdata, void* buf, uLong size) { - - FileAccess* f = *(FileAccess**)data; - return f->get_buffer((uint8_t*)buf, size); +static uLong zipio_read(void *data, void *fdata, void *buf, uLong size) { + FileAccess *f = *(FileAccess **)data; + return f->get_buffer((uint8_t *)buf, size); }; -static uLong zipio_write(voidpf opaque, voidpf stream, const void* buf, uLong size) { +static uLong zipio_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { - FileAccess* f = *(FileAccess**)opaque; - f->store_buffer((uint8_t*)buf, size); + FileAccess *f = *(FileAccess **)opaque; + f->store_buffer((uint8_t *)buf, size); return size; }; +static long zipio_tell(voidpf opaque, voidpf stream) { -static long zipio_tell (voidpf opaque, voidpf stream) { - - FileAccess* f = *(FileAccess**)opaque; + FileAccess *f = *(FileAccess **)opaque; return f->get_pos(); }; static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess* f = *(FileAccess**)opaque; + FileAccess *f = *(FileAccess **)opaque; int pos = offset; switch (origin) { - case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_pos() + offset; - break; - case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_len() + offset; - break; - default: - break; + case ZLIB_FILEFUNC_SEEK_CUR: + pos = f->get_pos() + offset; + break; + case ZLIB_FILEFUNC_SEEK_END: + pos = f->get_len() + offset; + break; + default: + break; }; f->seek(pos); @@ -100,36 +96,32 @@ static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { static int zipio_close(voidpf opaque, voidpf stream) { - FileAccess*& f = *(FileAccess**)opaque; + FileAccess *&f = *(FileAccess **)opaque; if (f) { f->close(); - f=NULL; + f = NULL; } return 0; }; static int zipio_testerror(voidpf opaque, voidpf stream) { - FileAccess* f = *(FileAccess**)opaque; - return (f && f->get_error()!=OK)?1:0; + FileAccess *f = *(FileAccess **)opaque; + return (f && f->get_error() != OK) ? 1 : 0; }; - - static voidpf zipio_alloc(voidpf opaque, uInt items, uInt size) { - voidpf ptr =memalloc(items*size); - zeromem(ptr,items*size); + voidpf ptr = memalloc(items * size); + zeromem(ptr, items * size); return ptr; } - static void zipio_free(voidpf opaque, voidpf address) { memfree(address); } - static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { zlib_filefunc_def io; @@ -141,11 +133,9 @@ static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { io.zseek_file = zipio_seek; io.zclose_file = zipio_close; io.zerror_file = zipio_testerror; - io.alloc_mem=zipio_alloc; - io.free_mem=zipio_free; + io.alloc_mem = zipio_alloc; + io.free_mem = zipio_free; return io; } - - #endif // ZIP_IO_H |
