diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
commit | 5dbf1809c6e3e905b94b8764e99491e608122261 (patch) | |
tree | 5e5a5360db15d86d59ec8c6e4f7eb511388c5a9a /scene/resources | |
parent | 45438e9918d421b244bfd7776a30e67dc7f2d3e3 (diff) | |
download | redot-engine-5dbf1809c6e3e905b94b8764e99491e608122261.tar.gz |
A Whole New World (clang-format edition)
I can show you the code
Pretty, with proper whitespace
Tell me, coder, now when did
You last write readable code?
I can open your eyes
Make you see your bad indent
Force you to respect the style
The core devs agreed upon
A whole new world
A new fantastic code format
A de facto standard
With some sugar
Enforced with clang-format
A whole new world
A dazzling style we all dreamed of
And when we read it through
It's crystal clear
That now we're in a whole new world of code
Diffstat (limited to 'scene/resources')
101 files changed, 8494 insertions, 10151 deletions
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp index b743834e63..4fddd55e20 100644 --- a/scene/resources/animation.cpp +++ b/scene/resources/animation.cpp @@ -29,33 +29,32 @@ #include "animation.h" #include "geometry.h" +bool Animation::_set(const StringName &p_name, const Variant &p_value) { -bool Animation::_set(const StringName& p_name, const Variant& p_value) { + String name = p_name; - String name=p_name; - - if (name=="length") + if (name == "length") set_length(p_value); - else if (name=="loop") + else if (name == "loop") set_loop(p_value); - else if (name=="step") + else if (name == "step") set_step(p_value); else if (name.begins_with("tracks/")) { - int track=name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); + int track = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); - if (tracks.size()==track && what=="type") { + if (tracks.size() == track && what == "type") { - String type=p_value; + String type = p_value; - if (type=="transform") { + if (type == "transform") { add_track(TYPE_TRANSFORM); - } else if (type=="value") { + } else if (type == "value") { add_track(TYPE_VALUE); - } else if (type=="method") { + } else if (type == "method") { add_track(TYPE_METHOD); } else { @@ -66,23 +65,23 @@ bool Animation::_set(const StringName& p_name, const Variant& p_value) { return true; } - ERR_FAIL_INDEX_V( track, tracks.size(),false ); + ERR_FAIL_INDEX_V(track, tracks.size(), false); - if (what=="path") - track_set_path(track,p_value); - else if (what=="interp") - track_set_interpolation_type(track,InterpolationType(p_value.operator int())); - else if (what=="loop_wrap") - track_set_interpolation_loop_wrap(track,p_value); - else if (what=="imported") - track_set_imported(track,p_value); - else if (what == "keys" || what=="key_values") { + if (what == "path") + track_set_path(track, p_value); + else if (what == "interp") + track_set_interpolation_type(track, InterpolationType(p_value.operator int())); + else if (what == "loop_wrap") + track_set_interpolation_loop_wrap(track, p_value); + else if (what == "imported") + track_set_imported(track, p_value); + else if (what == "keys" || what == "key_values") { - if (track_get_type(track)==TYPE_TRANSFORM) { + if (track_get_type(track) == TYPE_TRANSFORM) { - TransformTrack *tt = static_cast<TransformTrack*>(tracks[track]); - PoolVector<float> values=p_value; - int vcount=values.size(); + TransformTrack *tt = static_cast<TransformTrack *>(tracks[track]); + PoolVector<float> values = p_value; + int vcount = values.size(); #if 0 // old compatibility hack if ((vcount%11) == 0) { @@ -121,137 +120,126 @@ bool Animation::_set(const StringName& p_name, const Variant& p_value) { } #endif - ERR_FAIL_COND_V(vcount%12,false); // shuld be multiple of 11 + ERR_FAIL_COND_V(vcount % 12, false); // shuld be multiple of 11 PoolVector<float>::Read r = values.read(); - tt->transforms.resize(vcount/12); - - - for(int i=0;i<(vcount/12);i++) { - + tt->transforms.resize(vcount / 12); - TKey<TransformKey> &tk=tt->transforms[i]; - const float *ofs=&r[i*12]; - tk.time=ofs[0]; - tk.transition=ofs[1]; + for (int i = 0; i < (vcount / 12); i++) { - tk.value.loc.x=ofs[2]; - tk.value.loc.y=ofs[3]; - tk.value.loc.z=ofs[4]; + TKey<TransformKey> &tk = tt->transforms[i]; + const float *ofs = &r[i * 12]; + tk.time = ofs[0]; + tk.transition = ofs[1]; - tk.value.rot.x=ofs[5]; - tk.value.rot.y=ofs[6]; - tk.value.rot.z=ofs[7]; - tk.value.rot.w=ofs[8]; - - tk.value.scale.x=ofs[9]; - tk.value.scale.y=ofs[10]; - tk.value.scale.z=ofs[11]; + tk.value.loc.x = ofs[2]; + tk.value.loc.y = ofs[3]; + tk.value.loc.z = ofs[4]; + tk.value.rot.x = ofs[5]; + tk.value.rot.y = ofs[6]; + tk.value.rot.z = ofs[7]; + tk.value.rot.w = ofs[8]; + tk.value.scale.x = ofs[9]; + tk.value.scale.y = ofs[10]; + tk.value.scale.z = ofs[11]; } - } else if (track_get_type(track)==TYPE_VALUE) { + } else if (track_get_type(track) == TYPE_VALUE) { - ValueTrack *vt = static_cast<ValueTrack*>(tracks[track]); + ValueTrack *vt = static_cast<ValueTrack *>(tracks[track]); Dictionary d = p_value; - ERR_FAIL_COND_V(!d.has("times"),false); - ERR_FAIL_COND_V(!d.has("values"),false); + ERR_FAIL_COND_V(!d.has("times"), false); + ERR_FAIL_COND_V(!d.has("values"), false); if (d.has("cont")) { bool v = d["cont"]; - vt->update_mode=v?UPDATE_CONTINUOUS:UPDATE_DISCRETE; + vt->update_mode = v ? UPDATE_CONTINUOUS : UPDATE_DISCRETE; } if (d.has("update")) { - int um =d["update"]; - if (um<0) - um=0; - else if (um>2) - um=2; - vt->update_mode=UpdateMode(um); + int um = d["update"]; + if (um < 0) + um = 0; + else if (um > 2) + um = 2; + vt->update_mode = UpdateMode(um); } + PoolVector<float> times = d["times"]; + Array values = d["values"]; - - PoolVector<float> times=d["times"]; - Array values=d["values"]; - - ERR_FAIL_COND_V(times.size()!=values.size(),false); + ERR_FAIL_COND_V(times.size() != values.size(), false); if (times.size()) { - int valcount=times.size(); + int valcount = times.size(); PoolVector<float>::Read rt = times.read(); vt->values.resize(valcount); - for(int i=0;i<valcount;i++) { + for (int i = 0; i < valcount; i++) { - vt->values[i].time=rt[i]; - vt->values[i].value=values[i]; + vt->values[i].time = rt[i]; + vt->values[i].value = values[i]; } if (d.has("transitions")) { PoolVector<float> transitions = d["transitions"]; - ERR_FAIL_COND_V(transitions.size()!=valcount,false); + ERR_FAIL_COND_V(transitions.size() != valcount, false); PoolVector<float>::Read rtr = transitions.read(); + for (int i = 0; i < valcount; i++) { - for(int i=0;i<valcount;i++) { - - vt->values[i].transition=rtr[i]; + vt->values[i].transition = rtr[i]; } } - } return true; } else { - while(track_get_key_count(track)) - track_remove_key(track,0); //well shouldn't be set anyway + while (track_get_key_count(track)) + track_remove_key(track, 0); //well shouldn't be set anyway Dictionary d = p_value; - ERR_FAIL_COND_V(!d.has("times"),false); - ERR_FAIL_COND_V(!d.has("values"),false); + ERR_FAIL_COND_V(!d.has("times"), false); + ERR_FAIL_COND_V(!d.has("values"), false); - PoolVector<float> times=d["times"]; - Array values=d["values"]; + PoolVector<float> times = d["times"]; + Array values = d["values"]; - ERR_FAIL_COND_V(times.size()!=values.size(),false); + ERR_FAIL_COND_V(times.size() != values.size(), false); if (times.size()) { - int valcount=times.size(); + int valcount = times.size(); PoolVector<float>::Read rt = times.read(); - for(int i=0;i<valcount;i++) { + for (int i = 0; i < valcount; i++) { - track_insert_key(track,rt[i],values[i]); + track_insert_key(track, rt[i], values[i]); } if (d.has("transitions")) { PoolVector<float> transitions = d["transitions"]; - ERR_FAIL_COND_V(transitions.size()!=valcount,false); + ERR_FAIL_COND_V(transitions.size() != valcount, false); PoolVector<float>::Read rtr = transitions.read(); - for(int i=0;i<valcount;i++) { + for (int i = 0; i < valcount; i++) { - track_set_key_transition(track,i,rtr[i]); + track_set_key_transition(track, i, rtr[i]); } } - } - - } } else return false; @@ -261,84 +249,81 @@ bool Animation::_set(const StringName& p_name, const Variant& p_value) { return true; } +bool Animation::_get(const StringName &p_name, Variant &r_ret) const { -bool Animation::_get(const StringName& p_name,Variant &r_ret) const { + String name = p_name; - String name=p_name; - - if (name=="length") - r_ret= length; - else if (name=="loop") - r_ret= loop; - else if (name=="step") - r_ret= step; + if (name == "length") + r_ret = length; + else if (name == "loop") + r_ret = loop; + else if (name == "step") + r_ret = step; else if (name.begins_with("tracks/")) { - int track=name.get_slicec('/',1).to_int(); - String what=name.get_slicec('/',2); - ERR_FAIL_INDEX_V( track, tracks.size(), false ); - if (what=="type") { - + int track = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); + ERR_FAIL_INDEX_V(track, tracks.size(), false); + if (what == "type") { switch (track_get_type(track)) { - case TYPE_TRANSFORM: r_ret= "transform"; break; - case TYPE_VALUE: r_ret= "value";break; - case TYPE_METHOD: r_ret= "method";break; + case TYPE_TRANSFORM: r_ret = "transform"; break; + case TYPE_VALUE: r_ret = "value"; break; + case TYPE_METHOD: r_ret = "method"; break; } return true; - } else if (what=="path") - r_ret=track_get_path(track); - else if (what=="interp") + } else if (what == "path") + r_ret = track_get_path(track); + else if (what == "interp") r_ret = track_get_interpolation_type(track); - else if (what=="loop_wrap") + else if (what == "loop_wrap") r_ret = track_get_interpolation_loop_wrap(track); - else if (what=="imported") + else if (what == "imported") r_ret = track_is_imported(track); - else if (what=="keys") { + else if (what == "keys") { - if (track_get_type(track)==TYPE_TRANSFORM) { + if (track_get_type(track) == TYPE_TRANSFORM) { PoolVector<real_t> keys; - int kk=track_get_key_count(track); - keys.resize(kk*12); + int kk = track_get_key_count(track); + keys.resize(kk * 12); PoolVector<real_t>::Write w = keys.write(); - int idx=0; - for(int i=0;i<track_get_key_count(track);i++) { + int idx = 0; + for (int i = 0; i < track_get_key_count(track); i++) { Vector3 loc; Quat rot; Vector3 scale; - transform_track_get_key(track,i,&loc,&rot,&scale); - - w[idx++]=track_get_key_time(track,i); - w[idx++]=track_get_key_transition(track,i); - w[idx++]=loc.x; - w[idx++]=loc.y; - w[idx++]=loc.z; - - w[idx++]=rot.x; - w[idx++]=rot.y; - w[idx++]=rot.z; - w[idx++]=rot.w; - - w[idx++]=scale.x; - w[idx++]=scale.y; - w[idx++]=scale.z; + transform_track_get_key(track, i, &loc, &rot, &scale); + + w[idx++] = track_get_key_time(track, i); + w[idx++] = track_get_key_transition(track, i); + w[idx++] = loc.x; + w[idx++] = loc.y; + w[idx++] = loc.z; + + w[idx++] = rot.x; + w[idx++] = rot.y; + w[idx++] = rot.z; + w[idx++] = rot.w; + + w[idx++] = scale.x; + w[idx++] = scale.y; + w[idx++] = scale.z; } w = PoolVector<real_t>::Write(); - r_ret=keys; + r_ret = keys; return true; - } else if (track_get_type(track)==TYPE_VALUE) { - + } else if (track_get_type(track) == TYPE_VALUE) { - const ValueTrack *vt = static_cast<const ValueTrack*>(tracks[track]); + const ValueTrack *vt = static_cast<const ValueTrack *>(tracks[track]); Dictionary d; @@ -346,82 +331,80 @@ bool Animation::_get(const StringName& p_name,Variant &r_ret) const { PoolVector<float> key_transitions; Array key_values; - int kk=vt->values.size(); + int kk = vt->values.size(); key_times.resize(kk); key_transitions.resize(kk); key_values.resize(kk); - PoolVector<float>::Write wti=key_times.write(); - PoolVector<float>::Write wtr=key_transitions.write(); + PoolVector<float>::Write wti = key_times.write(); + PoolVector<float>::Write wtr = key_transitions.write(); - int idx=0; + int idx = 0; const TKey<Variant> *vls = vt->values.ptr(); - for(int i=0;i<kk;i++) { + for (int i = 0; i < kk; i++) { - wti[idx]=vls[i].time; - wtr[idx]=vls[i].transition; - key_values[idx]=vls[i].value; + wti[idx] = vls[i].time; + wtr[idx] = vls[i].transition; + key_values[idx] = vls[i].value; idx++; } - wti=PoolVector<float>::Write(); - wtr=PoolVector<float>::Write(); + wti = PoolVector<float>::Write(); + wtr = PoolVector<float>::Write(); - d["times"]=key_times; - d["transitions"]=key_transitions; - d["values"]=key_values; - if (track_get_type(track)==TYPE_VALUE) { - d["update"]=value_track_get_update_mode(track); + d["times"] = key_times; + d["transitions"] = key_transitions; + d["values"] = key_values; + if (track_get_type(track) == TYPE_VALUE) { + d["update"] = value_track_get_update_mode(track); } - r_ret=d; + r_ret = d; return true; } else { - Dictionary d; PoolVector<float> key_times; PoolVector<float> key_transitions; Array key_values; - int kk=track_get_key_count(track); + int kk = track_get_key_count(track); key_times.resize(kk); key_transitions.resize(kk); key_values.resize(kk); - PoolVector<float>::Write wti=key_times.write(); - PoolVector<float>::Write wtr=key_transitions.write(); + PoolVector<float>::Write wti = key_times.write(); + PoolVector<float>::Write wtr = key_transitions.write(); - int idx=0; - for(int i=0;i<track_get_key_count(track);i++) { + int idx = 0; + for (int i = 0; i < track_get_key_count(track); i++) { - wti[idx]=track_get_key_time(track,i); - wtr[idx]=track_get_key_transition(track,i); - key_values[idx]=track_get_key_value(track,i); + wti[idx] = track_get_key_time(track, i); + wtr[idx] = track_get_key_transition(track, i); + key_values[idx] = track_get_key_value(track, i); idx++; } - wti=PoolVector<float>::Write(); - wtr=PoolVector<float>::Write(); + wti = PoolVector<float>::Write(); + wtr = PoolVector<float>::Write(); - d["times"]=key_times; - d["transitions"]=key_transitions; - d["values"]=key_values; - if (track_get_type(track)==TYPE_VALUE) { - d["update"]=value_track_get_update_mode(track); + d["times"] = key_times; + d["transitions"] = key_transitions; + d["values"] = key_values; + if (track_get_type(track) == TYPE_VALUE) { + d["update"] = value_track_get_update_mode(track); } - r_ret=d; + r_ret = d; return true; - } } else return false; @@ -429,47 +412,45 @@ bool Animation::_get(const StringName& p_name,Variant &r_ret) const { return false; return true; - } +void Animation::_get_property_list(List<PropertyInfo> *p_list) const { -void Animation::_get_property_list( List<PropertyInfo> *p_list) const { - - p_list->push_back( PropertyInfo( Variant::REAL, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001")); - p_list->push_back( PropertyInfo( Variant::BOOL, "loop" )); - p_list->push_back( PropertyInfo( Variant::REAL, "step", PROPERTY_HINT_RANGE, "0,4096,0.001" )); + p_list->push_back(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001")); + p_list->push_back(PropertyInfo(Variant::BOOL, "loop")); + p_list->push_back(PropertyInfo(Variant::REAL, "step", PROPERTY_HINT_RANGE, "0,4096,0.001")); - for (int i=0;i<tracks.size();i++) { + for (int i = 0; i < tracks.size(); i++) { - p_list->push_back( PropertyInfo( Variant::STRING, "tracks/"+itos(i)+"/type", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); - p_list->push_back( PropertyInfo( Variant::NODE_PATH, "tracks/"+itos(i)+"/path", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); - p_list->push_back( PropertyInfo( Variant::INT, "tracks/"+itos(i)+"/interp", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); - p_list->push_back( PropertyInfo( Variant::BOOL, "tracks/"+itos(i)+"/loop_wrap", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); - p_list->push_back( PropertyInfo( Variant::BOOL, "tracks/"+itos(i)+"/imported", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); - p_list->push_back( PropertyInfo( Variant::ARRAY, "tracks/"+itos(i)+"/keys", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); + p_list->push_back(PropertyInfo(Variant::STRING, "tracks/" + itos(i) + "/type", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::NODE_PATH, "tracks/" + itos(i) + "/path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::INT, "tracks/" + itos(i) + "/interp", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/loop_wrap", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/imported", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::ARRAY, "tracks/" + itos(i) + "/keys", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } } -int Animation::add_track(TrackType p_type,int p_at_pos) { +int Animation::add_track(TrackType p_type, int p_at_pos) { - if (p_at_pos<0 || p_at_pos>=tracks.size()) - p_at_pos=tracks.size(); + if (p_at_pos < 0 || p_at_pos >= tracks.size()) + p_at_pos = tracks.size(); - switch( p_type ) { + switch (p_type) { case TYPE_TRANSFORM: { - TransformTrack *tt = memnew( TransformTrack ); - tracks.insert( p_at_pos,tt ); + TransformTrack *tt = memnew(TransformTrack); + tracks.insert(p_at_pos, tt); } break; case TYPE_VALUE: { - tracks.insert( p_at_pos,memnew( ValueTrack ) ); + tracks.insert(p_at_pos, memnew(ValueTrack)); } break; case TYPE_METHOD: { - tracks.insert( p_at_pos,memnew( MethodTrack ) ); + tracks.insert(p_at_pos, memnew(MethodTrack)); } break; default: { @@ -484,31 +465,31 @@ int Animation::add_track(TrackType p_type,int p_at_pos) { void Animation::remove_track(int p_track) { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); + TransformTrack *tt = static_cast<TransformTrack *>(t); _clear(tt->transforms); } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); + ValueTrack *vt = static_cast<ValueTrack *>(t); _clear(vt->values); } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); + MethodTrack *mt = static_cast<MethodTrack *>(t); _clear(mt->methods); } break; } - memdelete( t ); + memdelete(t); tracks.remove(p_track); emit_changed(); } @@ -520,27 +501,26 @@ int Animation::get_track_count() const { Animation::TrackType Animation::track_get_type(int p_track) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(), TYPE_TRANSFORM ); + ERR_FAIL_INDEX_V(p_track, tracks.size(), TYPE_TRANSFORM); return tracks[p_track]->type; } -void Animation::track_set_path(int p_track,const NodePath& p_path) { +void Animation::track_set_path(int p_track, const NodePath &p_path) { ERR_FAIL_INDEX(p_track, tracks.size()); - tracks[p_track]->path=p_path; + tracks[p_track]->path = p_path; emit_changed(); - } NodePath Animation::track_get_path(int p_track) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),NodePath()); + ERR_FAIL_INDEX_V(p_track, tracks.size(), NodePath()); return tracks[p_track]->path; } -int Animation::find_track(const NodePath& p_path) const { +int Animation::find_track(const NodePath &p_path) const { - for (int i=0; i<tracks.size(); i++) { + for (int i = 0; i < tracks.size(); i++) { if (tracks[i]->path == p_path) return i; @@ -548,34 +528,30 @@ int Animation::find_track(const NodePath& p_path) const { return -1; }; - -void Animation::track_set_interpolation_type(int p_track,InterpolationType p_interp) { +void Animation::track_set_interpolation_type(int p_track, InterpolationType p_interp) { ERR_FAIL_INDEX(p_track, tracks.size()); - ERR_FAIL_INDEX(p_interp,3); - tracks[p_track]->interpolation=p_interp; + ERR_FAIL_INDEX(p_interp, 3); + tracks[p_track]->interpolation = p_interp; emit_changed(); - } Animation::InterpolationType Animation::track_get_interpolation_type(int p_track) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),INTERPOLATION_NEAREST); + ERR_FAIL_INDEX_V(p_track, tracks.size(), INTERPOLATION_NEAREST); return tracks[p_track]->interpolation; } -void Animation::track_set_interpolation_loop_wrap(int p_track,bool p_enable) { +void Animation::track_set_interpolation_loop_wrap(int p_track, bool p_enable) { ERR_FAIL_INDEX(p_track, tracks.size()); - tracks[p_track]->loop_wrap=p_enable; + tracks[p_track]->loop_wrap = p_enable; emit_changed(); - } -bool Animation::track_get_interpolation_loop_wrap(int p_track) const{ +bool Animation::track_get_interpolation_loop_wrap(int p_track) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),INTERPOLATION_NEAREST); + ERR_FAIL_INDEX_V(p_track, tracks.size(), INTERPOLATION_NEAREST); return tracks[p_track]->loop_wrap; - } // transform @@ -605,23 +581,22 @@ int Animation::_insert_pos(float p_time, T& p_keys) { } */ -template<class T, class V> -int Animation::_insert(float p_time, T& p_keys, const V& p_value) { +template <class T, class V> +int Animation::_insert(float p_time, T &p_keys, const V &p_value) { - int idx=p_keys.size(); + int idx = p_keys.size(); - while(true) { + while (true) { - - if (idx==0 || p_keys[idx-1].time < p_time) { + if (idx == 0 || p_keys[idx - 1].time < p_time) { //condition for insertion. - p_keys.insert(idx,p_value); + p_keys.insert(idx, p_value); return idx; - } else if (p_keys[idx-1].time == p_time) { + } else if (p_keys[idx - 1].time == p_time) { // condition for replacing. - p_keys[idx-1]=p_value; - return idx-1; + p_keys[idx - 1] = p_value; + return idx - 1; } idx--; @@ -630,82 +605,81 @@ int Animation::_insert(float p_time, T& p_keys, const V& p_value) { return -1; } -template<class T> -void Animation::_clear(T& p_keys) { - +template <class T> +void Animation::_clear(T &p_keys) { p_keys.clear(); } -Error Animation::transform_track_get_key(int p_track, int p_key, Vector3* r_loc, Quat* r_rot, Vector3* r_scale) const { +Error Animation::transform_track_get_key(int p_track, int p_key, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),ERR_INVALID_PARAMETER); - Track *t=tracks[p_track]; + ERR_FAIL_INDEX_V(p_track, tracks.size(), ERR_INVALID_PARAMETER); + Track *t = tracks[p_track]; - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_COND_V(t->type!=TYPE_TRANSFORM,ERR_INVALID_PARAMETER); - ERR_FAIL_INDEX_V(p_key,tt->transforms.size(),ERR_INVALID_PARAMETER); + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, ERR_INVALID_PARAMETER); + ERR_FAIL_INDEX_V(p_key, tt->transforms.size(), ERR_INVALID_PARAMETER); if (r_loc) - *r_loc=tt->transforms[p_key].value.loc; + *r_loc = tt->transforms[p_key].value.loc; if (r_rot) - *r_rot=tt->transforms[p_key].value.rot; + *r_rot = tt->transforms[p_key].value.rot; if (r_scale) - *r_scale=tt->transforms[p_key].value.scale; + *r_scale = tt->transforms[p_key].value.scale; return OK; } -int Animation::transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat& p_rot, const Vector3& p_scale) { +int Animation::transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot, const Vector3 &p_scale) { - ERR_FAIL_INDEX_V(p_track, tracks.size(),-1); - Track *t=tracks[p_track]; - ERR_FAIL_COND_V(t->type!=TYPE_TRANSFORM,-1); + ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, -1); - TransformTrack * tt = static_cast<TransformTrack*>(t); + TransformTrack *tt = static_cast<TransformTrack *>(t); TKey<TransformKey> tkey; - tkey.time=p_time; - tkey.value.loc=p_loc; - tkey.value.rot=p_rot; - tkey.value.scale=p_scale; + tkey.time = p_time; + tkey.value.loc = p_loc; + tkey.value.rot = p_rot; + tkey.value.scale = p_scale; - int ret = _insert( p_time, tt->transforms, tkey ); + int ret = _insert(p_time, tt->transforms, tkey); emit_changed(); return ret; } void Animation::track_remove_key_at_pos(int p_track, float p_pos) { - int idx = track_find_key(p_track,p_pos,true); + int idx = track_find_key(p_track, p_pos, true); ERR_FAIL_COND(idx < 0); - track_remove_key(p_track,idx); + track_remove_key(p_track, idx); } void Animation::track_remove_key(int p_track, int p_idx) { - ERR_FAIL_INDEX(p_track,tracks.size()); - Track *t=tracks[p_track]; + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_INDEX(p_idx,tt->transforms.size()); + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_INDEX(p_idx, tt->transforms.size()); tt->transforms.remove(p_idx); } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - ERR_FAIL_INDEX(p_idx,vt->values.size()); + ValueTrack *vt = static_cast<ValueTrack *>(t); + ERR_FAIL_INDEX(p_idx, vt->values.size()); vt->values.remove(p_idx); } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - ERR_FAIL_INDEX(p_idx,mt->methods.size()); + MethodTrack *mt = static_cast<MethodTrack *>(t); + ERR_FAIL_INDEX(p_idx, mt->methods.size()); mt->methods.remove(p_idx); } break; @@ -716,39 +690,39 @@ void Animation::track_remove_key(int p_track, int p_idx) { int Animation::track_find_key(int p_track, float p_time, bool p_exact) const { - ERR_FAIL_INDEX_V(p_track,tracks.size(),-1); - Track *t=tracks[p_track]; + ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - int k = _find(tt->transforms,p_time); - if (k<0 || k>=tt->transforms.size()) + TransformTrack *tt = static_cast<TransformTrack *>(t); + int k = _find(tt->transforms, p_time); + if (k < 0 || k >= tt->transforms.size()) return -1; - if (tt->transforms[k].time!=p_time && p_exact) + if (tt->transforms[k].time != p_time && p_exact) return -1; return k; } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - int k = _find(vt->values,p_time); - if (k<0 || k>=vt->values.size()) + ValueTrack *vt = static_cast<ValueTrack *>(t); + int k = _find(vt->values, p_time); + if (k < 0 || k >= vt->values.size()) return -1; - if (vt->values[k].time!=p_time && p_exact) + if (vt->values[k].time != p_time && p_exact) return -1; return k; } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - int k = _find(mt->methods,p_time); - if (k<0 || k>=mt->methods.size()) + MethodTrack *mt = static_cast<MethodTrack *>(t); + int k = _find(mt->methods, p_time); + if (k < 0 || k >= mt->methods.size()) return -1; - if (mt->methods[k].time!=p_time && p_exact) + if (mt->methods[k].time != p_time && p_exact) return -1; return k; @@ -758,65 +732,63 @@ int Animation::track_find_key(int p_track, float p_time, bool p_exact) const { return -1; } - -void Animation::track_insert_key(int p_track, float p_time, const Variant& p_value,float p_transition) { +void Animation::track_insert_key(int p_track, float p_time, const Variant &p_value, float p_transition) { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { Dictionary d = p_value; Vector3 loc; if (d.has("loc")) - loc=d["loc"]; + loc = d["loc"]; Quat rot; if (d.has("rot")) - rot=d["rot"]; + rot = d["rot"]; Vector3 scale; if (d.has("scale")) - scale=d["scale"]; + scale = d["scale"]; - int idx = transform_track_insert_key(p_track,p_time,loc,rot,scale); - track_set_key_transition(p_track,idx,p_transition); + int idx = transform_track_insert_key(p_track, p_time, loc, rot, scale); + track_set_key_transition(p_track, idx, p_transition); } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); + ValueTrack *vt = static_cast<ValueTrack *>(t); - TKey<Variant> k; - k.time=p_time; - k.transition=p_transition; - k.value=p_value; - _insert( p_time, vt->values, k ); + TKey<Variant> k; + k.time = p_time; + k.transition = p_transition; + k.value = p_value; + _insert(p_time, vt->values, k); } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); + MethodTrack *mt = static_cast<MethodTrack *>(t); - ERR_FAIL_COND( p_value.get_type() != Variant::DICTIONARY ); + ERR_FAIL_COND(p_value.get_type() != Variant::DICTIONARY); - Dictionary d=p_value; - ERR_FAIL_COND(!d.has("method") || d["method"].get_type()!=Variant::STRING); + Dictionary d = p_value; + ERR_FAIL_COND(!d.has("method") || d["method"].get_type() != Variant::STRING); ERR_FAIL_COND(!d.has("args") || !d["args"].is_array()); MethodKey k; - k.time=p_time; - k.transition=p_transition; - k.method=d["method"]; - k.params=d["args"]; + k.time = p_time; + k.transition = p_transition; + k.method = d["method"]; + k.params = d["args"]; - _insert( p_time, mt->methods, k ); + _insert(p_time, mt->methods, k); } break; - } emit_changed(); @@ -824,25 +796,25 @@ void Animation::track_insert_key(int p_track, float p_time, const Variant& p_val int Animation::track_get_key_count(int p_track) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),-1); - Track *t=tracks[p_track]; + ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); + TransformTrack *tt = static_cast<TransformTrack *>(t); return tt->transforms.size(); } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); + ValueTrack *vt = static_cast<ValueTrack *>(t); return vt->values.size(); } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); + MethodTrack *mt = static_cast<MethodTrack *>(t); return mt->methods.size(); } break; } @@ -853,40 +825,39 @@ int Animation::track_get_key_count(int p_track) const { Variant Animation::track_get_key_value(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), Variant()); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, tt->transforms.size(), Variant() ); + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), Variant()); Dictionary d; - d["loc"]=tt->transforms[p_key_idx].value.loc; - d["rot"]=tt->transforms[p_key_idx].value.rot; - d["scale"]=tt->transforms[p_key_idx].value.scale; + d["loc"] = tt->transforms[p_key_idx].value.loc; + d["rot"] = tt->transforms[p_key_idx].value.rot; + d["scale"] = tt->transforms[p_key_idx].value.scale; return d; } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, vt->values.size(), Variant() ); + ValueTrack *vt = static_cast<ValueTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), Variant()); return vt->values[p_key_idx].value; } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, mt->methods.size(), Variant() ); + MethodTrack *mt = static_cast<MethodTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), Variant()); Dictionary d; - d["method"]=mt->methods[p_key_idx].method; - d["args"]=mt->methods[p_key_idx].params; + d["method"] = mt->methods[p_key_idx].method; + d["args"] = mt->methods[p_key_idx].params; return d; } break; - } ERR_FAIL_V(Variant()); @@ -895,452 +866,431 @@ Variant Animation::track_get_key_value(int p_track, int p_key_idx) const { float Animation::track_get_key_time(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, tt->transforms.size(), -1 ); + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), -1); return tt->transforms[p_key_idx].time; } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, vt->values.size(), -1 ); + ValueTrack *vt = static_cast<ValueTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), -1); return vt->values[p_key_idx].time; - } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, mt->methods.size(), -1 ); + MethodTrack *mt = static_cast<MethodTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), -1); return mt->methods[p_key_idx].time; - } break; } ERR_FAIL_V(-1); - } float Animation::track_get_key_transition(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, tt->transforms.size(), -1 ); + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), -1); return tt->transforms[p_key_idx].transition; } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, vt->values.size(), -1 ); + ValueTrack *vt = static_cast<ValueTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), -1); return vt->values[p_key_idx].transition; - } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - ERR_FAIL_INDEX_V( p_key_idx, mt->methods.size(), -1 ); + MethodTrack *mt = static_cast<MethodTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), -1); return mt->methods[p_key_idx].transition; - } break; } ERR_FAIL_V(0); - } -void Animation::track_set_key_value(int p_track, int p_key_idx,const Variant& p_value) { +void Animation::track_set_key_value(int p_track, int p_key_idx, const Variant &p_value) { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_INDEX( p_key_idx, tt->transforms.size()); + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, tt->transforms.size()); Dictionary d = p_value; if (d.has("loc")) - tt->transforms[p_key_idx].value.loc=d["loc"]; + tt->transforms[p_key_idx].value.loc = d["loc"]; if (d.has("rot")) - tt->transforms[p_key_idx].value.rot=d["rot"]; + tt->transforms[p_key_idx].value.rot = d["rot"]; if (d.has("scale")) - tt->transforms[p_key_idx].value.scale=d["scale"]; + tt->transforms[p_key_idx].value.scale = d["scale"]; } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - ERR_FAIL_INDEX( p_key_idx, vt->values.size()); - vt->values[p_key_idx].value=p_value; + ValueTrack *vt = static_cast<ValueTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, vt->values.size()); + vt->values[p_key_idx].value = p_value; } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - ERR_FAIL_INDEX( p_key_idx, mt->methods.size()); + MethodTrack *mt = static_cast<MethodTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, mt->methods.size()); Dictionary d = p_value; if (d.has("method")) - mt->methods[p_key_idx].method=d["method"]; + mt->methods[p_key_idx].method = d["method"]; if (d.has("args")) - mt->methods[p_key_idx].params=d["args"]; + mt->methods[p_key_idx].params = d["args"]; } break; } - } -void Animation::track_set_key_transition(int p_track, int p_key_idx,float p_transition) { +void Animation::track_set_key_transition(int p_track, int p_key_idx, float p_transition) { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; + Track *t = tracks[p_track]; - switch(t->type) { + switch (t->type) { case TYPE_TRANSFORM: { - TransformTrack * tt = static_cast<TransformTrack*>(t); - ERR_FAIL_INDEX( p_key_idx, tt->transforms.size()); - tt->transforms[p_key_idx].transition=p_transition; + TransformTrack *tt = static_cast<TransformTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, tt->transforms.size()); + tt->transforms[p_key_idx].transition = p_transition; } break; case TYPE_VALUE: { - ValueTrack * vt = static_cast<ValueTrack*>(t); - ERR_FAIL_INDEX( p_key_idx, vt->values.size()); - vt->values[p_key_idx].transition=p_transition; - + ValueTrack *vt = static_cast<ValueTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, vt->values.size()); + vt->values[p_key_idx].transition = p_transition; } break; case TYPE_METHOD: { - MethodTrack * mt = static_cast<MethodTrack*>(t); - ERR_FAIL_INDEX( p_key_idx, mt->methods.size()); - mt->methods[p_key_idx].transition=p_transition; - + MethodTrack *mt = static_cast<MethodTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, mt->methods.size()); + mt->methods[p_key_idx].transition = p_transition; } break; } - } +template <class K> +int Animation::_find(const Vector<K> &p_keys, float p_time) const { - -template<class K> -int Animation::_find( const Vector<K>& p_keys, float p_time) const { - - int len=p_keys.size(); - if (len==0) + int len = p_keys.size(); + if (len == 0) return -2; int low = 0; - int high = len -1; + int high = len - 1; int middle; - const K* keys =&p_keys[0]; + const K *keys = &p_keys[0]; - while( low <= high ) { + while (low <= high) { - middle = ( low + high ) / 2; + middle = (low + high) / 2; - if( p_time == keys[ middle ].time ) { //match + if (p_time == keys[middle].time) { //match return middle; - } else if( p_time < keys[middle].time ) + } else if (p_time < keys[middle].time) high = middle - 1; //search low end of array else low = middle + 1; //search high end of array } - if (keys[middle].time>p_time) + if (keys[middle].time > p_time) middle--; return middle; } -Animation::TransformKey Animation::_interpolate( const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, float p_c) const { +Animation::TransformKey Animation::_interpolate(const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, float p_c) const { TransformKey ret; - ret.loc=_interpolate(p_a.loc,p_b.loc,p_c); - ret.rot=_interpolate(p_a.rot,p_b.rot,p_c); - ret.scale=_interpolate(p_a.scale,p_b.scale,p_c); + ret.loc = _interpolate(p_a.loc, p_b.loc, p_c); + ret.rot = _interpolate(p_a.rot, p_b.rot, p_c); + ret.scale = _interpolate(p_a.scale, p_b.scale, p_c); return ret; } -Vector3 Animation::_interpolate( const Vector3& p_a, const Vector3& p_b, float p_c) const { +Vector3 Animation::_interpolate(const Vector3 &p_a, const Vector3 &p_b, float p_c) const { - return p_a.linear_interpolate(p_b,p_c); + return p_a.linear_interpolate(p_b, p_c); } -Quat Animation::_interpolate( const Quat& p_a, const Quat& p_b, float p_c) const { +Quat Animation::_interpolate(const Quat &p_a, const Quat &p_b, float p_c) const { - return p_a.slerp(p_b,p_c); + return p_a.slerp(p_b, p_c); } -Variant Animation::_interpolate( const Variant& p_a, const Variant& p_b, float p_c) const { +Variant Animation::_interpolate(const Variant &p_a, const Variant &p_b, float p_c) const { Variant dst; - Variant::interpolate(p_a,p_b,p_c,dst); + Variant::interpolate(p_a, p_b, p_c, dst); return dst; } +float Animation::_interpolate(const float &p_a, const float &p_b, float p_c) const { -float Animation::_interpolate( const float& p_a, const float& p_b, float p_c) const { - - return p_a*(1.0-p_c) + p_b*p_c; + return p_a * (1.0 - p_c) + p_b * p_c; } -Animation::TransformKey Animation::_cubic_interpolate( const Animation::TransformKey& p_pre_a, const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, const Animation::TransformKey& p_post_b,float p_c) const { - +Animation::TransformKey Animation::_cubic_interpolate(const Animation::TransformKey &p_pre_a, const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, const Animation::TransformKey &p_post_b, float p_c) const { Animation::TransformKey tk; - tk.loc = p_a.loc.cubic_interpolate(p_b.loc,p_pre_a.loc,p_post_b.loc,p_c); - tk.scale = p_a.scale.cubic_interpolate(p_b.scale,p_pre_a.scale,p_post_b.scale,p_c); - tk.rot = p_a.rot.cubic_slerp(p_b.rot,p_pre_a.rot,p_post_b.rot,p_c); + tk.loc = p_a.loc.cubic_interpolate(p_b.loc, p_pre_a.loc, p_post_b.loc, p_c); + tk.scale = p_a.scale.cubic_interpolate(p_b.scale, p_pre_a.scale, p_post_b.scale, p_c); + tk.rot = p_a.rot.cubic_slerp(p_b.rot, p_pre_a.rot, p_post_b.rot, p_c); return tk; - } -Vector3 Animation::_cubic_interpolate( const Vector3& p_pre_a,const Vector3& p_a, const Vector3& p_b,const Vector3& p_post_b, float p_c) const { +Vector3 Animation::_cubic_interpolate(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, float p_c) const { - return p_a.cubic_interpolate(p_b,p_pre_a,p_post_b,p_c); + return p_a.cubic_interpolate(p_b, p_pre_a, p_post_b, p_c); } -Quat Animation::_cubic_interpolate( const Quat& p_pre_a,const Quat& p_a, const Quat& p_b,const Quat& p_post_b, float p_c) const { +Quat Animation::_cubic_interpolate(const Quat &p_pre_a, const Quat &p_a, const Quat &p_b, const Quat &p_post_b, float p_c) const { - return p_a.cubic_slerp(p_b,p_pre_a,p_post_b,p_c); + return p_a.cubic_slerp(p_b, p_pre_a, p_post_b, p_c); } -Variant Animation::_cubic_interpolate( const Variant& p_pre_a,const Variant& p_a, const Variant& p_b, const Variant& p_post_b,float p_c) const { +Variant Animation::_cubic_interpolate(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, float p_c) const { - Variant::Type type_a=p_a.get_type(); - Variant::Type type_b=p_b.get_type(); - Variant::Type type_pa=p_pre_a.get_type(); - Variant::Type type_pb=p_post_b.get_type(); + Variant::Type type_a = p_a.get_type(); + Variant::Type type_b = p_b.get_type(); + Variant::Type type_pa = p_pre_a.get_type(); + Variant::Type type_pb = p_post_b.get_type(); //make int and real play along - uint32_t vformat=1<<type_a; - vformat|=1<<type_b; - vformat|=1<<type_pa; - vformat|=1<<type_pb; + uint32_t vformat = 1 << type_a; + vformat |= 1 << type_b; + vformat |= 1 << type_pa; + vformat |= 1 << type_pb; - if (vformat==((1<<Variant::INT)|(1<<Variant::REAL)) || vformat==(1<<Variant::REAL)) { + if (vformat == ((1 << Variant::INT) | (1 << Variant::REAL)) || vformat == (1 << Variant::REAL)) { //mix of real and int - real_t p0=p_pre_a; - real_t p1=p_a; - real_t p2=p_b; - real_t p3=p_post_b; + real_t p0 = p_pre_a; + real_t p1 = p_a; + real_t p2 = p_b; + real_t p3 = p_post_b; float t = p_c; float t2 = t * t; float t3 = t2 * t; - return - 0.5f * ( ( p1 * 2.0f) + - ( -p0 + p2 ) * t + - ( 2.0f * p0 - 5.0f * p1 + 4 * p2 - p3 ) * t2 + - ( -p0 + 3.0f * p1 - 3.0f * p2 + p3 ) * t3 ); - + return 0.5f * ((p1 * 2.0f) + + (-p0 + p2) * t + + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); } else if ((vformat & (vformat - 1))) { return p_a; //can't interpolate, mix of types } - switch(type_a) { + switch (type_a) { case Variant::VECTOR2: { - Vector2 a=p_a; - Vector2 b=p_b; - Vector2 pa=p_pre_a; - Vector2 pb=p_post_b; + Vector2 a = p_a; + Vector2 b = p_b; + Vector2 pa = p_pre_a; + Vector2 pb = p_post_b; - return a.cubic_interpolate(b,pa,pb,p_c); + return a.cubic_interpolate(b, pa, pb, p_c); } break; case Variant::RECT2: { - Rect2 a=p_a; - Rect2 b=p_b; - Rect2 pa=p_pre_a; - Rect2 pb=p_post_b; + Rect2 a = p_a; + Rect2 b = p_b; + Rect2 pa = p_pre_a; + Rect2 pb = p_post_b; return Rect2( - a.pos.cubic_interpolate(b.pos,pa.pos,pb.pos,p_c), - a.size.cubic_interpolate(b.size,pa.size,pb.size,p_c) - ); + a.pos.cubic_interpolate(b.pos, pa.pos, pb.pos, p_c), + a.size.cubic_interpolate(b.size, pa.size, pb.size, p_c)); } break; case Variant::VECTOR3: { - Vector3 a=p_a; - Vector3 b=p_b; - Vector3 pa=p_pre_a; - Vector3 pb=p_post_b; + Vector3 a = p_a; + Vector3 b = p_b; + Vector3 pa = p_pre_a; + Vector3 pb = p_post_b; - return a.cubic_interpolate(b,pa,pb,p_c); + return a.cubic_interpolate(b, pa, pb, p_c); } break; case Variant::QUAT: { - Quat a=p_a; - Quat b=p_b; - Quat pa=p_pre_a; - Quat pb=p_post_b; + Quat a = p_a; + Quat b = p_b; + Quat pa = p_pre_a; + Quat pb = p_post_b; - return a.cubic_slerp(b,pa,pb,p_c); + return a.cubic_slerp(b, pa, pb, p_c); } break; case Variant::RECT3: { - Rect3 a=p_a; - Rect3 b=p_b; - Rect3 pa=p_pre_a; - Rect3 pb=p_post_b; + Rect3 a = p_a; + Rect3 b = p_b; + Rect3 pa = p_pre_a; + Rect3 pb = p_post_b; return Rect3( - a.pos.cubic_interpolate(b.pos,pa.pos,pb.pos,p_c), - a.size.cubic_interpolate(b.size,pa.size,pb.size,p_c) - ); + a.pos.cubic_interpolate(b.pos, pa.pos, pb.pos, p_c), + a.size.cubic_interpolate(b.size, pa.size, pb.size, p_c)); } break; default: { - return _interpolate(p_a,p_b,p_c); + return _interpolate(p_a, p_b, p_c); } } return Variant(); } -float Animation::_cubic_interpolate( const float& p_pre_a,const float& p_a, const float& p_b, const float& p_post_b, float p_c) const { +float Animation::_cubic_interpolate(const float &p_pre_a, const float &p_a, const float &p_b, const float &p_post_b, float p_c) const { - return _interpolate(p_a,p_b,p_c); + return _interpolate(p_a, p_b, p_c); } -template<class T> -T Animation::_interpolate( const Vector< TKey<T> >& p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap,bool *p_ok) const { +template <class T> +T Animation::_interpolate(const Vector<TKey<T> > &p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok) const { - int len=_find( p_keys, length )+1; // try to find last key (there may be more past the end) + int len = _find(p_keys, length) + 1; // try to find last key (there may be more past the end) - if (len<=0) { + if (len <= 0) { // (-1 or -2 returned originally) (plus one above) // meaning no keys, or only key time is larger than length if (p_ok) - *p_ok=false; + *p_ok = false; return T(); - } else if (len==1) { // one key found (0+1), return it + } else if (len == 1) { // one key found (0+1), return it if (p_ok) - *p_ok=true; + *p_ok = true; return p_keys[0].value; } - int idx=_find(p_keys, p_time); + int idx = _find(p_keys, p_time); - ERR_FAIL_COND_V( idx==-2, T()); + ERR_FAIL_COND_V(idx == -2, T()); if (p_ok) - *p_ok=true; + *p_ok = true; - int next=0; - float c=0; + int next = 0; + float c = 0; // prepare for all cases of interpolation if (loop && p_loop_wrap) { - // loop - if (idx>=0) { + // loop + if (idx >= 0) { - if ((idx+1) < len) { + if ((idx + 1) < len) { - next=idx+1; - float delta=p_keys[next].time - p_keys[idx].time; - float from=p_time-p_keys[idx].time; + next = idx + 1; + float delta = p_keys[next].time - p_keys[idx].time; + float from = p_time - p_keys[idx].time; - if (Math::absf(delta)>CMP_EPSILON) - c=from/delta; + if (Math::absf(delta) > CMP_EPSILON) + c = from / delta; else - c=0; + c = 0; } else { - next=0; - float delta=(length - p_keys[idx].time) + p_keys[next].time; - float from=p_time-p_keys[idx].time; + next = 0; + float delta = (length - p_keys[idx].time) + p_keys[next].time; + float from = p_time - p_keys[idx].time; - if (Math::absf(delta)>CMP_EPSILON) - c=from/delta; + if (Math::absf(delta) > CMP_EPSILON) + c = from / delta; else - c=0; - + c = 0; } } else { // on loop, behind first key - idx=len-1; - next=0; - float endtime=(length - p_keys[idx].time); - if (endtime<0) // may be keys past the end - endtime=0; - float delta=endtime + p_keys[next].time; - float from=endtime+p_time; - - if (Math::absf(delta)>CMP_EPSILON) - c=from/delta; + idx = len - 1; + next = 0; + float endtime = (length - p_keys[idx].time); + if (endtime < 0) // may be keys past the end + endtime = 0; + float delta = endtime + p_keys[next].time; + float from = endtime + p_time; + + if (Math::absf(delta) > CMP_EPSILON) + c = from / delta; else - c=0; + c = 0; } } else { // no loop - if (idx>=0) { + if (idx >= 0) { - if ((idx+1) < len) { + if ((idx + 1) < len) { - next=idx+1; - float delta=p_keys[next].time - p_keys[idx].time; - float from=p_time - p_keys[idx].time; + next = idx + 1; + float delta = p_keys[next].time - p_keys[idx].time; + float from = p_time - p_keys[idx].time; - if (Math::absf(delta)>CMP_EPSILON) - c=from/delta; + if (Math::absf(delta) > CMP_EPSILON) + c = from / delta; else - c=0; + c = 0; } else { - next=idx; + next = idx; } - } else if (idx<0) { + } else if (idx < 0) { - idx=next=0; + idx = next = 0; } - } float tr = p_keys[idx].transition; - if (tr==0 || idx==next) { + if (tr == 0 || idx == next) { // don't interpolate if not needed return p_keys[idx].value; } - if (tr!=1.0) { + if (tr != 1.0) { - c = Math::ease(c,tr); + c = Math::ease(c, tr); } - switch(p_interp) { + switch (p_interp) { case INTERPOLATION_NEAREST: { @@ -1351,66 +1301,59 @@ T Animation::_interpolate( const Vector< TKey<T> >& p_keys, float p_time, Inter return _interpolate(p_keys[idx].value, p_keys[next].value, c); } break; case INTERPOLATION_CUBIC: { - int pre = idx-1; - if (pre<0) - pre=0; - int post = next+1; - if (post>=len) - post=next; + int pre = idx - 1; + if (pre < 0) + pre = 0; + int post = next + 1; + if (post >= len) + post = next; - - return _cubic_interpolate(p_keys[pre].value,p_keys[idx].value, p_keys[next].value,p_keys[post].value, c); + return _cubic_interpolate(p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c); } break; default: return p_keys[idx].value; } // do a barrel roll - - } +Error Animation::transform_track_interpolate(int p_track, float p_time, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const { -Error Animation::transform_track_interpolate(int p_track, float p_time, Vector3 * r_loc, Quat *r_rot, Vector3 *r_scale) const { - - ERR_FAIL_INDEX_V(p_track, tracks.size(),ERR_INVALID_PARAMETER); - Track *t=tracks[p_track]; - ERR_FAIL_COND_V(t->type!=TYPE_TRANSFORM,ERR_INVALID_PARAMETER); + ERR_FAIL_INDEX_V(p_track, tracks.size(), ERR_INVALID_PARAMETER); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, ERR_INVALID_PARAMETER); - TransformTrack * tt = static_cast<TransformTrack*>(t); + TransformTrack *tt = static_cast<TransformTrack *>(t); bool ok; - TransformKey tk = _interpolate( tt->transforms, p_time, tt->interpolation, tt->loop_wrap, &ok ); + TransformKey tk = _interpolate(tt->transforms, p_time, tt->interpolation, tt->loop_wrap, &ok); if (!ok) // ?? return ERR_UNAVAILABLE; if (r_loc) - *r_loc=tk.loc; + *r_loc = tk.loc; if (r_rot) - *r_rot=tk.rot; + *r_rot = tk.rot; if (r_scale) - *r_scale=tk.scale; + *r_scale = tk.scale; return OK; - } Variant Animation::value_track_interpolate(int p_track, float p_time) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),0); - Track *t=tracks[p_track]; - ERR_FAIL_COND_V(t->type!=TYPE_VALUE, Variant()); - ValueTrack * vt = static_cast<ValueTrack*>(t); + ERR_FAIL_INDEX_V(p_track, tracks.size(), 0); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_VALUE, Variant()); + ValueTrack *vt = static_cast<ValueTrack *>(t); bool ok; - - Variant res = _interpolate( vt->values, p_time, vt->update_mode==UPDATE_CONTINUOUS?vt->interpolation:INTERPOLATION_NEAREST,vt->loop_wrap, &ok ); - + Variant res = _interpolate(vt->values, p_time, vt->update_mode == UPDATE_CONTINUOUS ? vt->interpolation : INTERPOLATION_NEAREST, vt->loop_wrap, &ok); if (ok) { @@ -1420,219 +1363,203 @@ Variant Animation::value_track_interpolate(int p_track, float p_time) const { return Variant(); } -void Animation::_value_track_get_key_indices_in_range(const ValueTrack * vt, float from_time, float to_time,List<int> *p_indices) const { +void Animation::_value_track_get_key_indices_in_range(const ValueTrack *vt, float from_time, float to_time, List<int> *p_indices) const { - if (from_time!=length && to_time==length) - to_time=length*1.01; //include a little more if at the end - int to=_find( vt->values, to_time); + if (from_time != length && to_time == length) + to_time = length * 1.01; //include a little more if at the end + int to = _find(vt->values, to_time); // can't really send the events == time, will be sent in the next frame. // if event>=len then it will probably never be requested by the anim player. - if (to>=0 && vt->values[to].time>=to_time) + if (to >= 0 && vt->values[to].time >= to_time) to--; - if (to<0) + if (to < 0) return; // not bother - int from=_find( vt->values, from_time); + int from = _find(vt->values, from_time); // position in the right first event.+ - if (from<0 || vt->values[from].time<from_time) + if (from < 0 || vt->values[from].time < from_time) from++; - int max=vt->values.size(); + int max = vt->values.size(); - for (int i=from;i<=to;i++) { + for (int i = from; i <= to; i++) { - ERR_CONTINUE( i<0 || i>=max); // shouldn't happen + ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen p_indices->push_back(i); } - - } -void Animation::value_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const { +void Animation::value_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; - ERR_FAIL_COND( t->type != TYPE_VALUE ); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_VALUE); - ValueTrack * vt = static_cast<ValueTrack*>(t); + ValueTrack *vt = static_cast<ValueTrack *>(t); - float from_time=p_time-p_delta; - float to_time=p_time; + float from_time = p_time - p_delta; + float to_time = p_time; - if (from_time>to_time) - SWAP(from_time,to_time); + if (from_time > to_time) + SWAP(from_time, to_time); if (loop) { - from_time=Math::fposmod(from_time,length); - to_time=Math::fposmod(to_time,length); + from_time = Math::fposmod(from_time, length); + to_time = Math::fposmod(to_time, length); - if (from_time>to_time) { + if (from_time > to_time) { // handle loop by splitting - _value_track_get_key_indices_in_range(vt,length-from_time,length,p_indices); - _value_track_get_key_indices_in_range(vt,0,to_time,p_indices); + _value_track_get_key_indices_in_range(vt, length - from_time, length, p_indices); + _value_track_get_key_indices_in_range(vt, 0, to_time, p_indices); return; } } else { - if (from_time<0) - from_time=0; - if (from_time>length) - from_time=length; - - if (to_time<0) - to_time=0; - if (to_time>length) - to_time=length; - + if (from_time < 0) + from_time = 0; + if (from_time > length) + from_time = length; + if (to_time < 0) + to_time = 0; + if (to_time > length) + to_time = length; } - _value_track_get_key_indices_in_range(vt,from_time,to_time,p_indices); - - + _value_track_get_key_indices_in_range(vt, from_time, to_time, p_indices); } void Animation::value_track_set_update_mode(int p_track, UpdateMode p_mode) { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; - ERR_FAIL_COND( t->type != TYPE_VALUE ); - ERR_FAIL_INDEX(p_mode,3); - - ValueTrack * vt = static_cast<ValueTrack*>(t); - vt->update_mode=p_mode; + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_VALUE); + ERR_FAIL_INDEX(p_mode, 3); + ValueTrack *vt = static_cast<ValueTrack *>(t); + vt->update_mode = p_mode; } Animation::UpdateMode Animation::value_track_get_update_mode(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), UPDATE_CONTINUOUS); - Track *t=tracks[p_track]; - ERR_FAIL_COND_V( t->type != TYPE_VALUE, UPDATE_CONTINUOUS ); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_VALUE, UPDATE_CONTINUOUS); - ValueTrack * vt = static_cast<ValueTrack*>(t); + ValueTrack *vt = static_cast<ValueTrack *>(t); return vt->update_mode; - } +void Animation::_method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const { -void Animation::_method_track_get_key_indices_in_range(const MethodTrack * mt, float from_time, float to_time,List<int> *p_indices) const { - - if (from_time!=length && to_time==length) - to_time=length*1.01; //include a little more if at the end - + if (from_time != length && to_time == length) + to_time = length * 1.01; //include a little more if at the end - int to=_find( mt->methods, to_time); + int to = _find(mt->methods, to_time); // can't really send the events == time, will be sent in the next frame. // if event>=len then it will probably never be requested by the anim player. - if (to>=0 && mt->methods[to].time>=to_time) + if (to >= 0 && mt->methods[to].time >= to_time) to--; - if (to<0) + if (to < 0) return; // not bother - int from=_find( mt->methods, from_time); + int from = _find(mt->methods, from_time); // position in the right first event.+ - if (from<0 || mt->methods[from].time<from_time) + if (from < 0 || mt->methods[from].time < from_time) from++; - int max=mt->methods.size(); + int max = mt->methods.size(); - for (int i=from;i<=to;i++) { + for (int i = from; i <= to; i++) { - ERR_CONTINUE( i<0 || i>=max); // shouldn't happen + ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen p_indices->push_back(i); } - } -void Animation::method_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const { +void Animation::method_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const { ERR_FAIL_INDEX(p_track, tracks.size()); - Track *t=tracks[p_track]; - ERR_FAIL_COND( t->type != TYPE_METHOD ); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_METHOD); - MethodTrack * mt = static_cast<MethodTrack*>(t); + MethodTrack *mt = static_cast<MethodTrack *>(t); - float from_time=p_time-p_delta; - float to_time=p_time; + float from_time = p_time - p_delta; + float to_time = p_time; - if (from_time>to_time) - SWAP(from_time,to_time); + if (from_time > to_time) + SWAP(from_time, to_time); if (loop) { if (from_time > length || from_time < 0) - from_time=Math::fposmod(from_time,length); + from_time = Math::fposmod(from_time, length); if (to_time > length || to_time < 0) - to_time=Math::fposmod(to_time,length); + to_time = Math::fposmod(to_time, length); - if (from_time>to_time) { + if (from_time > to_time) { // handle loop by splitting - _method_track_get_key_indices_in_range(mt,from_time,length,p_indices); - _method_track_get_key_indices_in_range(mt,0,to_time,p_indices); + _method_track_get_key_indices_in_range(mt, from_time, length, p_indices); + _method_track_get_key_indices_in_range(mt, 0, to_time, p_indices); return; } } else { - if (from_time<0) - from_time=0; - if (from_time>length) - from_time=length; - - if (to_time<0) - to_time=0; - if (to_time>length) - to_time=length; + if (from_time < 0) + from_time = 0; + if (from_time > length) + from_time = length; + if (to_time < 0) + to_time = 0; + if (to_time > length) + to_time = length; } - _method_track_get_key_indices_in_range(mt,from_time,to_time,p_indices); - - + _method_track_get_key_indices_in_range(mt, from_time, to_time, p_indices); } -Vector<Variant> Animation::method_track_get_params(int p_track,int p_key_idx) const { +Vector<Variant> Animation::method_track_get_params(int p_track, int p_key_idx) const { - ERR_FAIL_INDEX_V(p_track, tracks.size(),Vector<Variant>()); - Track *t=tracks[p_track]; - ERR_FAIL_COND_V( t->type != TYPE_METHOD, Vector<Variant>() ); + ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector<Variant>()); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_METHOD, Vector<Variant>()); - MethodTrack * pm = static_cast<MethodTrack*>(t); + MethodTrack *pm = static_cast<MethodTrack *>(t); - ERR_FAIL_INDEX_V( p_key_idx, pm->methods.size(), Vector<Variant>() ); + ERR_FAIL_INDEX_V(p_key_idx, pm->methods.size(), Vector<Variant>()); - const MethodKey& mk=pm->methods[p_key_idx]; + const MethodKey &mk = pm->methods[p_key_idx]; return mk.params; } -StringName Animation::method_track_get_name(int p_track,int p_key_idx) const { - - ERR_FAIL_INDEX_V(p_track, tracks.size(),StringName()); - Track *t=tracks[p_track]; - ERR_FAIL_COND_V( t->type != TYPE_METHOD, StringName() ); +StringName Animation::method_track_get_name(int p_track, int p_key_idx) const { - MethodTrack * pm = static_cast<MethodTrack*>(t); + ERR_FAIL_INDEX_V(p_track, tracks.size(), StringName()); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_METHOD, StringName()); - ERR_FAIL_INDEX_V( p_key_idx, pm->methods.size(), StringName() ); + MethodTrack *pm = static_cast<MethodTrack *>(t); - return pm->methods[ p_key_idx ].method; + ERR_FAIL_INDEX_V(p_key_idx, pm->methods.size(), StringName()); + return pm->methods[p_key_idx].method; } - void Animation::set_length(float p_length) { - ERR_FAIL_COND( length<0 ); - length=p_length; + ERR_FAIL_COND(length < 0); + length = p_length; emit_changed(); } float Animation::get_length() const { @@ -1642,7 +1569,7 @@ float Animation::get_length() const { void Animation::set_loop(bool p_enabled) { - loop=p_enabled; + loop = p_enabled; emit_changed(); } bool Animation::has_loop() const { @@ -1652,286 +1579,271 @@ bool Animation::has_loop() const { void Animation::track_move_up(int p_track) { + if (p_track >= 0 && p_track < (tracks.size() - 1)) { - if (p_track>=0 && p_track<(tracks.size()-1)) { - - SWAP( tracks[p_track], tracks[p_track+1] ); + SWAP(tracks[p_track], tracks[p_track + 1]); } emit_changed(); } -void Animation::track_set_imported(int p_track,bool p_imported) { +void Animation::track_set_imported(int p_track, bool p_imported) { - ERR_FAIL_INDEX(p_track,tracks.size()); - tracks[p_track]->imported=p_imported; + ERR_FAIL_INDEX(p_track, tracks.size()); + tracks[p_track]->imported = p_imported; } -bool Animation::track_is_imported(int p_track) const{ +bool Animation::track_is_imported(int p_track) const { - ERR_FAIL_INDEX_V(p_track,tracks.size(),false); + ERR_FAIL_INDEX_V(p_track, tracks.size(), false); return tracks[p_track]->imported; - } - void Animation::track_move_down(int p_track) { - if (p_track>0 && p_track<tracks.size()) { + if (p_track > 0 && p_track < tracks.size()) { - SWAP( tracks[p_track], tracks[p_track-1] ); + SWAP(tracks[p_track], tracks[p_track - 1]); } emit_changed(); } void Animation::set_step(float p_step) { - step=p_step; + step = p_step; emit_changed(); } -float Animation::get_step() const{ +float Animation::get_step() const { return step; } - void Animation::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_track","type","at_pos"),&Animation::add_track,DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("remove_track","idx"),&Animation::remove_track); - ClassDB::bind_method(D_METHOD("get_track_count"),&Animation::get_track_count); - ClassDB::bind_method(D_METHOD("track_get_type","idx"),&Animation::track_get_type); - ClassDB::bind_method(D_METHOD("track_get_path","idx"),&Animation::track_get_path); - ClassDB::bind_method(D_METHOD("track_set_path","idx","path"),&Animation::track_set_path); - ClassDB::bind_method(D_METHOD("find_track","path"),&Animation::find_track); - - ClassDB::bind_method(D_METHOD("track_move_up","idx"),&Animation::track_move_up); - ClassDB::bind_method(D_METHOD("track_move_down","idx"),&Animation::track_move_down); - - ClassDB::bind_method(D_METHOD("track_set_imported","idx","imported"),&Animation::track_set_imported); - ClassDB::bind_method(D_METHOD("track_is_imported","idx"),&Animation::track_is_imported); - + ClassDB::bind_method(D_METHOD("add_track", "type", "at_pos"), &Animation::add_track, DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("remove_track", "idx"), &Animation::remove_track); + ClassDB::bind_method(D_METHOD("get_track_count"), &Animation::get_track_count); + ClassDB::bind_method(D_METHOD("track_get_type", "idx"), &Animation::track_get_type); + ClassDB::bind_method(D_METHOD("track_get_path", "idx"), &Animation::track_get_path); + ClassDB::bind_method(D_METHOD("track_set_path", "idx", "path"), &Animation::track_set_path); + ClassDB::bind_method(D_METHOD("find_track", "path"), &Animation::find_track); - ClassDB::bind_method(D_METHOD("transform_track_insert_key","idx","time","loc","rot","scale"),&Animation::transform_track_insert_key); - ClassDB::bind_method(D_METHOD("track_insert_key","idx","time","key","transition"),&Animation::track_insert_key,DEFVAL(1)); - ClassDB::bind_method(D_METHOD("track_remove_key","idx","key_idx"),&Animation::track_remove_key); - ClassDB::bind_method(D_METHOD("track_remove_key_at_pos","idx","pos"),&Animation::track_remove_key_at_pos); - ClassDB::bind_method(D_METHOD("track_set_key_value","idx","key","value"),&Animation::track_set_key_value); - ClassDB::bind_method(D_METHOD("track_set_key_transition","idx","key_idx","transition"),&Animation::track_set_key_transition); - ClassDB::bind_method(D_METHOD("track_get_key_transition","idx","key_idx"),&Animation::track_get_key_transition); + ClassDB::bind_method(D_METHOD("track_move_up", "idx"), &Animation::track_move_up); + ClassDB::bind_method(D_METHOD("track_move_down", "idx"), &Animation::track_move_down); - ClassDB::bind_method(D_METHOD("track_get_key_count","idx"),&Animation::track_get_key_count); - ClassDB::bind_method(D_METHOD("track_get_key_value","idx","key_idx"),&Animation::track_get_key_value); - ClassDB::bind_method(D_METHOD("track_get_key_time","idx","key_idx"),&Animation::track_get_key_time); - ClassDB::bind_method(D_METHOD("track_find_key","idx","time","exact"),&Animation::track_find_key,DEFVAL(false)); + ClassDB::bind_method(D_METHOD("track_set_imported", "idx", "imported"), &Animation::track_set_imported); + ClassDB::bind_method(D_METHOD("track_is_imported", "idx"), &Animation::track_is_imported); - ClassDB::bind_method(D_METHOD("track_set_interpolation_type","idx","interpolation"),&Animation::track_set_interpolation_type); - ClassDB::bind_method(D_METHOD("track_get_interpolation_type","idx"),&Animation::track_get_interpolation_type); + ClassDB::bind_method(D_METHOD("transform_track_insert_key", "idx", "time", "loc", "rot", "scale"), &Animation::transform_track_insert_key); + ClassDB::bind_method(D_METHOD("track_insert_key", "idx", "time", "key", "transition"), &Animation::track_insert_key, DEFVAL(1)); + ClassDB::bind_method(D_METHOD("track_remove_key", "idx", "key_idx"), &Animation::track_remove_key); + ClassDB::bind_method(D_METHOD("track_remove_key_at_pos", "idx", "pos"), &Animation::track_remove_key_at_pos); + ClassDB::bind_method(D_METHOD("track_set_key_value", "idx", "key", "value"), &Animation::track_set_key_value); + ClassDB::bind_method(D_METHOD("track_set_key_transition", "idx", "key_idx", "transition"), &Animation::track_set_key_transition); + ClassDB::bind_method(D_METHOD("track_get_key_transition", "idx", "key_idx"), &Animation::track_get_key_transition); - ClassDB::bind_method(D_METHOD("track_set_interpolation_loop_wrap","idx","interpolation"),&Animation::track_set_interpolation_loop_wrap); - ClassDB::bind_method(D_METHOD("track_get_interpolation_loop_wrap","idx"),&Animation::track_get_interpolation_loop_wrap); + ClassDB::bind_method(D_METHOD("track_get_key_count", "idx"), &Animation::track_get_key_count); + ClassDB::bind_method(D_METHOD("track_get_key_value", "idx", "key_idx"), &Animation::track_get_key_value); + ClassDB::bind_method(D_METHOD("track_get_key_time", "idx", "key_idx"), &Animation::track_get_key_time); + ClassDB::bind_method(D_METHOD("track_find_key", "idx", "time", "exact"), &Animation::track_find_key, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("track_set_interpolation_type", "idx", "interpolation"), &Animation::track_set_interpolation_type); + ClassDB::bind_method(D_METHOD("track_get_interpolation_type", "idx"), &Animation::track_get_interpolation_type); - ClassDB::bind_method(D_METHOD("transform_track_interpolate","idx","time_sec"),&Animation::_transform_track_interpolate); - ClassDB::bind_method(D_METHOD("value_track_set_update_mode","idx","mode"),&Animation::value_track_set_update_mode); - ClassDB::bind_method(D_METHOD("value_track_get_update_mode","idx"),&Animation::value_track_get_update_mode); + ClassDB::bind_method(D_METHOD("track_set_interpolation_loop_wrap", "idx", "interpolation"), &Animation::track_set_interpolation_loop_wrap); + ClassDB::bind_method(D_METHOD("track_get_interpolation_loop_wrap", "idx"), &Animation::track_get_interpolation_loop_wrap); - ClassDB::bind_method(D_METHOD("value_track_get_key_indices","idx","time_sec","delta"),&Animation::_value_track_get_key_indices); + ClassDB::bind_method(D_METHOD("transform_track_interpolate", "idx", "time_sec"), &Animation::_transform_track_interpolate); + ClassDB::bind_method(D_METHOD("value_track_set_update_mode", "idx", "mode"), &Animation::value_track_set_update_mode); + ClassDB::bind_method(D_METHOD("value_track_get_update_mode", "idx"), &Animation::value_track_get_update_mode); - ClassDB::bind_method(D_METHOD("method_track_get_key_indices","idx","time_sec","delta"),&Animation::_method_track_get_key_indices); - ClassDB::bind_method(D_METHOD("method_track_get_name","idx","key_idx"),&Animation::method_track_get_name); - ClassDB::bind_method(D_METHOD("method_track_get_params","idx","key_idx"),&Animation::method_track_get_params); + ClassDB::bind_method(D_METHOD("value_track_get_key_indices", "idx", "time_sec", "delta"), &Animation::_value_track_get_key_indices); - ClassDB::bind_method(D_METHOD("set_length","time_sec"),&Animation::set_length); - ClassDB::bind_method(D_METHOD("get_length"),&Animation::get_length); + ClassDB::bind_method(D_METHOD("method_track_get_key_indices", "idx", "time_sec", "delta"), &Animation::_method_track_get_key_indices); + ClassDB::bind_method(D_METHOD("method_track_get_name", "idx", "key_idx"), &Animation::method_track_get_name); + ClassDB::bind_method(D_METHOD("method_track_get_params", "idx", "key_idx"), &Animation::method_track_get_params); - ClassDB::bind_method(D_METHOD("set_loop","enabled"),&Animation::set_loop); - ClassDB::bind_method(D_METHOD("has_loop"),&Animation::has_loop); + ClassDB::bind_method(D_METHOD("set_length", "time_sec"), &Animation::set_length); + ClassDB::bind_method(D_METHOD("get_length"), &Animation::get_length); - ClassDB::bind_method(D_METHOD("set_step","size_sec"),&Animation::set_step); - ClassDB::bind_method(D_METHOD("get_step"),&Animation::get_step); + ClassDB::bind_method(D_METHOD("set_loop", "enabled"), &Animation::set_loop); + ClassDB::bind_method(D_METHOD("has_loop"), &Animation::has_loop); - ClassDB::bind_method(D_METHOD("clear"),&Animation::clear); + ClassDB::bind_method(D_METHOD("set_step", "size_sec"), &Animation::set_step); + ClassDB::bind_method(D_METHOD("get_step"), &Animation::get_step); - BIND_CONSTANT( TYPE_VALUE ); - BIND_CONSTANT( TYPE_TRANSFORM ); - BIND_CONSTANT( TYPE_METHOD ); + ClassDB::bind_method(D_METHOD("clear"), &Animation::clear); - BIND_CONSTANT( INTERPOLATION_NEAREST ); - BIND_CONSTANT( INTERPOLATION_LINEAR ); - BIND_CONSTANT( INTERPOLATION_CUBIC ); - - BIND_CONSTANT( UPDATE_CONTINUOUS ); - BIND_CONSTANT( UPDATE_DISCRETE ); - BIND_CONSTANT( UPDATE_TRIGGER ); + BIND_CONSTANT(TYPE_VALUE); + BIND_CONSTANT(TYPE_TRANSFORM); + BIND_CONSTANT(TYPE_METHOD); + BIND_CONSTANT(INTERPOLATION_NEAREST); + BIND_CONSTANT(INTERPOLATION_LINEAR); + BIND_CONSTANT(INTERPOLATION_CUBIC); + BIND_CONSTANT(UPDATE_CONTINUOUS); + BIND_CONSTANT(UPDATE_DISCRETE); + BIND_CONSTANT(UPDATE_TRIGGER); } void Animation::clear() { - for(int i=0;i<tracks.size();i++) - memdelete( tracks[i] ); + for (int i = 0; i < tracks.size(); i++) + memdelete(tracks[i]); tracks.clear(); - loop=false; - length=1; - + loop = false; + length = 1; } +bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0, const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle, const Vector3 &p_norm) { - -bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0,const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err,float p_alowed_angular_err,float p_max_optimizable_angle,const Vector3& p_norm) { - - - real_t c = (t1.time-t0.time)/(t2.time-t0.time); - real_t t[3]={-1,-1,-1}; + real_t c = (t1.time - t0.time) / (t2.time - t0.time); + real_t t[3] = { -1, -1, -1 }; { //translation - const Vector3 &v0=t0.value.loc; - const Vector3 &v1=t1.value.loc; - const Vector3 &v2=t2.value.loc; + const Vector3 &v0 = t0.value.loc; + const Vector3 &v1 = t1.value.loc; + const Vector3 &v2 = t2.value.loc; - if (v0.distance_to(v2)<CMP_EPSILON) { + if (v0.distance_to(v2) < CMP_EPSILON) { //0 and 2 are close, let's see if 1 is close - if (v0.distance_to(v1)>CMP_EPSILON) { + if (v0.distance_to(v1) > CMP_EPSILON) { //not close, not optimizable return false; } } else { - Vector3 pd = (v2-v0); + Vector3 pd = (v2 - v0); float d0 = pd.dot(v0); float d1 = pd.dot(v1); float d2 = pd.dot(v2); - if (d1<d0 || d1>d2) { + if (d1 < d0 || d1 > d2) { return false; } - Vector3 s[2]={ v0, v2 }; - real_t d =Geometry::get_closest_point_to_segment(v1,s).distance_to(v1); + Vector3 s[2] = { v0, v2 }; + real_t d = Geometry::get_closest_point_to_segment(v1, s).distance_to(v1); - if (d>pd.length()*p_alowed_linear_err) { + if (d > pd.length() * p_alowed_linear_err) { return false; //beyond allowed error for colinearity } - if (p_norm!=Vector3() && Math::acos(pd.normalized().dot(p_norm))>p_alowed_angular_err) + if (p_norm != Vector3() && Math::acos(pd.normalized().dot(p_norm)) > p_alowed_angular_err) return false; - t[0] = (d1-d0)/(d2-d0); + t[0] = (d1 - d0) / (d2 - d0); } } { //rotation - const Quat &q0=t0.value.rot; - const Quat &q1=t1.value.rot; - const Quat &q2=t2.value.rot; + const Quat &q0 = t0.value.rot; + const Quat &q1 = t1.value.rot; + const Quat &q2 = t2.value.rot; //localize both to rotation from q0 - if ((q0-q2).length() < CMP_EPSILON) { + if ((q0 - q2).length() < CMP_EPSILON) { - if ((q0-q1).length() > CMP_EPSILON) + if ((q0 - q1).length() > CMP_EPSILON) return false; } else { - Quat r02 = (q0.inverse() * q2).normalized(); Quat r01 = (q0.inverse() * q1).normalized(); - Vector3 v02,v01; - real_t a02,a01; + Vector3 v02, v01; + real_t a02, a01; - r02.get_axis_and_angle(v02,a02); - r01.get_axis_and_angle(v01,a01); + r02.get_axis_and_angle(v02, a02); + r01.get_axis_and_angle(v01, a01); - if (Math::abs(a02)>p_max_optimizable_angle) + if (Math::abs(a02) > p_max_optimizable_angle) return false; - if (v01.dot(v02)<0) { + if (v01.dot(v02) < 0) { //make sure both rotations go the same way to compare - v02=-v02; - a02=-a02; + v02 = -v02; + a02 = -a02; } - real_t err_01 = Math::acos(v01.normalized().dot(v02.normalized()))/Math_PI; - if (err_01>p_alowed_angular_err) { + real_t err_01 = Math::acos(v01.normalized().dot(v02.normalized())) / Math_PI; + if (err_01 > p_alowed_angular_err) { //not rotating in the same axis return false; } - if (a01*a02 < 0 ) { + if (a01 * a02 < 0) { //not rotating in the same direction return false; } - real_t tr = a01/a02; - if (tr<0 || tr>1) + real_t tr = a01 / a02; + if (tr < 0 || tr > 1) return false; //rotating too much or too less - t[1]=tr; - + t[1] = tr; } - } { //scale - const Vector3 &v0=t0.value.scale; - const Vector3 &v1=t1.value.scale; - const Vector3 &v2=t2.value.scale; + const Vector3 &v0 = t0.value.scale; + const Vector3 &v1 = t1.value.scale; + const Vector3 &v2 = t2.value.scale; - if (v0.distance_to(v2)<CMP_EPSILON) { + if (v0.distance_to(v2) < CMP_EPSILON) { //0 and 2 are close, let's see if 1 is close - if (v0.distance_to(v1)>CMP_EPSILON) { + if (v0.distance_to(v1) > CMP_EPSILON) { //not close, not optimizable return false; } } else { - Vector3 pd = (v2-v0); + Vector3 pd = (v2 - v0); float d0 = pd.dot(v0); float d1 = pd.dot(v1); float d2 = pd.dot(v2); - if (d1<d0 || d1>d2) { + if (d1 < d0 || d1 > d2) { return false; //beyond segment range } - Vector3 s[2]={ v0, v2 }; - real_t d =Geometry::get_closest_point_to_segment(v1,s).distance_to(v1); + Vector3 s[2] = { v0, v2 }; + real_t d = Geometry::get_closest_point_to_segment(v1, s).distance_to(v1); - if (d>pd.length()*p_alowed_linear_err) { + if (d > pd.length() * p_alowed_linear_err) { return false; //beyond allowed error for colinearity } - t[2] = (d1-d0)/(d2-d0); + t[2] = (d1 - d0) / (d2 - d0); } } - bool erase=false; - if (t[0]==-1 && t[1]==-1 && t[2]==-1) { + bool erase = false; + if (t[0] == -1 && t[1] == -1 && t[2] == -1) { - erase=true; + erase = true; } else { - erase=true; - real_t lt=-1; - for(int j=0;j<3;j++) { + erase = true; + real_t lt = -1; + for (int j = 0; j < 3; j++) { //search for t on first, one must be it - if (t[j]!=-1) { - lt=t[j]; //official t + if (t[j] != -1) { + lt = t[j]; //official t //validate rest - for(int k=j+1;k<3;k++) { - if (t[k]==-1) + for (int k = j + 1; k < 3; k++) { + if (t[k] == -1) continue; - if (Math::abs(lt-t[k])>p_alowed_linear_err) { - erase=false; + if (Math::abs(lt - t[k]) > p_alowed_linear_err) { + erase = false; break; } } @@ -1939,102 +1851,86 @@ bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0,const } } - ERR_FAIL_COND_V( lt==-1,false ); + ERR_FAIL_COND_V(lt == -1, false); if (erase) { - if (Math::abs(lt-c)>p_alowed_linear_err) { + if (Math::abs(lt - c) > p_alowed_linear_err) { //todo, evaluate changing the transition if this fails? //this could be done as a second pass and would be //able to optimize more - erase=false; + erase = false; } else { //print_line(itos(i)+"because of interp"); } } - } - return erase; - - } +void Animation::_transform_track_optimize(int p_idx, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle) { -void Animation::_transform_track_optimize(int p_idx,float p_alowed_linear_err,float p_alowed_angular_err,float p_max_optimizable_angle) { - - ERR_FAIL_INDEX(p_idx,tracks.size()); - ERR_FAIL_COND(tracks[p_idx]->type!=TYPE_TRANSFORM); - TransformTrack *tt= static_cast<TransformTrack*>(tracks[p_idx]); - bool prev_erased=false; + ERR_FAIL_INDEX(p_idx, tracks.size()); + ERR_FAIL_COND(tracks[p_idx]->type != TYPE_TRANSFORM); + TransformTrack *tt = static_cast<TransformTrack *>(tracks[p_idx]); + bool prev_erased = false; TKey<TransformKey> first_erased; Vector3 norm; - for(int i=1;i<tt->transforms.size()-1;i++) { + for (int i = 1; i < tt->transforms.size() - 1; i++) { - TKey<TransformKey> &t0 = tt->transforms[i-1]; + TKey<TransformKey> &t0 = tt->transforms[i - 1]; TKey<TransformKey> &t1 = tt->transforms[i]; - TKey<TransformKey> &t2 = tt->transforms[i+1]; + TKey<TransformKey> &t2 = tt->transforms[i + 1]; - bool erase = _transform_track_optimize_key(t0,t1,t2,p_alowed_linear_err,p_alowed_angular_err,p_max_optimizable_angle,norm); + bool erase = _transform_track_optimize_key(t0, t1, t2, p_alowed_linear_err, p_alowed_angular_err, p_max_optimizable_angle, norm); if (erase && !prev_erased) { - norm=(t2.value.loc-t1.value.loc).normalized(); + norm = (t2.value.loc - t1.value.loc).normalized(); } - - if (prev_erased && !_transform_track_optimize_key(t0,first_erased,t2,p_alowed_linear_err,p_alowed_angular_err,p_max_optimizable_angle,norm)) { - //avoid error to go beyond first erased key - erase=false; + if (prev_erased && !_transform_track_optimize_key(t0, first_erased, t2, p_alowed_linear_err, p_alowed_angular_err, p_max_optimizable_angle, norm)) { + //avoid error to go beyond first erased key + erase = false; } - if (erase) { if (!prev_erased) { - first_erased=t1; - prev_erased=true; + first_erased = t1; + prev_erased = true; } tt->transforms.remove(i); i--; } else { - prev_erased=false; - norm=Vector3(); + prev_erased = false; + norm = Vector3(); } } - - } -void Animation::optimize(float p_allowed_linear_err,float p_allowed_angular_err,float p_angle_max) { +void Animation::optimize(float p_allowed_linear_err, float p_allowed_angular_err, float p_angle_max) { - for(int i=0;i<tracks.size();i++) { - - if (tracks[i]->type==TYPE_TRANSFORM) - _transform_track_optimize(i,p_allowed_linear_err,p_allowed_angular_err,p_angle_max); + for (int i = 0; i < tracks.size(); i++) { + if (tracks[i]->type == TYPE_TRANSFORM) + _transform_track_optimize(i, p_allowed_linear_err, p_allowed_angular_err, p_angle_max); } - } - Animation::Animation() { - step=0.1; - loop=false; - length=1; + step = 0.1; + loop = false; + length = 1; } - Animation::~Animation() { - for(int i=0;i<tracks.size();i++) - memdelete( tracks[i] ); - + for (int i = 0; i < tracks.size(); i++) + memdelete(tracks[i]); } - - diff --git a/scene/resources/animation.h b/scene/resources/animation.h index b81ac4f1bf..57ab8b282f 100644 --- a/scene/resources/animation.h +++ b/scene/resources/animation.h @@ -35,12 +35,10 @@ */ class Animation : public Resource { - GDCLASS( Animation, Resource ); + GDCLASS(Animation, Resource); RES_BASE_EXTENSION("anm"); -public: - - +public: enum TrackType { TYPE_VALUE, ///< Set a value in a property, can be interpolated. TYPE_TRANSFORM, ///< Transform a node or a bone. @@ -61,7 +59,6 @@ public: }; private: - struct Track { TrackType type; @@ -69,7 +66,11 @@ private: bool loop_wrap; NodePath path; // path to something bool imported; - Track() { interpolation=INTERPOLATION_LINEAR; imported=false; loop_wrap=true;} + Track() { + interpolation = INTERPOLATION_LINEAR; + imported = false; + loop_wrap = true; + } virtual ~Track() {} }; @@ -77,18 +78,17 @@ private: float transition; float time; // time in secs - Key() { transition=1; } + Key() { transition = 1; } }; // transform key holds either Vector3 or Quaternion - template<class T> + template <class T> struct TKey : public Key { float time; T value; }; - struct TransformKey { Vector3 loc; @@ -100,9 +100,9 @@ private: struct TransformTrack : public Track { - Vector< TKey<TransformKey> > transforms; + Vector<TKey<TransformKey> > transforms; - TransformTrack() { type=TYPE_TRANSFORM; } + TransformTrack() { type = TYPE_TRANSFORM; } }; /* PROPERTY VALUE TRACK */ @@ -111,12 +111,14 @@ private: UpdateMode update_mode; bool update_on_seek; - Vector< TKey<Variant> > values; + Vector<TKey<Variant> > values; - ValueTrack() { type=TYPE_VALUE; update_mode=UPDATE_CONTINUOUS; } + ValueTrack() { + type = TYPE_VALUE; + update_mode = UPDATE_CONTINUOUS; + } }; - /* METHOD TRACK */ struct MethodKey : public Key { @@ -127,56 +129,55 @@ private: struct MethodTrack : public Track { - Vector< MethodKey > methods; - MethodTrack() { type=TYPE_METHOD; } + Vector<MethodKey> methods; + MethodTrack() { type = TYPE_METHOD; } }; - Vector<Track*> tracks; + Vector<Track *> tracks; /* template<class T> int _insert_pos(float p_time, T& p_keys);*/ - template<class T> - void _clear(T& p_keys); + template <class T> + void _clear(T &p_keys); - template<class T, class V> - int _insert(float p_time, T& p_keys, const V& p_value); + template <class T, class V> + int _insert(float p_time, T &p_keys, const V &p_value); - template<class K> - inline int _find( const Vector<K>& p_keys, float p_time) const; + template <class K> + inline int _find(const Vector<K> &p_keys, float p_time) const; - _FORCE_INLINE_ Animation::TransformKey _interpolate( const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, float p_c) const; + _FORCE_INLINE_ Animation::TransformKey _interpolate(const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, float p_c) const; - _FORCE_INLINE_ Vector3 _interpolate( const Vector3& p_a, const Vector3& p_b, float p_c) const; - _FORCE_INLINE_ Quat _interpolate( const Quat& p_a, const Quat& p_b, float p_c) const; - _FORCE_INLINE_ Variant _interpolate( const Variant& p_a, const Variant& p_b, float p_c) const; - _FORCE_INLINE_ float _interpolate( const float& p_a, const float& p_b, float p_c) const; + _FORCE_INLINE_ Vector3 _interpolate(const Vector3 &p_a, const Vector3 &p_b, float p_c) const; + _FORCE_INLINE_ Quat _interpolate(const Quat &p_a, const Quat &p_b, float p_c) const; + _FORCE_INLINE_ Variant _interpolate(const Variant &p_a, const Variant &p_b, float p_c) const; + _FORCE_INLINE_ float _interpolate(const float &p_a, const float &p_b, float p_c) const; - _FORCE_INLINE_ Animation::TransformKey _cubic_interpolate( const Animation::TransformKey& p_pre_a, const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, const Animation::TransformKey& p_post_b,float p_c) const; - _FORCE_INLINE_ Vector3 _cubic_interpolate( const Vector3& p_pre_a,const Vector3& p_a, const Vector3& p_b,const Vector3& p_post_b, float p_c) const; - _FORCE_INLINE_ Quat _cubic_interpolate( const Quat& p_pre_a,const Quat& p_a, const Quat& p_b,const Quat& p_post_b, float p_c) const; - _FORCE_INLINE_ Variant _cubic_interpolate( const Variant& p_pre_a,const Variant& p_a, const Variant& p_b, const Variant& p_post_b,float p_c) const; - _FORCE_INLINE_ float _cubic_interpolate( const float& p_pre_a,const float& p_a, const float& p_b, const float& p_post_b, float p_c) const; + _FORCE_INLINE_ Animation::TransformKey _cubic_interpolate(const Animation::TransformKey &p_pre_a, const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, const Animation::TransformKey &p_post_b, float p_c) const; + _FORCE_INLINE_ Vector3 _cubic_interpolate(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, float p_c) const; + _FORCE_INLINE_ Quat _cubic_interpolate(const Quat &p_pre_a, const Quat &p_a, const Quat &p_b, const Quat &p_post_b, float p_c) const; + _FORCE_INLINE_ Variant _cubic_interpolate(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, float p_c) const; + _FORCE_INLINE_ float _cubic_interpolate(const float &p_pre_a, const float &p_a, const float &p_b, const float &p_post_b, float p_c) const; - template<class T> - _FORCE_INLINE_ T _interpolate( const Vector< TKey<T> >& p_keys, float p_time, InterpolationType p_interp,bool p_loop_wrap,bool *p_ok) const; + template <class T> + _FORCE_INLINE_ T _interpolate(const Vector<TKey<T> > &p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok) const; - _FORCE_INLINE_ void _value_track_get_key_indices_in_range(const ValueTrack * vt, float from_time, float to_time,List<int> *p_indices) const; - _FORCE_INLINE_ void _method_track_get_key_indices_in_range(const MethodTrack * mt, float from_time, float to_time,List<int> *p_indices) const; + _FORCE_INLINE_ void _value_track_get_key_indices_in_range(const ValueTrack *vt, float from_time, float to_time, List<int> *p_indices) const; + _FORCE_INLINE_ void _method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const; float length; float step; bool loop; -// bind helpers + // bind helpers private: - Array _transform_track_interpolate(int p_track, float p_time) const { Vector3 loc; Quat rot; Vector3 scale; - transform_track_interpolate(p_track,p_time,&loc,&rot,&scale); + transform_track_interpolate(p_track, p_time, &loc, &rot, &scale); Array ret; ret.push_back(loc); ret.push_back(rot); @@ -187,10 +188,10 @@ private: PoolVector<int> _value_track_get_key_indices(int p_track, float p_time, float p_delta) const { List<int> idxs; - value_track_get_key_indices(p_track,p_time,p_delta,&idxs); + value_track_get_key_indices(p_track, p_time, p_delta, &idxs); PoolVector<int> idxr; - for (List<int>::Element *E=idxs.front();E;E=E->next()) { + for (List<int>::Element *E = idxs.front(); E; E = E->next()) { idxr.push_back(E->get()); } @@ -199,52 +200,49 @@ private: PoolVector<int> _method_track_get_key_indices(int p_track, float p_time, float p_delta) const { List<int> idxs; - method_track_get_key_indices(p_track,p_time,p_delta,&idxs); + method_track_get_key_indices(p_track, p_time, p_delta, &idxs); PoolVector<int> idxr; - for (List<int>::Element *E=idxs.front();E;E=E->next()) { + for (List<int>::Element *E = idxs.front(); E; E = E->next()) { idxr.push_back(E->get()); } return idxr; } - bool _transform_track_optimize_key(const TKey<TransformKey> &t0,const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err,float p_alowed_angular_err,float p_max_optimizable_angle,const Vector3& p_norm); - void _transform_track_optimize(int p_idx, float p_allowed_err=0.05, float p_alowed_angular_err=0.01,float p_max_optimizable_angle=Math_PI*0.125); + bool _transform_track_optimize_key(const TKey<TransformKey> &t0, const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle, const Vector3 &p_norm); + void _transform_track_optimize(int p_idx, float p_allowed_err = 0.05, float p_alowed_angular_err = 0.01, float p_max_optimizable_angle = Math_PI * 0.125); protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); public: - - int add_track(TrackType p_type,int p_at_pos=-1); + int add_track(TrackType p_type, int p_at_pos = -1); void remove_track(int p_track); int get_track_count() const; TrackType track_get_type(int p_track) const; - void track_set_path(int p_track,const NodePath& p_path); + void track_set_path(int p_track, const NodePath &p_path); NodePath track_get_path(int p_track) const; - int find_track(const NodePath& p_path) const; + int find_track(const NodePath &p_path) const; // transform - void track_move_up(int p_track); void track_move_down(int p_track); - void track_set_imported(int p_track,bool p_imported); + void track_set_imported(int p_track, bool p_imported); bool track_is_imported(int p_track) const; - int transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat& p_rot=Quat(), const Vector3& p_scale=Vector3()); - void track_insert_key(int p_track, float p_time, const Variant& p_key, float p_transition=1); - void track_set_key_transition(int p_track, int p_key_idx,float p_transition); - void track_set_key_value(int p_track, int p_key_idx,const Variant& p_value); - int track_find_key(int p_track, float p_time, bool p_exact=false) const; + int transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot = Quat(), const Vector3 &p_scale = Vector3()); + void track_insert_key(int p_track, float p_time, const Variant &p_key, float p_transition = 1); + void track_set_key_transition(int p_track, int p_key_idx, float p_transition); + void track_set_key_value(int p_track, int p_key_idx, const Variant &p_value); + int track_find_key(int p_track, float p_time, bool p_exact = false) const; void track_remove_key(int p_track, int p_idx); void track_remove_key_at_pos(int p_track, float p_pos); int track_get_key_count(int p_track) const; @@ -252,25 +250,23 @@ public: float track_get_key_time(int p_track, int p_key_idx) const; float track_get_key_transition(int p_track, int p_key_idx) const; - Error transform_track_get_key(int p_track, int p_key, Vector3* r_loc, Quat* r_rot, Vector3* r_scale) const; - void track_set_interpolation_type(int p_track,InterpolationType p_interp); + Error transform_track_get_key(int p_track, int p_key, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const; + void track_set_interpolation_type(int p_track, InterpolationType p_interp); InterpolationType track_get_interpolation_type(int p_track) const; - void track_set_interpolation_loop_wrap(int p_track,bool p_enable); + void track_set_interpolation_loop_wrap(int p_track, bool p_enable); bool track_get_interpolation_loop_wrap(int p_track) const; - Error transform_track_interpolate(int p_track, float p_time, Vector3 * r_loc, Quat *r_rot, Vector3 *r_scale) const; + Error transform_track_interpolate(int p_track, float p_time, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const; Variant value_track_interpolate(int p_track, float p_time) const; - void value_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const; + void value_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const; void value_track_set_update_mode(int p_track, UpdateMode p_mode); UpdateMode value_track_get_update_mode(int p_track) const; - - void method_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const; - Vector<Variant> method_track_get_params(int p_track,int p_key_idx) const; - StringName method_track_get_name(int p_track,int p_key_idx) const; - + void method_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const; + Vector<Variant> method_track_get_params(int p_track, int p_key_idx) const; + StringName method_track_get_name(int p_track, int p_key_idx) const; void set_length(float p_length); float get_length() const; @@ -283,17 +279,14 @@ public: void clear(); - void optimize(float p_allowed_linear_err=0.05,float p_allowed_angular_err=0.01,float p_max_optimizable_angle=Math_PI*0.125); + void optimize(float p_allowed_linear_err = 0.05, float p_allowed_angular_err = 0.01, float p_max_optimizable_angle = Math_PI * 0.125); Animation(); ~Animation(); - }; -VARIANT_ENUM_CAST( Animation::TrackType ); -VARIANT_ENUM_CAST( Animation::InterpolationType ); -VARIANT_ENUM_CAST( Animation::UpdateMode ); - - +VARIANT_ENUM_CAST(Animation::TrackType); +VARIANT_ENUM_CAST(Animation::InterpolationType); +VARIANT_ENUM_CAST(Animation::UpdateMode); #endif diff --git a/scene/resources/audio_stream_resampled.cpp b/scene/resources/audio_stream_resampled.cpp index b2f314a55e..1c0c725ef9 100644 --- a/scene/resources/audio_stream_resampled.cpp +++ b/scene/resources/audio_stream_resampled.cpp @@ -29,7 +29,6 @@ #include "audio_stream_resampled.h" #include "global_config.h" - #if 0 int AudioStreamResampled::get_channel_count() const { diff --git a/scene/resources/audio_stream_sample.cpp b/scene/resources/audio_stream_sample.cpp index 4aee119b0e..b419f4b6be 100644 --- a/scene/resources/audio_stream_sample.cpp +++ b/scene/resources/audio_stream_sample.cpp @@ -30,26 +30,26 @@ void AudioStreamPlaybackSample::start(float p_from_pos) { - for(int i=0;i<2;i++) { - ima_adpcm[i].step_index=0; - ima_adpcm[i].predictor=0; - ima_adpcm[i].loop_step_index=0; - ima_adpcm[i].loop_predictor=0; - ima_adpcm[i].last_nibble=-1; - ima_adpcm[i].loop_pos=0x7FFFFFFF; - ima_adpcm[i].window_ofs=0; - ima_adpcm[i].ptr=(const uint8_t*)base->data; - ima_adpcm[i].ptr+=AudioStreamSample::DATA_PAD; + for (int i = 0; i < 2; i++) { + ima_adpcm[i].step_index = 0; + ima_adpcm[i].predictor = 0; + ima_adpcm[i].loop_step_index = 0; + ima_adpcm[i].loop_predictor = 0; + ima_adpcm[i].last_nibble = -1; + ima_adpcm[i].loop_pos = 0x7FFFFFFF; + ima_adpcm[i].window_ofs = 0; + ima_adpcm[i].ptr = (const uint8_t *)base->data; + ima_adpcm[i].ptr += AudioStreamSample::DATA_PAD; } seek_pos(p_from_pos); - sign=1; - active=true; + sign = 1; + active = true; } void AudioStreamPlaybackSample::stop() { - active=false; + active = false; } bool AudioStreamPlaybackSample::is_playing() const { @@ -64,42 +64,40 @@ int AudioStreamPlaybackSample::get_loop_count() const { float AudioStreamPlaybackSample::get_pos() const { - return float(offset>>MIX_FRAC_BITS)/base->mix_rate; + return float(offset >> MIX_FRAC_BITS) / base->mix_rate; } void AudioStreamPlaybackSample::seek_pos(float p_time) { - if (base->format==AudioStreamSample::FORMAT_IMA_ADPCM) + if (base->format == AudioStreamSample::FORMAT_IMA_ADPCM) return; //no seeking in ima-adpcm - float max=get_length(); - if (p_time<0) { - p_time=0; - } else if (p_time>=max) { - p_time=max-0.001; + float max = get_length(); + if (p_time < 0) { + p_time = 0; + } else if (p_time >= max) { + p_time = max - 0.001; } - offset = uint64_t(p_time * base->mix_rate)<<MIX_FRAC_BITS; + offset = uint64_t(p_time * base->mix_rate) << MIX_FRAC_BITS; } - -template<class Depth,bool is_stereo,bool is_ima_adpcm> -void AudioStreamPlaybackSample::do_resample(const Depth* p_src, AudioFrame *p_dst,int64_t &offset,int32_t &increment,uint32_t amount,IMA_ADPCM_State *ima_adpcm) { +template <class Depth, bool is_stereo, bool is_ima_adpcm> +void AudioStreamPlaybackSample::do_resample(const Depth *p_src, AudioFrame *p_dst, int64_t &offset, int32_t &increment, uint32_t amount, IMA_ADPCM_State *ima_adpcm) { // this function will be compiled branchless by any decent compiler - int32_t final,final_r,next,next_r; + int32_t final, final_r, next, next_r; while (amount--) { - int64_t pos=offset >> MIX_FRAC_BITS; + int64_t pos = offset >> MIX_FRAC_BITS; if (is_stereo && !is_ima_adpcm) - pos<<=1; + pos <<= 1; if (is_ima_adpcm) { int64_t sample_pos = pos + ima_adpcm[0].window_ofs; - while(sample_pos>ima_adpcm[0].last_nibble) { - + while (sample_pos > ima_adpcm[0].last_nibble) { static const int16_t _ima_adpcm_step_table[89] = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, @@ -118,227 +116,215 @@ void AudioStreamPlaybackSample::do_resample(const Depth* p_src, AudioFrame *p_ds -1, -1, -1, -1, 2, 4, 6, 8 }; - for(int i=0;i<(is_stereo?2:1);i++) { + for (int i = 0; i < (is_stereo ? 2 : 1); i++) { - - int16_t nibble,diff,step; + int16_t nibble, diff, step; ima_adpcm[i].last_nibble++; - const uint8_t *src_ptr=ima_adpcm[i].ptr; - - - uint8_t nbb = src_ptr[ (ima_adpcm[i].last_nibble>>1) * (is_stereo?2:1) + i ]; - nibble = (ima_adpcm[i].last_nibble&1)?(nbb>>4):(nbb&0xF); - step=_ima_adpcm_step_table[ima_adpcm[i].step_index]; + const uint8_t *src_ptr = ima_adpcm[i].ptr; + uint8_t nbb = src_ptr[(ima_adpcm[i].last_nibble >> 1) * (is_stereo ? 2 : 1) + i]; + nibble = (ima_adpcm[i].last_nibble & 1) ? (nbb >> 4) : (nbb & 0xF); + step = _ima_adpcm_step_table[ima_adpcm[i].step_index]; ima_adpcm[i].step_index += _ima_adpcm_index_table[nibble]; - if (ima_adpcm[i].step_index<0) - ima_adpcm[i].step_index=0; - if (ima_adpcm[i].step_index>88) - ima_adpcm[i].step_index=88; + if (ima_adpcm[i].step_index < 0) + ima_adpcm[i].step_index = 0; + if (ima_adpcm[i].step_index > 88) + ima_adpcm[i].step_index = 88; - diff = step >> 3 ; + diff = step >> 3; if (nibble & 1) - diff += step >> 2 ; + diff += step >> 2; if (nibble & 2) - diff += step >> 1 ; + diff += step >> 1; if (nibble & 4) - diff += step ; + diff += step; if (nibble & 8) - diff = -diff ; - - ima_adpcm[i].predictor+=diff; - if (ima_adpcm[i].predictor<-0x8000) - ima_adpcm[i].predictor=-0x8000; - else if (ima_adpcm[i].predictor>0x7FFF) - ima_adpcm[i].predictor=0x7FFF; + diff = -diff; + ima_adpcm[i].predictor += diff; + if (ima_adpcm[i].predictor < -0x8000) + ima_adpcm[i].predictor = -0x8000; + else if (ima_adpcm[i].predictor > 0x7FFF) + ima_adpcm[i].predictor = 0x7FFF; /* store loop if there */ - if (ima_adpcm[i].last_nibble==ima_adpcm[i].loop_pos) { + if (ima_adpcm[i].last_nibble == ima_adpcm[i].loop_pos) { ima_adpcm[i].loop_step_index = ima_adpcm[i].step_index; ima_adpcm[i].loop_predictor = ima_adpcm[i].predictor; } //printf("%i - %i - pred %i\n",int(ima_adpcm[i].last_nibble),int(nibble),int(ima_adpcm[i].predictor)); - } - } - final=ima_adpcm[0].predictor; + final = ima_adpcm[0].predictor; if (is_stereo) { - final_r=ima_adpcm[1].predictor; + final_r = ima_adpcm[1].predictor; } } else { - final=p_src[pos]; + final = p_src[pos]; if (is_stereo) - final_r=p_src[pos+1]; + final_r = p_src[pos + 1]; - if (sizeof(Depth)==1) { /* conditions will not exist anymore when compiled! */ - final<<=8; + if (sizeof(Depth) == 1) { /* conditions will not exist anymore when compiled! */ + final <<= 8; if (is_stereo) - final_r<<=8; + final_r <<= 8; } if (is_stereo) { - next=p_src[pos+2]; - next_r=p_src[pos+3]; + next = p_src[pos + 2]; + next_r = p_src[pos + 3]; } else { - next=p_src[pos+1]; + next = p_src[pos + 1]; } - if (sizeof(Depth)==1) { - next<<=8; + if (sizeof(Depth) == 1) { + next <<= 8; if (is_stereo) - next_r<<=8; + next_r <<= 8; } - int32_t frac=int64_t(offset&MIX_FRAC_MASK); + int32_t frac = int64_t(offset & MIX_FRAC_MASK); - final=final+((next-final)*frac >> MIX_FRAC_BITS); + final = final + ((next - final) * frac >> MIX_FRAC_BITS); if (is_stereo) - final_r=final_r+((next_r-final_r)*frac >> MIX_FRAC_BITS); - + final_r = final_r + ((next_r - final_r) * frac >> MIX_FRAC_BITS); } - if (!is_stereo) { - final_r=final; //copy to right channel if stereo + final_r = final; //copy to right channel if stereo } - p_dst->l=final/32767.0; - p_dst->r=final_r/32767.0; + p_dst->l = final / 32767.0; + p_dst->r = final_r / 32767.0; p_dst++; - offset+=increment; + offset += increment; } } -void AudioStreamPlaybackSample::mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames) { +void AudioStreamPlaybackSample::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) { if (!base->data || !active) { - for(int i=0;i<p_frames;i++) { - p_buffer[i]=AudioFrame(0,0); + for (int i = 0; i < p_frames; i++) { + p_buffer[i] = AudioFrame(0, 0); } return; } int len = base->data_bytes; - switch(base->format) { - case AudioStreamSample::FORMAT_8_BITS: len/=1; break; - case AudioStreamSample::FORMAT_16_BITS: len/=2; break; - case AudioStreamSample::FORMAT_IMA_ADPCM: len*=2; break; + switch (base->format) { + case AudioStreamSample::FORMAT_8_BITS: len /= 1; break; + case AudioStreamSample::FORMAT_16_BITS: len /= 2; break; + case AudioStreamSample::FORMAT_IMA_ADPCM: len *= 2; break; } if (base->stereo) { - len/=2; + len /= 2; } /* some 64-bit fixed point precaches */ - int64_t loop_begin_fp=((int64_t)len<< MIX_FRAC_BITS); - int64_t loop_end_fp=((int64_t)base->loop_end << MIX_FRAC_BITS); - int64_t length_fp=((int64_t)len << MIX_FRAC_BITS); - int64_t begin_limit=(base->loop_mode!=AudioStreamSample::LOOP_DISABLED)?loop_begin_fp:0; - int64_t end_limit=(base->loop_mode!=AudioStreamSample::LOOP_DISABLED)?loop_end_fp:length_fp; - bool is_stereo=base->stereo; + int64_t loop_begin_fp = ((int64_t)len << MIX_FRAC_BITS); + int64_t loop_end_fp = ((int64_t)base->loop_end << MIX_FRAC_BITS); + int64_t length_fp = ((int64_t)len << MIX_FRAC_BITS); + int64_t begin_limit = (base->loop_mode != AudioStreamSample::LOOP_DISABLED) ? loop_begin_fp : 0; + int64_t end_limit = (base->loop_mode != AudioStreamSample::LOOP_DISABLED) ? loop_end_fp : length_fp; + bool is_stereo = base->stereo; - int32_t todo=p_frames; + int32_t todo = p_frames; float base_rate = AudioServer::get_singleton()->get_mix_rate(); float srate = base->mix_rate; - srate*=p_rate_scale; + srate *= p_rate_scale; float fincrement = srate / base_rate; int32_t increment = int32_t(fincrement * MIX_FRAC_LEN); - increment*=sign; - + increment *= sign; //looping - AudioStreamSample::LoopMode loop_format=base->loop_mode; + AudioStreamSample::LoopMode loop_format = base->loop_mode; AudioStreamSample::Format format = base->format; - /* audio data */ - uint8_t *dataptr=(uint8_t*)base->data; - const void *data=dataptr+AudioStreamSample::DATA_PAD; - AudioFrame *dst_buff=p_buffer; - + uint8_t *dataptr = (uint8_t *)base->data; + const void *data = dataptr + AudioStreamSample::DATA_PAD; + AudioFrame *dst_buff = p_buffer; - if (format==AudioStreamSample::FORMAT_IMA_ADPCM) { + if (format == AudioStreamSample::FORMAT_IMA_ADPCM) { - if (loop_format!=AudioStreamSample::LOOP_DISABLED) { - ima_adpcm[0].loop_pos=loop_begin_fp>>MIX_FRAC_BITS; - ima_adpcm[1].loop_pos=loop_begin_fp>>MIX_FRAC_BITS; - loop_format=AudioStreamSample::LOOP_FORWARD; + if (loop_format != AudioStreamSample::LOOP_DISABLED) { + ima_adpcm[0].loop_pos = loop_begin_fp >> MIX_FRAC_BITS; + ima_adpcm[1].loop_pos = loop_begin_fp >> MIX_FRAC_BITS; + loop_format = AudioStreamSample::LOOP_FORWARD; } } - while (todo>0) { + while (todo > 0) { - int64_t limit=0; - int32_t target=0,aux=0; + int64_t limit = 0; + int32_t target = 0, aux = 0; /** LOOP CHECKING **/ - if ( increment < 0 ) { + if (increment < 0) { /* going backwards */ - if ( loop_format!=AudioStreamSample::LOOP_DISABLED && offset < loop_begin_fp ) { + if (loop_format != AudioStreamSample::LOOP_DISABLED && offset < loop_begin_fp) { /* loopstart reached */ - if ( loop_format==AudioStreamSample::LOOP_PING_PONG ) { + if (loop_format == AudioStreamSample::LOOP_PING_PONG) { /* bounce ping pong */ - offset= loop_begin_fp + ( loop_begin_fp-offset ); - increment=-increment; - sign*=-1; + offset = loop_begin_fp + (loop_begin_fp - offset); + increment = -increment; + sign *= -1; } else { /* go to loop-end */ - offset=loop_end_fp-(loop_begin_fp-offset); + offset = loop_end_fp - (loop_begin_fp - offset); } } else { /* check for sample not reaching begining */ - if(offset < 0) { + if (offset < 0) { - active=false; + active = false; break; } } } else { /* going forward */ - if( loop_format!=AudioStreamSample::LOOP_DISABLED && offset >= loop_end_fp ) { + if (loop_format != AudioStreamSample::LOOP_DISABLED && offset >= loop_end_fp) { /* loopend reached */ - if ( loop_format==AudioStreamSample::LOOP_PING_PONG ) { + if (loop_format == AudioStreamSample::LOOP_PING_PONG) { /* bounce ping pong */ - offset=loop_end_fp-(offset-loop_end_fp); - increment=-increment; - sign*=-1; + offset = loop_end_fp - (offset - loop_end_fp); + increment = -increment; + sign *= -1; } else { /* go to loop-begin */ - if (format==AudioStreamSample::FORMAT_IMA_ADPCM) { - for(int i=0;i<2;i++) { - ima_adpcm[i].step_index=ima_adpcm[i].loop_step_index; - ima_adpcm[i].predictor=ima_adpcm[i].loop_predictor; - ima_adpcm[i].last_nibble=loop_begin_fp>>MIX_FRAC_BITS; + if (format == AudioStreamSample::FORMAT_IMA_ADPCM) { + for (int i = 0; i < 2; i++) { + ima_adpcm[i].step_index = ima_adpcm[i].loop_step_index; + ima_adpcm[i].predictor = ima_adpcm[i].loop_predictor; + ima_adpcm[i].last_nibble = loop_begin_fp >> MIX_FRAC_BITS; } - offset=loop_begin_fp; + offset = loop_begin_fp; } else { - offset=loop_begin_fp+(offset-loop_end_fp); + offset = loop_begin_fp + (offset - loop_end_fp); } - } } else { /* no loop, check for end of sample */ - if(offset >= length_fp) { + if (offset >= length_fp) { - active=false; + active = false; break; } } @@ -347,160 +333,151 @@ void AudioStreamPlaybackSample::mix(AudioFrame* p_buffer,float p_rate_scale,int /** MIXCOUNT COMPUTING **/ /* next possible limit (looppoints or sample begin/end */ - limit=(increment < 0) ?begin_limit:end_limit; + limit = (increment < 0) ? begin_limit : end_limit; /* compute what is shorter, the todo or the limit? */ - aux=(limit-offset)/increment+1; - target=(aux<todo)?aux:todo; /* mix target is the shorter buffer */ + aux = (limit - offset) / increment + 1; + target = (aux < todo) ? aux : todo; /* mix target is the shorter buffer */ /* check just in case */ - if ( target<=0 ) { - active=false; + if (target <= 0) { + active = false; break; } - todo-=target; + todo -= target; - switch(base->format) { + switch (base->format) { case AudioStreamSample::FORMAT_8_BITS: { if (is_stereo) - do_resample<int8_t,true,false>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm); + do_resample<int8_t, true, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm); else - do_resample<int8_t,false,false>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm); + do_resample<int8_t, false, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm); } break; case AudioStreamSample::FORMAT_16_BITS: { if (is_stereo) - do_resample<int16_t,true,false>((int16_t*)data,dst_buff,offset,increment,target,ima_adpcm); + do_resample<int16_t, true, false>((int16_t *)data, dst_buff, offset, increment, target, ima_adpcm); else - do_resample<int16_t,false,false>((int16_t*)data,dst_buff,offset,increment,target,ima_adpcm); + do_resample<int16_t, false, false>((int16_t *)data, dst_buff, offset, increment, target, ima_adpcm); } break; case AudioStreamSample::FORMAT_IMA_ADPCM: { if (is_stereo) - do_resample<int8_t,true,true>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm); + do_resample<int8_t, true, true>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm); else - do_resample<int8_t,false,true>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm); + do_resample<int8_t, false, true>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm); } break; } - dst_buff+=target; - + dst_buff += target; } - - } float AudioStreamPlaybackSample::get_length() const { int len = base->data_bytes; - switch(base->format) { - case AudioStreamSample::FORMAT_8_BITS: len/=1; break; - case AudioStreamSample::FORMAT_16_BITS: len/=2; break; - case AudioStreamSample::FORMAT_IMA_ADPCM: len*=2; break; + switch (base->format) { + case AudioStreamSample::FORMAT_8_BITS: len /= 1; break; + case AudioStreamSample::FORMAT_16_BITS: len /= 2; break; + case AudioStreamSample::FORMAT_IMA_ADPCM: len *= 2; break; } if (base->stereo) { - len/=2; + len /= 2; } - - return float(len)/base->mix_rate; + return float(len) / base->mix_rate; } - AudioStreamPlaybackSample::AudioStreamPlaybackSample() { - active=false; - offset=0; - sign=1; + active = false; + offset = 0; + sign = 1; } - ///////////////////// - void AudioStreamSample::set_format(Format p_format) { - format=p_format; + format = p_format; } -AudioStreamSample::Format AudioStreamSample::get_format() const{ +AudioStreamSample::Format AudioStreamSample::get_format() const { return format; } -void AudioStreamSample::set_loop_mode(LoopMode p_loop_mode){ +void AudioStreamSample::set_loop_mode(LoopMode p_loop_mode) { - loop_mode=p_loop_mode; + loop_mode = p_loop_mode; } -AudioStreamSample::LoopMode AudioStreamSample::get_loop_mode() const{ +AudioStreamSample::LoopMode AudioStreamSample::get_loop_mode() const { return loop_mode; } -void AudioStreamSample::set_loop_begin(int p_frame){ +void AudioStreamSample::set_loop_begin(int p_frame) { - loop_begin=p_frame; + loop_begin = p_frame; } -int AudioStreamSample::get_loop_begin() const{ +int AudioStreamSample::get_loop_begin() const { return loop_begin; } -void AudioStreamSample::set_loop_end(int p_frame){ +void AudioStreamSample::set_loop_end(int p_frame) { - loop_end=p_frame; + loop_end = p_frame; } -int AudioStreamSample::get_loop_end() const{ +int AudioStreamSample::get_loop_end() const { return loop_end; } +void AudioStreamSample::set_mix_rate(int p_hz) { -void AudioStreamSample::set_mix_rate(int p_hz){ - - mix_rate=p_hz; + mix_rate = p_hz; } -int AudioStreamSample::get_mix_rate() const{ +int AudioStreamSample::get_mix_rate() const { return mix_rate; } -void AudioStreamSample::set_stereo(bool p_enable){ +void AudioStreamSample::set_stereo(bool p_enable) { - stereo=p_enable; + stereo = p_enable; } -bool AudioStreamSample::is_stereo() const{ +bool AudioStreamSample::is_stereo() const { return stereo; } -void AudioStreamSample::set_data(const PoolVector<uint8_t>& p_data) { +void AudioStreamSample::set_data(const PoolVector<uint8_t> &p_data) { AudioServer::get_singleton()->lock(); if (data) { AudioServer::get_singleton()->audio_data_free(data); - data=NULL; - data_bytes=0; + data = NULL; + data_bytes = 0; } int datalen = p_data.size(); if (datalen) { PoolVector<uint8_t>::Read r = p_data.read(); - int alloc_len = datalen+DATA_PAD*2; + int alloc_len = datalen + DATA_PAD * 2; data = AudioServer::get_singleton()->audio_data_alloc(alloc_len); //alloc with some padding for interpolation - zeromem(data,alloc_len); - uint8_t *dataptr=(uint8_t*)data; - copymem(dataptr+DATA_PAD,r.ptr(),datalen); - data_bytes=datalen; + zeromem(data, alloc_len); + uint8_t *dataptr = (uint8_t *)data; + copymem(dataptr + DATA_PAD, r.ptr(), datalen); + data_bytes = datalen; } AudioServer::get_singleton()->unlock(); - } -PoolVector<uint8_t> AudioStreamSample::get_data() const{ +PoolVector<uint8_t> AudioStreamSample::get_data() const { PoolVector<uint8_t> pv; @@ -508,20 +485,19 @@ PoolVector<uint8_t> AudioStreamSample::get_data() const{ pv.resize(data_bytes); { - PoolVector<uint8_t>::Write w =pv.write(); - copymem(w.ptr(),data,data_bytes); + PoolVector<uint8_t>::Write w = pv.write(); + copymem(w.ptr(), data, data_bytes); } } return pv; } - Ref<AudioStreamPlayback> AudioStreamSample::instance_playback() { Ref<AudioStreamPlaybackSample> sample; sample.instance(); - sample->base=Ref<AudioStreamSample>(this); + sample->base = Ref<AudioStreamSample>(this); return sample; } @@ -532,54 +508,51 @@ String AudioStreamSample::get_stream_name() const { void AudioStreamSample::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_format","format"),&AudioStreamSample::set_format); - ClassDB::bind_method(D_METHOD("get_format"),&AudioStreamSample::get_format); - - ClassDB::bind_method(D_METHOD("set_loop_mode","loop_mode"),&AudioStreamSample::set_loop_mode); - ClassDB::bind_method(D_METHOD("get_loop_mode"),&AudioStreamSample::get_loop_mode); + ClassDB::bind_method(D_METHOD("set_format", "format"), &AudioStreamSample::set_format); + ClassDB::bind_method(D_METHOD("get_format"), &AudioStreamSample::get_format); - ClassDB::bind_method(D_METHOD("set_loop_begin","loop_begin"),&AudioStreamSample::set_loop_begin); - ClassDB::bind_method(D_METHOD("get_loop_begin"),&AudioStreamSample::get_loop_begin); + ClassDB::bind_method(D_METHOD("set_loop_mode", "loop_mode"), &AudioStreamSample::set_loop_mode); + ClassDB::bind_method(D_METHOD("get_loop_mode"), &AudioStreamSample::get_loop_mode); - ClassDB::bind_method(D_METHOD("set_loop_end","loop_end"),&AudioStreamSample::set_loop_end); - ClassDB::bind_method(D_METHOD("get_loop_end"),&AudioStreamSample::get_loop_end); + ClassDB::bind_method(D_METHOD("set_loop_begin", "loop_begin"), &AudioStreamSample::set_loop_begin); + ClassDB::bind_method(D_METHOD("get_loop_begin"), &AudioStreamSample::get_loop_begin); - ClassDB::bind_method(D_METHOD("set_mix_rate","mix_rate"),&AudioStreamSample::set_mix_rate); - ClassDB::bind_method(D_METHOD("get_mix_rate"),&AudioStreamSample::get_mix_rate); + ClassDB::bind_method(D_METHOD("set_loop_end", "loop_end"), &AudioStreamSample::set_loop_end); + ClassDB::bind_method(D_METHOD("get_loop_end"), &AudioStreamSample::get_loop_end); - ClassDB::bind_method(D_METHOD("set_stereo","stereo"),&AudioStreamSample::set_stereo); - ClassDB::bind_method(D_METHOD("is_stereo"),&AudioStreamSample::is_stereo); + ClassDB::bind_method(D_METHOD("set_mix_rate", "mix_rate"), &AudioStreamSample::set_mix_rate); + ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioStreamSample::get_mix_rate); - ClassDB::bind_method(D_METHOD("set_data","data"),&AudioStreamSample::set_data); - ClassDB::bind_method(D_METHOD("get_data"),&AudioStreamSample::get_data); + ClassDB::bind_method(D_METHOD("set_stereo", "stereo"), &AudioStreamSample::set_stereo); + ClassDB::bind_method(D_METHOD("is_stereo"), &AudioStreamSample::is_stereo); - ADD_PROPERTY(PropertyInfo(Variant::INT,"format",PROPERTY_HINT_ENUM,"8-Bit,16-Bit,IMA-ADPCM"),"set_format","get_format"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"loop_mode",PROPERTY_HINT_ENUM,"Disabled,Forward,Ping-Pong"),"set_loop_mode","get_loop_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"loop_begin"),"set_loop_begin","get_loop_begin"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"loop_end"),"set_loop_end","get_loop_end"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"mix_rate"),"set_mix_rate","get_mix_rate"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"stereo"),"set_stereo","is_stereo"); - ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_data","get_data"); + ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamSample::set_data); + ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamSample::get_data); + ADD_PROPERTY(PropertyInfo(Variant::INT, "format", PROPERTY_HINT_ENUM, "8-Bit,16-Bit,IMA-ADPCM"), "set_format", "get_format"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode", PROPERTY_HINT_ENUM, "Disabled,Forward,Ping-Pong"), "set_loop_mode", "get_loop_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_begin"), "set_loop_begin", "get_loop_begin"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_end"), "set_loop_end", "get_loop_end"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_rate"), "set_mix_rate", "get_mix_rate"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stereo"), "set_stereo", "is_stereo"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); } -AudioStreamSample::AudioStreamSample() -{ - format=FORMAT_8_BITS; - loop_mode=LOOP_DISABLED; - stereo=false; - loop_begin=0; - loop_end=0; - mix_rate=44100; - data=NULL; - data_bytes=0; +AudioStreamSample::AudioStreamSample() { + format = FORMAT_8_BITS; + loop_mode = LOOP_DISABLED; + stereo = false; + loop_begin = 0; + loop_end = 0; + mix_rate = 44100; + data = NULL; + data_bytes = 0; } AudioStreamSample::~AudioStreamSample() { - if (data) { AudioServer::get_singleton()->audio_data_free(data); - data=NULL; - data_bytes=0; + data = NULL; + data_bytes = 0; } } diff --git a/scene/resources/audio_stream_sample.h b/scene/resources/audio_stream_sample.h index 53e628c0e4..d5d1ae79c0 100644 --- a/scene/resources/audio_stream_sample.h +++ b/scene/resources/audio_stream_sample.h @@ -31,16 +31,15 @@ #include "servers/audio/audio_stream.h" - class AudioStreamSample; class AudioStreamPlaybackSample : public AudioStreamPlayback { - GDCLASS( AudioStreamPlaybackSample, AudioStreamPlayback ) + GDCLASS(AudioStreamPlaybackSample, AudioStreamPlayback) enum { - MIX_FRAC_BITS=13, - MIX_FRAC_LEN=(1<<MIX_FRAC_BITS), - MIX_FRAC_MASK=MIX_FRAC_LEN-1, + MIX_FRAC_BITS = 13, + MIX_FRAC_LEN = (1 << MIX_FRAC_BITS), + MIX_FRAC_MASK = MIX_FRAC_LEN - 1, }; struct IMA_ADPCM_State { @@ -59,14 +58,14 @@ class AudioStreamPlaybackSample : public AudioStreamPlayback { int64_t offset; int sign; bool active; -friend class AudioStreamSample; + friend class AudioStreamSample; Ref<AudioStreamSample> base; - template<class Depth,bool is_stereo,bool is_ima_adpcm> - void do_resample(const Depth* p_src, AudioFrame *p_dst,int64_t &offset,int32_t &increment,uint32_t amount,IMA_ADPCM_State *ima_adpcm); -public: + template <class Depth, bool is_stereo, bool is_ima_adpcm> + void do_resample(const Depth *p_src, AudioFrame *p_dst, int64_t &offset, int32_t &increment, uint32_t amount, IMA_ADPCM_State *ima_adpcm); - virtual void start(float p_from_pos=0.0); +public: + virtual void start(float p_from_pos = 0.0); virtual void stop(); virtual bool is_playing() const; @@ -75,20 +74,18 @@ public: virtual float get_pos() const; virtual void seek_pos(float p_time); - virtual void mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames); + virtual void mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames); virtual float get_length() const; //if supported, otherwise return 0 - AudioStreamPlaybackSample(); }; class AudioStreamSample : public AudioStream { - GDCLASS(AudioStreamSample,AudioStream) + GDCLASS(AudioStreamSample, AudioStream) RES_BASE_EXTENSION("smp") public: - enum Format { FORMAT_8_BITS, FORMAT_16_BITS, @@ -101,12 +98,11 @@ public: LOOP_PING_PONG }; - private: -friend class AudioStreamPlaybackSample; + friend class AudioStreamPlaybackSample; enum { - DATA_PAD=16 //padding for interpolation + DATA_PAD = 16 //padding for interpolation }; Format format; @@ -117,9 +113,10 @@ friend class AudioStreamPlaybackSample; int mix_rate; void *data; uint32_t data_bytes; -protected: +protected: static void _bind_methods(); + public: void set_format(Format p_format); Format get_format() const; @@ -139,10 +136,9 @@ public: void set_stereo(bool p_enable); bool is_stereo() const; - void set_data(const PoolVector<uint8_t>& p_data); + void set_data(const PoolVector<uint8_t> &p_data); PoolVector<uint8_t> get_data() const; - virtual Ref<AudioStreamPlayback> instance_playback(); virtual String get_stream_name() const; diff --git a/scene/resources/baked_light.cpp b/scene/resources/baked_light.cpp index 616c12e8d7..7fa930fd58 100644 --- a/scene/resources/baked_light.cpp +++ b/scene/resources/baked_light.cpp @@ -28,4 +28,3 @@ /*************************************************************************/ #include "baked_light.h" #include "servers/visual_server.h" - diff --git a/scene/resources/baked_light.h b/scene/resources/baked_light.h index 0c69ce429e..7dee40b34e 100644 --- a/scene/resources/baked_light.h +++ b/scene/resources/baked_light.h @@ -32,6 +32,4 @@ #include "resource.h" #include "scene/resources/texture.h" - - #endif // BAKED_LIGHT_H diff --git a/scene/resources/bit_mask.cpp b/scene/resources/bit_mask.cpp index 4ceac5af0c..277acad905 100644 --- a/scene/resources/bit_mask.cpp +++ b/scene/resources/bit_mask.cpp @@ -29,177 +29,166 @@ #include "bit_mask.h" #include "io/image_loader.h" -void BitMap::create(const Size2& p_size) { +void BitMap::create(const Size2 &p_size) { - ERR_FAIL_COND(p_size.width<1); - ERR_FAIL_COND(p_size.height<1); - - width=p_size.width; - height=p_size.height; - bitmask.resize(((width*height)/8)+1); - zeromem(bitmask.ptr(),bitmask.size()); + ERR_FAIL_COND(p_size.width < 1); + ERR_FAIL_COND(p_size.height < 1); + width = p_size.width; + height = p_size.height; + bitmask.resize(((width * height) / 8) + 1); + zeromem(bitmask.ptr(), bitmask.size()); } -void BitMap::create_from_image_alpha(const Image& p_image){ +void BitMap::create_from_image_alpha(const Image &p_image) { ERR_FAIL_COND(p_image.empty()); - Image img=p_image; + Image img = p_image; img.convert(Image::FORMAT_LA8); - ERR_FAIL_COND(img.get_format()!=Image::FORMAT_LA8); - - create(Size2(img.get_width(),img.get_height())); + ERR_FAIL_COND(img.get_format() != Image::FORMAT_LA8); + create(Size2(img.get_width(), img.get_height())); PoolVector<uint8_t>::Read r = img.get_data().read(); uint8_t *w = bitmask.ptr(); - for(int i=0;i<width*height;i++) { + for (int i = 0; i < width * height; i++) { - int bbyte = i/8; + int bbyte = i / 8; int bbit = i % 8; - if (r[i*2]) - w[bbyte]|=(1<<bbit); + if (r[i * 2]) + w[bbyte] |= (1 << bbit); } - } +void BitMap::set_bit_rect(const Rect2 &p_rect, bool p_value) { -void BitMap::set_bit_rect(const Rect2& p_rect,bool p_value) { - - Rect2i current = Rect2i(0,0,width,height).clip(p_rect); + Rect2i current = Rect2i(0, 0, width, height).clip(p_rect); uint8_t *data = bitmask.ptr(); - for(int i=current.pos.x;i<current.pos.x+current.size.x;i++) { - - for(int j=current.pos.y;j<current.pos.y+current.size.y;j++) { + for (int i = current.pos.x; i < current.pos.x + current.size.x; i++) { + for (int j = current.pos.y; j < current.pos.y + current.size.y; j++) { int ofs = width * j + i; - int bbyte = ofs/8; + int bbyte = ofs / 8; int bbit = ofs % 8; uint8_t b = data[bbyte]; if (p_value) - b|=(1<<bbit); + b |= (1 << bbit); else - b&=!(1<<bbit); - - data[bbyte]=b; + b &= !(1 << bbit); + data[bbyte] = b; } } - } int BitMap::get_true_bit_count() const { int ds = bitmask.size(); const uint8_t *d = bitmask.ptr(); - int c=0; + int c = 0; -//fast, almot branchless version + //fast, almot branchless version - for(int i=0;i<ds;i++) { + for (int i = 0; i < ds; i++) { - c+=(d[i]&(1<<7))>>7; - c+=(d[i]&(1<<6))>>6; - c+=(d[i]&(1<<5))>>5; - c+=(d[i]&(1<<4))>>4; - c+=(d[i]&(1<<3))>>3; - c+=(d[i]&(1<<2))>>2; - c+=d[i]&1; + c += (d[i] & (1 << 7)) >> 7; + c += (d[i] & (1 << 6)) >> 6; + c += (d[i] & (1 << 5)) >> 5; + c += (d[i] & (1 << 4)) >> 4; + c += (d[i] & (1 << 3)) >> 3; + c += (d[i] & (1 << 2)) >> 2; + c += d[i] & 1; } return c; } +void BitMap::set_bit(const Point2 &p_pos, bool p_value) { -void BitMap::set_bit(const Point2& p_pos,bool p_value){ - - int x=Math::fast_ftoi(p_pos.x); - int y=Math::fast_ftoi(p_pos.y); + int x = Math::fast_ftoi(p_pos.x); + int y = Math::fast_ftoi(p_pos.y); - ERR_FAIL_INDEX(x,width); - ERR_FAIL_INDEX(y,height); + ERR_FAIL_INDEX(x, width); + ERR_FAIL_INDEX(y, height); int ofs = width * y + x; - int bbyte = ofs/8; + int bbyte = ofs / 8; int bbit = ofs % 8; uint8_t b = bitmask[bbyte]; if (p_value) - b|=(1<<bbit); + b |= (1 << bbit); else - b&=!(1<<bbit); + b &= !(1 << bbit); - bitmask[bbyte]=b; + bitmask[bbyte] = b; } -bool BitMap::get_bit(const Point2& p_pos) const{ +bool BitMap::get_bit(const Point2 &p_pos) const { - int x=Math::fast_ftoi(p_pos.x); - int y=Math::fast_ftoi(p_pos.y); - ERR_FAIL_INDEX_V(x,width,false); - ERR_FAIL_INDEX_V(y,height,false); + int x = Math::fast_ftoi(p_pos.x); + int y = Math::fast_ftoi(p_pos.y); + ERR_FAIL_INDEX_V(x, width, false); + ERR_FAIL_INDEX_V(y, height, false); int ofs = width * y + x; - int bbyte = ofs/8; + int bbyte = ofs / 8; int bbit = ofs % 8; - return (bitmask[bbyte]&(1<<bbit))!=0; - + return (bitmask[bbyte] & (1 << bbit)) != 0; } Size2 BitMap::get_size() const { - return Size2(width,height); + return Size2(width, height); } -void BitMap::_set_data(const Dictionary& p_d) { +void BitMap::_set_data(const Dictionary &p_d) { ERR_FAIL_COND(!p_d.has("size")); ERR_FAIL_COND(!p_d.has("data")); create(p_d["size"]); - bitmask=p_d["data"]; + bitmask = p_d["data"]; } -Dictionary BitMap::_get_data() const{ +Dictionary BitMap::_get_data() const { Dictionary d; - d["size"]=get_size(); - d["data"]=bitmask; + d["size"] = get_size(); + d["data"] = bitmask; return d; } void BitMap::_bind_methods() { - ClassDB::bind_method(D_METHOD("create","size"),&BitMap::create); - ClassDB::bind_method(D_METHOD("create_from_image_alpha","image"),&BitMap::create_from_image_alpha); + ClassDB::bind_method(D_METHOD("create", "size"), &BitMap::create); + ClassDB::bind_method(D_METHOD("create_from_image_alpha", "image"), &BitMap::create_from_image_alpha); - ClassDB::bind_method(D_METHOD("set_bit","pos","bit"),&BitMap::set_bit); - ClassDB::bind_method(D_METHOD("get_bit","pos"),&BitMap::get_bit); + ClassDB::bind_method(D_METHOD("set_bit", "pos", "bit"), &BitMap::set_bit); + ClassDB::bind_method(D_METHOD("get_bit", "pos"), &BitMap::get_bit); - ClassDB::bind_method(D_METHOD("set_bit_rect","p_rect","bit"),&BitMap::set_bit_rect); - ClassDB::bind_method(D_METHOD("get_true_bit_count"),&BitMap::get_true_bit_count); + ClassDB::bind_method(D_METHOD("set_bit_rect", "p_rect", "bit"), &BitMap::set_bit_rect); + ClassDB::bind_method(D_METHOD("get_true_bit_count"), &BitMap::get_true_bit_count); - ClassDB::bind_method(D_METHOD("get_size"),&BitMap::get_size); + ClassDB::bind_method(D_METHOD("get_size"), &BitMap::get_size); - ClassDB::bind_method(D_METHOD("_set_data"),&BitMap::_set_data); - ClassDB::bind_method(D_METHOD("_get_data"),&BitMap::_get_data); - - ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_data","_get_data"); + ClassDB::bind_method(D_METHOD("_set_data"), &BitMap::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &BitMap::_get_data); + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); } BitMap::BitMap() { - width=0; - height=0; + width = 0; + height = 0; } ////////////////////////////////////// - diff --git a/scene/resources/bit_mask.h b/scene/resources/bit_mask.h index f749a53e34..3cee2279b8 100644 --- a/scene/resources/bit_mask.h +++ b/scene/resources/bit_mask.h @@ -29,13 +29,12 @@ #ifndef BIT_MASK_H #define BIT_MASK_H -#include "resource.h" #include "io/resource_loader.h" - +#include "resource.h" class BitMap : public Resource { - GDCLASS(BitMap,Resource); + GDCLASS(BitMap, Resource); OBJ_SAVE_TYPE(BitMap); RES_BASE_EXTENSION("pbm"); @@ -44,19 +43,18 @@ class BitMap : public Resource { int height; protected: - void _set_data(const Dictionary& p_d); + void _set_data(const Dictionary &p_d); Dictionary _get_data() const; static void _bind_methods(); -public: +public: + void create(const Size2 &p_size); + void create_from_image_alpha(const Image &p_image); - void create(const Size2& p_size); - void create_from_image_alpha(const Image& p_image); - - void set_bit(const Point2& p_pos,bool p_value); - bool get_bit(const Point2& p_pos) const; - void set_bit_rect(const Rect2& p_rect,bool p_value); + void set_bit(const Point2 &p_pos, bool p_value); + bool get_bit(const Point2 &p_pos) const; + void set_bit_rect(const Rect2 &p_rect, bool p_value); int get_true_bit_count() const; Size2 get_size() const; @@ -64,5 +62,4 @@ public: BitMap(); }; - #endif // BIT_MASK_H diff --git a/scene/resources/bounds.cpp b/scene/resources/bounds.cpp index 26bf6270e9..974ff76cd0 100644 --- a/scene/resources/bounds.cpp +++ b/scene/resources/bounds.cpp @@ -28,19 +28,17 @@ /*************************************************************************/ #include "bounds.h" - void Bounds::_bind_methods() { - ClassDB::bind_method( D_METHOD("set_bsp_tree","bsp_tree"),&Bounds::set_bsp_tree); - ClassDB::bind_method( D_METHOD("get_bsp_tree"),&Bounds::get_bsp_tree ); - - ADD_PROPERTY( PropertyInfo( Variant::ARRAY, "bsp_tree" ), "set_bsp_tree", "get_bsp_tree"); + ClassDB::bind_method(D_METHOD("set_bsp_tree", "bsp_tree"), &Bounds::set_bsp_tree); + ClassDB::bind_method(D_METHOD("get_bsp_tree"), &Bounds::get_bsp_tree); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "bsp_tree"), "set_bsp_tree", "get_bsp_tree"); } -void Bounds::set_bsp_tree(const BSP_Tree& p_bsp_tree) { +void Bounds::set_bsp_tree(const BSP_Tree &p_bsp_tree) { - bsp_tree=p_bsp_tree; + bsp_tree = p_bsp_tree; } BSP_Tree Bounds::get_bsp_tree() const { @@ -48,7 +46,5 @@ BSP_Tree Bounds::get_bsp_tree() const { return bsp_tree; } - -Bounds::Bounds() -{ +Bounds::Bounds() { } diff --git a/scene/resources/bounds.h b/scene/resources/bounds.h index bd5d996a36..62e1b8e0ef 100644 --- a/scene/resources/bounds.h +++ b/scene/resources/bounds.h @@ -29,21 +29,19 @@ #ifndef BOUNDS_H #define BOUNDS_H -#include "resource.h" #include "bsp_tree.h" +#include "resource.h" class Bounds : public Resource { - GDCLASS(Bounds,Resource); + GDCLASS(Bounds, Resource); BSP_Tree bsp_tree; protected: - static void _bind_methods(); public: - - void set_bsp_tree(const BSP_Tree& p_bsp_tree); + void set_bsp_tree(const BSP_Tree &p_bsp_tree); BSP_Tree get_bsp_tree() const; Bounds(); diff --git a/scene/resources/box_shape.cpp b/scene/resources/box_shape.cpp index e8eccaceae..1e9991d7dc 100644 --- a/scene/resources/box_shape.cpp +++ b/scene/resources/box_shape.cpp @@ -29,34 +29,31 @@ #include "box_shape.h" #include "servers/physics_server.h" - Vector<Vector3> BoxShape::_gen_debug_mesh_lines() { - Vector<Vector3> lines; Rect3 aabb; - aabb.pos=-get_extents(); - aabb.size=aabb.pos*-2; + aabb.pos = -get_extents(); + aabb.size = aabb.pos * -2; - for(int i=0;i<12;i++) { - Vector3 a,b; - aabb.get_edge(i,a,b); + for (int i = 0; i < 12; i++) { + Vector3 a, b; + aabb.get_edge(i, a, b); lines.push_back(a); lines.push_back(b); } - return lines; } void BoxShape::_update_shape() { - PhysicsServer::get_singleton()->shape_set_data(get_shape(),extents); + PhysicsServer::get_singleton()->shape_set_data(get_shape(), extents); } -void BoxShape::set_extents(const Vector3& p_extents) { +void BoxShape::set_extents(const Vector3 &p_extents) { - extents=p_extents; + extents = p_extents; _update_shape(); notify_change_to_owners(); _change_notify("extents"); @@ -67,17 +64,16 @@ Vector3 BoxShape::get_extents() const { return extents; } - void BoxShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_extents","extents"),&BoxShape::set_extents); - ClassDB::bind_method(D_METHOD("get_extents"),&BoxShape::get_extents); - - ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"extents"), "set_extents", "get_extents") ; + ClassDB::bind_method(D_METHOD("set_extents", "extents"), &BoxShape::set_extents); + ClassDB::bind_method(D_METHOD("get_extents"), &BoxShape::get_extents); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents"), "set_extents", "get_extents"); } -BoxShape::BoxShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_BOX)) { +BoxShape::BoxShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_BOX)) { - set_extents(Vector3(1,1,1)); + set_extents(Vector3(1, 1, 1)); } diff --git a/scene/resources/box_shape.h b/scene/resources/box_shape.h index c17dd22015..2bab6d9b8a 100644 --- a/scene/resources/box_shape.h +++ b/scene/resources/box_shape.h @@ -33,19 +33,17 @@ class BoxShape : public Shape { - GDCLASS(BoxShape,Shape); + GDCLASS(BoxShape, Shape); Vector3 extents; protected: - static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); public: - - void set_extents(const Vector3& p_extents); + void set_extents(const Vector3 &p_extents); Vector3 get_extents() const; BoxShape(); diff --git a/scene/resources/canvas.cpp b/scene/resources/canvas.cpp index bda97141cc..dd0375b765 100644 --- a/scene/resources/canvas.cpp +++ b/scene/resources/canvas.cpp @@ -36,11 +36,9 @@ RID Canvas::get_rid() const { Canvas::Canvas() { - canvas=VisualServer::get_singleton()->canvas_create(); + canvas = VisualServer::get_singleton()->canvas_create(); } - Canvas::~Canvas() { VisualServer::get_singleton()->free(canvas); } - diff --git a/scene/resources/canvas.h b/scene/resources/canvas.h index 960136ac14..1d3775c30c 100644 --- a/scene/resources/canvas.h +++ b/scene/resources/canvas.h @@ -29,17 +29,15 @@ #ifndef CANVAS_H #define CANVAS_H - #include "resource.h" class Canvas : public Resource { - GDCLASS(Canvas,Resource); + GDCLASS(Canvas, Resource); RID canvas; public: - virtual RID get_rid() const; Canvas(); ~Canvas(); diff --git a/scene/resources/capsule_shape.cpp b/scene/resources/capsule_shape.cpp index bd30f009c4..1aa3fee0ca 100644 --- a/scene/resources/capsule_shape.cpp +++ b/scene/resources/capsule_shape.cpp @@ -29,43 +29,39 @@ #include "capsule_shape.h" #include "servers/physics_server.h" - Vector<Vector3> CapsuleShape::_gen_debug_mesh_lines() { - float radius = get_radius(); float height = get_height(); - Vector<Vector3> points; - Vector3 d(0,0,height*0.5); - for(int i=0;i<360;i++) { + Vector3 d(0, 0, height * 0.5); + for (int i = 0; i < 360; i++) { - float ra=Math::deg2rad((float)i); - float rb=Math::deg2rad((float)i+1); - Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*radius; - Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*radius; + float ra = Math::deg2rad((float)i); + float rb = Math::deg2rad((float)i + 1); + Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius; + Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius; - points.push_back(Vector3(a.x,a.y,0)+d); - points.push_back(Vector3(b.x,b.y,0)+d); + points.push_back(Vector3(a.x, a.y, 0) + d); + points.push_back(Vector3(b.x, b.y, 0) + d); - points.push_back(Vector3(a.x,a.y,0)-d); - points.push_back(Vector3(b.x,b.y,0)-d); + points.push_back(Vector3(a.x, a.y, 0) - d); + points.push_back(Vector3(b.x, b.y, 0) - d); - if (i%90==0) { + if (i % 90 == 0) { - points.push_back(Vector3(a.x,a.y,0)+d); - points.push_back(Vector3(a.x,a.y,0)-d); + points.push_back(Vector3(a.x, a.y, 0) + d); + points.push_back(Vector3(a.x, a.y, 0) - d); } - Vector3 dud = i<180?d:-d; - - points.push_back(Vector3(0,a.y,a.x)+dud); - points.push_back(Vector3(0,b.y,b.x)+dud); - points.push_back(Vector3(a.y,0,a.x)+dud); - points.push_back(Vector3(b.y,0,b.x)+dud); + Vector3 dud = i < 180 ? d : -d; + points.push_back(Vector3(0, a.y, a.x) + dud); + points.push_back(Vector3(0, b.y, b.x) + dud); + points.push_back(Vector3(a.y, 0, a.x) + dud); + points.push_back(Vector3(b.y, 0, b.x) + dud); } return points; @@ -74,14 +70,14 @@ Vector<Vector3> CapsuleShape::_gen_debug_mesh_lines() { void CapsuleShape::_update_shape() { Dictionary d; - d["radius"]=radius; - d["height"]=height; - PhysicsServer::get_singleton()->shape_set_data(get_shape(),d); + d["radius"] = radius; + d["height"] = height; + PhysicsServer::get_singleton()->shape_set_data(get_shape(), d); } void CapsuleShape::set_radius(float p_radius) { - radius=p_radius; + radius = p_radius; _update_shape(); notify_change_to_owners(); _change_notify("radius"); @@ -94,7 +90,7 @@ float CapsuleShape::get_radius() const { void CapsuleShape::set_height(float p_height) { - height=p_height; + height = p_height; _update_shape(); notify_change_to_owners(); _change_notify("height"); @@ -107,19 +103,19 @@ float CapsuleShape::get_height() const { void CapsuleShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_radius","radius"),&CapsuleShape::set_radius); - ClassDB::bind_method(D_METHOD("get_radius"),&CapsuleShape::get_radius); - ClassDB::bind_method(D_METHOD("set_height","height"),&CapsuleShape::set_height); - ClassDB::bind_method(D_METHOD("get_height"),&CapsuleShape::get_height); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0.01,4096,0.01"), "set_radius","get_radius") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"height",PROPERTY_HINT_RANGE,"0.01,4096,0.01"), "set_height","get_height") ; + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CapsuleShape::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &CapsuleShape::get_radius); + ClassDB::bind_method(D_METHOD("set_height", "height"), &CapsuleShape::set_height); + ClassDB::bind_method(D_METHOD("get_height"), &CapsuleShape::get_height); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_radius", "get_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_height", "get_height"); } -CapsuleShape::CapsuleShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CAPSULE)) { +CapsuleShape::CapsuleShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CAPSULE)) { - radius=1.0; - height=1.0; + radius = 1.0; + height = 1.0; _update_shape(); } diff --git a/scene/resources/capsule_shape.h b/scene/resources/capsule_shape.h index e788d9cfc5..ecffdd8ce7 100644 --- a/scene/resources/capsule_shape.h +++ b/scene/resources/capsule_shape.h @@ -33,25 +33,23 @@ class CapsuleShape : public Shape { - GDCLASS(CapsuleShape,Shape); + GDCLASS(CapsuleShape, Shape); float radius; float height; protected: - static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); -public: +public: void set_radius(float p_radius); float get_radius() const; void set_height(float p_height); float get_height() const; - CapsuleShape(); }; diff --git a/scene/resources/capsule_shape_2d.cpp b/scene/resources/capsule_shape_2d.cpp index 523d6d7455..d24640e43d 100644 --- a/scene/resources/capsule_shape_2d.cpp +++ b/scene/resources/capsule_shape_2d.cpp @@ -33,14 +33,13 @@ void CapsuleShape2D::_update_shape() { - Physics2DServer::get_singleton()->shape_set_data(get_rid(),Vector2(radius,height)); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), Vector2(radius, height)); emit_changed(); } - void CapsuleShape2D::set_radius(real_t p_radius) { - radius=p_radius; + radius = p_radius; _update_shape(); } @@ -51,7 +50,7 @@ real_t CapsuleShape2D::get_radius() const { void CapsuleShape2D::set_height(real_t p_height) { - height=p_height; + height = p_height; _update_shape(); } @@ -60,50 +59,47 @@ real_t CapsuleShape2D::get_height() const { return height; } - -void CapsuleShape2D::draw(const RID& p_to_rid,const Color& p_color) { +void CapsuleShape2D::draw(const RID &p_to_rid, const Color &p_color) { Vector<Vector2> points; - for(int i=0;i<24;i++) { - Vector2 ofs = Vector2(0,(i>6 && i<=18) ? -get_height()*0.5 : get_height()*0.5); + for (int i = 0; i < 24; i++) { + Vector2 ofs = Vector2(0, (i > 6 && i <= 18) ? -get_height() * 0.5 : get_height() * 0.5); - points.push_back(Vector2(Math::sin(i*Math_PI*2/24.0),Math::cos(i*Math_PI*2/24.0))*get_radius() + ofs); - if (i==6 || i==18) - points.push_back(Vector2(Math::sin(i*Math_PI*2/24.0),Math::cos(i*Math_PI*2/24.0))*get_radius() - ofs); + points.push_back(Vector2(Math::sin(i * Math_PI * 2 / 24.0), Math::cos(i * Math_PI * 2 / 24.0)) * get_radius() + ofs); + if (i == 6 || i == 18) + points.push_back(Vector2(Math::sin(i * Math_PI * 2 / 24.0), Math::cos(i * Math_PI * 2 / 24.0)) * get_radius() - ofs); } Vector<Color> col; col.push_back(p_color); - VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid,points,col); - + VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col); } Rect2 CapsuleShape2D::get_rect() const { - Vector2 he=Point2(get_radius(),get_radius()+get_height()*0.5); + Vector2 he = Point2(get_radius(), get_radius() + get_height() * 0.5); Rect2 rect; - rect.pos=-he; - rect.size=he*2.0; + rect.pos = -he; + rect.size = he * 2.0; return rect; } void CapsuleShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_radius","radius"),&CapsuleShape2D::set_radius); - ClassDB::bind_method(D_METHOD("get_radius"),&CapsuleShape2D::get_radius); - - ClassDB::bind_method(D_METHOD("set_height","height"),&CapsuleShape2D::set_height); - ClassDB::bind_method(D_METHOD("get_height"),&CapsuleShape2D::get_height); - + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CapsuleShape2D::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &CapsuleShape2D::get_radius); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius"),"set_radius","get_radius") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"height"),"set_height","get_height") ; + ClassDB::bind_method(D_METHOD("set_height", "height"), &CapsuleShape2D::set_height); + ClassDB::bind_method(D_METHOD("get_height"), &CapsuleShape2D::get_height); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius"), "set_radius", "get_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "height"), "set_height", "get_height"); } -CapsuleShape2D::CapsuleShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CAPSULE)) { +CapsuleShape2D::CapsuleShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CAPSULE)) { - radius=10; - height=20; + radius = 10; + height = 20; _update_shape(); } diff --git a/scene/resources/capsule_shape_2d.h b/scene/resources/capsule_shape_2d.h index ef06072e14..05d819c1d5 100644 --- a/scene/resources/capsule_shape_2d.h +++ b/scene/resources/capsule_shape_2d.h @@ -32,25 +32,25 @@ #include "scene/resources/shape_2d.h" class CapsuleShape2D : public Shape2D { - GDCLASS( CapsuleShape2D, Shape2D ); + GDCLASS(CapsuleShape2D, Shape2D); real_t height; real_t radius; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: +public: void set_height(real_t p_height); real_t get_height() const; void set_radius(real_t p_radius); real_t get_radius() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); - virtual Rect2 get_rect() const ; + virtual void draw(const RID &p_to_rid, const Color &p_color); + virtual Rect2 get_rect() const; CapsuleShape2D(); }; diff --git a/scene/resources/circle_shape_2d.cpp b/scene/resources/circle_shape_2d.cpp index cd707b1032..2271a3ad93 100644 --- a/scene/resources/circle_shape_2d.cpp +++ b/scene/resources/circle_shape_2d.cpp @@ -32,14 +32,13 @@ #include "servers/visual_server.h" void CircleShape2D::_update_shape() { - Physics2DServer::get_singleton()->shape_set_data(get_rid(),radius); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), radius); emit_changed(); } - void CircleShape2D::set_radius(real_t p_radius) { - radius=p_radius; + radius = p_radius; _update_shape(); } @@ -48,39 +47,37 @@ real_t CircleShape2D::get_radius() const { return radius; } - void CircleShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_radius","radius"),&CircleShape2D::set_radius); - ClassDB::bind_method(D_METHOD("get_radius"),&CircleShape2D::get_radius); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0.01,16384,0.5"),"set_radius","get_radius") ; + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CircleShape2D::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &CircleShape2D::get_radius); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,16384,0.5"), "set_radius", "get_radius"); } Rect2 CircleShape2D::get_rect() const { Rect2 rect; - rect.pos=-Point2(get_radius(),get_radius()); - rect.size=Point2(get_radius(),get_radius())*2.0; + rect.pos = -Point2(get_radius(), get_radius()); + rect.size = Point2(get_radius(), get_radius()) * 2.0; return rect; } -void CircleShape2D::draw(const RID& p_to_rid,const Color& p_color) { +void CircleShape2D::draw(const RID &p_to_rid, const Color &p_color) { Vector<Vector2> points; - for(int i=0;i<24;i++) { + for (int i = 0; i < 24; i++) { - points.push_back(Vector2(Math::cos(i*Math_PI*2/24.0),Math::sin(i*Math_PI*2/24.0))*get_radius()); + points.push_back(Vector2(Math::cos(i * Math_PI * 2 / 24.0), Math::sin(i * Math_PI * 2 / 24.0)) * get_radius()); } Vector<Color> col; col.push_back(p_color); - VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid,points,col); - + VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col); } -CircleShape2D::CircleShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CIRCLE)) { +CircleShape2D::CircleShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CIRCLE)) { - radius=10; + radius = 10; _update_shape(); } diff --git a/scene/resources/circle_shape_2d.h b/scene/resources/circle_shape_2d.h index ec11b55169..11fdc51f09 100644 --- a/scene/resources/circle_shape_2d.h +++ b/scene/resources/circle_shape_2d.h @@ -32,22 +32,21 @@ #include "scene/resources/shape_2d.h" class CircleShape2D : public Shape2D { - GDCLASS( CircleShape2D, Shape2D ); + GDCLASS(CircleShape2D, Shape2D); real_t radius; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: +public: void set_radius(real_t p_radius); real_t get_radius() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); + virtual void draw(const RID &p_to_rid, const Color &p_color); virtual Rect2 get_rect() const; - CircleShape2D(); }; diff --git a/scene/resources/color_ramp.cpp b/scene/resources/color_ramp.cpp index b14ba4c8ed..2c20ad527b 100644 --- a/scene/resources/color_ramp.cpp +++ b/scene/resources/color_ramp.cpp @@ -38,51 +38,45 @@ ColorRamp::ColorRamp() { //Set initial color ramp transition from black to white points.resize(2); - points[0].color = Color(0,0,0,1); + points[0].color = Color(0, 0, 0, 1); points[0].offset = 0; - points[1].color = Color(1,1,1,1); + points[1].color = Color(1, 1, 1, 1); points[1].offset = 1; is_sorted = true; } ColorRamp::~ColorRamp() { - } void ColorRamp::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_point", "offset", "color"), &ColorRamp::add_point); + ClassDB::bind_method(D_METHOD("remove_point", "offset", "color"), &ColorRamp::remove_point); + ClassDB::bind_method(D_METHOD("set_offset", "point", "offset"), &ColorRamp::set_offset); + ClassDB::bind_method(D_METHOD("get_offset", "point"), &ColorRamp::get_offset); + ClassDB::bind_method(D_METHOD("set_color", "point", "color"), &ColorRamp::set_color); + ClassDB::bind_method(D_METHOD("get_color", "point"), &ColorRamp::get_color); + ClassDB::bind_method(D_METHOD("interpolate", "offset"), &ColorRamp::get_color_at_offset); - ClassDB::bind_method(D_METHOD("add_point","offset","color"),&ColorRamp::add_point); - ClassDB::bind_method(D_METHOD("remove_point","offset","color"),&ColorRamp::remove_point); - - ClassDB::bind_method(D_METHOD("set_offset","point","offset"),&ColorRamp::set_offset); - ClassDB::bind_method(D_METHOD("get_offset","point"),&ColorRamp::get_offset); - - ClassDB::bind_method(D_METHOD("set_color","point","color"),&ColorRamp::set_color); - ClassDB::bind_method(D_METHOD("get_color","point"),&ColorRamp::get_color); + ClassDB::bind_method(D_METHOD("get_point_count"), &ColorRamp::get_points_count); - ClassDB::bind_method(D_METHOD("interpolate","offset"),&ColorRamp::get_color_at_offset); + ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_OFFSETS, "offsets"), &ColorRamp::set_offsets); + ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_OFFSETS), &ColorRamp::get_offsets); - ClassDB::bind_method(D_METHOD("get_point_count"),&ColorRamp::get_points_count); + ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_COLORS, "colors"), &ColorRamp::set_colors); + ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_COLORS), &ColorRamp::get_colors); - ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_OFFSETS,"offsets"),&ColorRamp::set_offsets); - ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_OFFSETS),&ColorRamp::get_offsets); - - ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_COLORS,"colors"),&ColorRamp::set_colors); - ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_COLORS),&ColorRamp::get_colors); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"offsets"),COLOR_RAMP_SET_OFFSETS,COLOR_RAMP_GET_OFFSETS) ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"colors"),COLOR_RAMP_SET_COLORS,COLOR_RAMP_GET_COLORS) ; + ADD_PROPERTY(PropertyInfo(Variant::REAL, "offsets"), COLOR_RAMP_SET_OFFSETS, COLOR_RAMP_GET_OFFSETS); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "colors"), COLOR_RAMP_SET_COLORS, COLOR_RAMP_GET_COLORS); } Vector<float> ColorRamp::get_offsets() const { Vector<float> offsets; offsets.resize(points.size()); - for(int i = 0; i < points.size(); i++) - { + for (int i = 0; i < points.size(); i++) { offsets[i] = points[i].offset; } return offsets; @@ -91,44 +85,41 @@ Vector<float> ColorRamp::get_offsets() const { Vector<Color> ColorRamp::get_colors() const { Vector<Color> colors; colors.resize(points.size()); - for(int i = 0; i < points.size(); i++) - { + for (int i = 0; i < points.size(); i++) { colors[i] = points[i].color; } return colors; } -void ColorRamp::set_offsets(const Vector<float>& p_offsets) { +void ColorRamp::set_offsets(const Vector<float> &p_offsets) { points.resize(p_offsets.size()); - for(int i = 0; i < points.size(); i++) - { + for (int i = 0; i < points.size(); i++) { points[i].offset = p_offsets[i]; } is_sorted = false; emit_signal(CoreStringNames::get_singleton()->changed); } -void ColorRamp::set_colors(const Vector<Color>& p_colors) { - if(points.size()<p_colors.size()) +void ColorRamp::set_colors(const Vector<Color> &p_colors) { + if (points.size() < p_colors.size()) is_sorted = false; points.resize(p_colors.size()); - for(int i = 0; i < points.size(); i++) - { + for (int i = 0; i < points.size(); i++) { points[i].color = p_colors[i]; } emit_signal(CoreStringNames::get_singleton()->changed); } -Vector<ColorRamp::Point>& ColorRamp::get_points() { +Vector<ColorRamp::Point> &ColorRamp::get_points() { return points; } -void ColorRamp::add_point(float p_offset, const Color& p_color) { +void ColorRamp::add_point(float p_offset, const Color &p_color) { Point p; - p.offset=p_offset; - p.color=p_color; - is_sorted=false; + p.offset = p_offset; + p.color = p_color; + is_sorted = false; points.push_back(p); emit_signal(CoreStringNames::get_singleton()->changed); @@ -136,20 +127,20 @@ void ColorRamp::add_point(float p_offset, const Color& p_color) { void ColorRamp::remove_point(int p_index) { - ERR_FAIL_INDEX(p_index,points.size()); - ERR_FAIL_COND(points.size()<=2); + ERR_FAIL_INDEX(p_index, points.size()); + ERR_FAIL_COND(points.size() <= 2); points.remove(p_index); emit_signal(CoreStringNames::get_singleton()->changed); } -void ColorRamp::set_points(Vector<ColorRamp::Point>& p_points) { +void ColorRamp::set_points(Vector<ColorRamp::Point> &p_points) { points = p_points; is_sorted = false; emit_signal(CoreStringNames::get_singleton()->changed); } void ColorRamp::set_offset(int pos, const float offset) { - if(points.size() <= pos) + if (points.size() <= pos) points.resize(pos + 1); points[pos].offset = offset; is_sorted = false; @@ -157,14 +148,13 @@ void ColorRamp::set_offset(int pos, const float offset) { } float ColorRamp::get_offset(int pos) const { - if(points.size() > pos) + if (points.size() > pos) return points[pos].offset; - return 0; //TODO: Maybe throw some error instead? + return 0; //TODO: Maybe throw some error instead? } -void ColorRamp::set_color(int pos, const Color& color) { - if(points.size() <= pos) - { +void ColorRamp::set_color(int pos, const Color &color) { + if (points.size() <= pos) { points.resize(pos + 1); is_sorted = false; } @@ -173,9 +163,9 @@ void ColorRamp::set_color(int pos, const Color& color) { } Color ColorRamp::get_color(int pos) const { - if(points.size() > pos) + if (points.size() > pos) return points[pos].color; - return Color(0,0,0,1); //TODO: Maybe throw some error instead? + return Color(0, 0, 0, 1); //TODO: Maybe throw some error instead? } int ColorRamp::get_points_count() const { diff --git a/scene/resources/color_ramp.h b/scene/resources/color_ramp.h index b6ca56dbf5..78c88c3270 100644 --- a/scene/resources/color_ramp.h +++ b/scene/resources/color_ramp.h @@ -31,17 +31,17 @@ #include "resource.h" -class ColorRamp: public Resource { - GDCLASS( ColorRamp, Resource ); - OBJ_SAVE_TYPE( ColorRamp ); +class ColorRamp : public Resource { + GDCLASS(ColorRamp, Resource); + OBJ_SAVE_TYPE(ColorRamp); public: struct Point { float offset; Color color; - bool operator<(const Point& p_ponit) const { - return offset<p_ponit.offset; + bool operator<(const Point &p_ponit) const { + return offset < p_ponit.offset; } }; @@ -56,47 +56,45 @@ public: ColorRamp(); virtual ~ColorRamp(); - void add_point(float p_offset, const Color& p_color); + void add_point(float p_offset, const Color &p_color); void remove_point(int p_index); - void set_points(Vector<Point>& points); - Vector<Point>& get_points(); + void set_points(Vector<Point> &points); + Vector<Point> &get_points(); void set_offset(int pos, const float offset); float get_offset(int pos) const; - void set_color(int pos, const Color& color); + void set_color(int pos, const Color &color); Color get_color(int pos) const; - void set_offsets(const Vector<float>& offsets); + void set_offsets(const Vector<float> &offsets); Vector<float> get_offsets() const; - void set_colors(const Vector<Color>& colors); + void set_colors(const Vector<Color> &colors); Vector<Color> get_colors() const; _FORCE_INLINE_ Color get_color_at_offset(float p_offset) { if (points.empty()) - return Color(0,0,0,1); + return Color(0, 0, 0, 1); - if(!is_sorted) - { + if (!is_sorted) { points.sort(); is_sorted = true; } //binary search int low = 0; - int high = points.size() -1; + int high = points.size() - 1; int middle; - while( low <= high ) - { - middle = ( low + high ) / 2; - Point& point = points[middle]; - if( point.offset > p_offset ) { + while (low <= high) { + middle = (low + high) / 2; + Point &point = points[middle]; + if (point.offset > p_offset) { high = middle - 1; //search low end of array - } else if ( point.offset < p_offset) { + } else if (point.offset < p_offset) { low = middle + 1; //search high end of array } else { return point.color; @@ -104,19 +102,18 @@ public: } //return interpolated value - if (points[middle].offset>p_offset) - { + if (points[middle].offset > p_offset) { middle--; } - int first=middle; - int second=middle+1; - if(second>=points.size()) - return points[points.size()-1].color; - if(first<0) + int first = middle; + int second = middle + 1; + if (second >= points.size()) + return points[points.size() - 1].color; + if (first < 0) return points[0].color; - Point& pointFirst = points[first]; - Point& pointSecond = points[second]; - return pointFirst.color.linear_interpolate(pointSecond.color, (p_offset-pointFirst.offset)/(pointSecond.offset - pointFirst.offset)); + Point &pointFirst = points[first]; + Point &pointSecond = points[second]; + return pointFirst.color.linear_interpolate(pointSecond.color, (p_offset - pointFirst.offset) / (pointSecond.offset - pointFirst.offset)); } int get_points_count() const; diff --git a/scene/resources/concave_polygon_shape.cpp b/scene/resources/concave_polygon_shape.cpp index 3945ade215..0031580153 100644 --- a/scene/resources/concave_polygon_shape.cpp +++ b/scene/resources/concave_polygon_shape.cpp @@ -34,87 +34,79 @@ Vector<Vector3> ConcavePolygonShape::_gen_debug_mesh_lines() { Set<DrawEdge> edges; - PoolVector<Vector3> data=get_faces(); - int datalen=data.size(); - ERR_FAIL_COND_V( (datalen%3)!=0,Vector<Vector3>() ); + PoolVector<Vector3> data = get_faces(); + int datalen = data.size(); + ERR_FAIL_COND_V((datalen % 3) != 0, Vector<Vector3>()); - PoolVector<Vector3>::Read r=data.read(); + PoolVector<Vector3>::Read r = data.read(); - for(int i=0;i<datalen;i+=3) { + for (int i = 0; i < datalen; i += 3) { - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - DrawEdge de(r[i+j],r[i+((j+1)%3)]); + DrawEdge de(r[i + j], r[i + ((j + 1) % 3)]); edges.insert(de); } - } Vector<Vector3> points; - points.resize(edges.size()*2); - int idx=0; - for (Set<DrawEdge>::Element*E=edges.front();E;E=E->next()) { + points.resize(edges.size() * 2); + int idx = 0; + for (Set<DrawEdge>::Element *E = edges.front(); E; E = E->next()) { - points[idx+0]=E->get().a; - points[idx+1]=E->get().b; - idx+=2; + points[idx + 0] = E->get().a; + points[idx + 1] = E->get().b; + idx += 2; } return points; - } -bool ConcavePolygonShape::_set(const StringName& p_name, const Variant& p_value) { +bool ConcavePolygonShape::_set(const StringName &p_name, const Variant &p_value) { - if (p_name=="data") - PhysicsServer::get_singleton()->shape_set_data(get_shape(),p_value); + if (p_name == "data") + PhysicsServer::get_singleton()->shape_set_data(get_shape(), p_value); else return false; return true; - } -bool ConcavePolygonShape::_get(const StringName& p_name,Variant &r_ret) const { +bool ConcavePolygonShape::_get(const StringName &p_name, Variant &r_ret) const { - if (p_name=="data") - r_ret=PhysicsServer::get_singleton()->shape_get_data(get_shape()); + if (p_name == "data") + r_ret = PhysicsServer::get_singleton()->shape_get_data(get_shape()); else return false; return true; - } -void ConcavePolygonShape::_get_property_list( List<PropertyInfo> *p_list) const { +void ConcavePolygonShape::_get_property_list(List<PropertyInfo> *p_list) const { - p_list->push_back( PropertyInfo(Variant::ARRAY,"data") ); + p_list->push_back(PropertyInfo(Variant::ARRAY, "data")); } - void ConcavePolygonShape::_update_shape() { - } -void ConcavePolygonShape::set_faces(const PoolVector<Vector3>& p_faces) { +void ConcavePolygonShape::set_faces(const PoolVector<Vector3> &p_faces) { - PhysicsServer::get_singleton()->shape_set_data(get_shape(),p_faces); + PhysicsServer::get_singleton()->shape_set_data(get_shape(), p_faces); notify_change_to_owners(); } PoolVector<Vector3> ConcavePolygonShape::get_faces() const { return PhysicsServer::get_singleton()->shape_get_data(get_shape()); - } - - void ConcavePolygonShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_faces","faces"),&ConcavePolygonShape::set_faces); - ClassDB::bind_method(D_METHOD("get_faces"),&ConcavePolygonShape::get_faces); + ClassDB::bind_method(D_METHOD("set_faces", "faces"), &ConcavePolygonShape::set_faces); + ClassDB::bind_method(D_METHOD("get_faces"), &ConcavePolygonShape::get_faces); } -ConcavePolygonShape::ConcavePolygonShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONCAVE_POLYGON)) { +ConcavePolygonShape::ConcavePolygonShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONCAVE_POLYGON)) { //set_planes(Vector3(1,1,1)); } diff --git a/scene/resources/concave_polygon_shape.h b/scene/resources/concave_polygon_shape.h index 36e806d37a..f048a4d151 100644 --- a/scene/resources/concave_polygon_shape.h +++ b/scene/resources/concave_polygon_shape.h @@ -33,44 +33,41 @@ class ConcavePolygonShape : public Shape { - GDCLASS(ConcavePolygonShape,Shape); + GDCLASS(ConcavePolygonShape, Shape); struct DrawEdge { Vector3 a; Vector3 b; - bool operator<(const DrawEdge& p_edge) const { - if (a==p_edge.a) - return b<p_edge.b; + bool operator<(const DrawEdge &p_edge) const { + if (a == p_edge.a) + return b < p_edge.b; else - return a<p_edge.a; + return a < p_edge.a; } - DrawEdge(const Vector3& p_a=Vector3(),const Vector3& p_b=Vector3()) { - a=p_a; - b=p_b; - if (a<b) { - SWAP(a,b); + DrawEdge(const Vector3 &p_a = Vector3(), const Vector3 &p_b = Vector3()) { + a = p_a; + b = p_b; + if (a < b) { + SWAP(a, b); } } }; protected: - - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); -public: - void set_faces(const PoolVector<Vector3>& p_faces); +public: + void set_faces(const PoolVector<Vector3> &p_faces); PoolVector<Vector3> get_faces() const; - ConcavePolygonShape(); }; diff --git a/scene/resources/concave_polygon_shape_2d.cpp b/scene/resources/concave_polygon_shape_2d.cpp index f3dfa8a2b3..04a69d9c8e 100644 --- a/scene/resources/concave_polygon_shape_2d.cpp +++ b/scene/resources/concave_polygon_shape_2d.cpp @@ -31,9 +31,9 @@ #include "servers/physics_2d_server.h" #include "servers/visual_server.h" -void ConcavePolygonShape2D::set_segments(const PoolVector<Vector2>& p_segments) { +void ConcavePolygonShape2D::set_segments(const PoolVector<Vector2> &p_segments) { - Physics2DServer::get_singleton()->shape_set_data(get_rid(),p_segments); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), p_segments); emit_changed(); } @@ -42,55 +42,47 @@ PoolVector<Vector2> ConcavePolygonShape2D::get_segments() const { return Physics2DServer::get_singleton()->shape_get_data(get_rid()); } -void ConcavePolygonShape2D::draw(const RID& p_to_rid,const Color& p_color) { - +void ConcavePolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) { PoolVector<Vector2> s = get_segments(); - int len=s.size(); - if (len==0 || (len%2)==1) + int len = s.size(); + if (len == 0 || (len % 2) == 1) return; PoolVector<Vector2>::Read r = s.read(); - for(int i=0;i<len;i+=2) { - VisualServer::get_singleton()->canvas_item_add_line(p_to_rid,r[i],r[i+1],p_color,2); + for (int i = 0; i < len; i += 2) { + VisualServer::get_singleton()->canvas_item_add_line(p_to_rid, r[i], r[i + 1], p_color, 2); } - } Rect2 ConcavePolygonShape2D::get_rect() const { - PoolVector<Vector2> s = get_segments(); - int len=s.size(); - if (len==0) + int len = s.size(); + if (len == 0) return Rect2(); Rect2 rect; PoolVector<Vector2>::Read r = s.read(); - for(int i=0;i<len;i++) { - if (i==0) - rect.pos=r[i]; + for (int i = 0; i < len; i++) { + if (i == 0) + rect.pos = r[i]; else rect.expand_to(r[i]); } return rect; - } - void ConcavePolygonShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_segments","segments"),&ConcavePolygonShape2D::set_segments); - ClassDB::bind_method(D_METHOD("get_segments"),&ConcavePolygonShape2D::get_segments); - - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"segments"),"set_segments","get_segments") ; + ClassDB::bind_method(D_METHOD("set_segments", "segments"), &ConcavePolygonShape2D::set_segments); + ClassDB::bind_method(D_METHOD("get_segments"), &ConcavePolygonShape2D::get_segments); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "segments"), "set_segments", "get_segments"); } -ConcavePolygonShape2D::ConcavePolygonShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONCAVE_POLYGON)) { - +ConcavePolygonShape2D::ConcavePolygonShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONCAVE_POLYGON)) { } - - diff --git a/scene/resources/concave_polygon_shape_2d.h b/scene/resources/concave_polygon_shape_2d.h index 309fb4a7b3..23c602980c 100644 --- a/scene/resources/concave_polygon_shape_2d.h +++ b/scene/resources/concave_polygon_shape_2d.h @@ -32,17 +32,17 @@ #include "scene/resources/shape_2d.h" class ConcavePolygonShape2D : public Shape2D { - GDCLASS( ConcavePolygonShape2D, Shape2D ); -protected: + GDCLASS(ConcavePolygonShape2D, Shape2D); +protected: static void _bind_methods(); -public: - void set_segments(const PoolVector<Vector2>& p_segments); +public: + void set_segments(const PoolVector<Vector2> &p_segments); PoolVector<Vector2> get_segments() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); - virtual Rect2 get_rect() const ; + virtual void draw(const RID &p_to_rid, const Color &p_color); + virtual Rect2 get_rect() const; ConcavePolygonShape2D(); }; diff --git a/scene/resources/convex_polygon_shape.cpp b/scene/resources/convex_polygon_shape.cpp index 207419f8cd..350c4c2d86 100644 --- a/scene/resources/convex_polygon_shape.cpp +++ b/scene/resources/convex_polygon_shape.cpp @@ -27,46 +27,42 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "convex_polygon_shape.h" -#include "servers/physics_server.h" #include "quick_hull.h" +#include "servers/physics_server.h" Vector<Vector3> ConvexPolygonShape::_gen_debug_mesh_lines() { PoolVector<Vector3> points = get_points(); - if (points.size()>3) { + if (points.size() > 3) { QuickHull qh; Vector<Vector3> varr = Variant(points); Geometry::MeshData md; - Error err = qh.build(varr,md); - if (err==OK) { + Error err = qh.build(varr, md); + if (err == OK) { Vector<Vector3> lines; - lines.resize(md.edges.size()*2); - for(int i=0;i<md.edges.size();i++) { - lines[i*2+0]=md.vertices[md.edges[i].a]; - lines[i*2+1]=md.vertices[md.edges[i].b]; + lines.resize(md.edges.size() * 2); + for (int i = 0; i < md.edges.size(); i++) { + lines[i * 2 + 0] = md.vertices[md.edges[i].a]; + lines[i * 2 + 1] = md.vertices[md.edges[i].b]; } return lines; - - } - } return Vector<Vector3>(); } - void ConvexPolygonShape::_update_shape() { - PhysicsServer::get_singleton()->shape_set_data(get_shape(),points); + PhysicsServer::get_singleton()->shape_set_data(get_shape(), points); emit_changed(); } -void ConvexPolygonShape::set_points(const PoolVector<Vector3>& p_points) { +void ConvexPolygonShape::set_points(const PoolVector<Vector3> &p_points) { - points=p_points; + points = p_points; _update_shape(); notify_change_to_owners(); } @@ -76,17 +72,16 @@ PoolVector<Vector3> ConvexPolygonShape::get_points() const { return points; } - void ConvexPolygonShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_points","points"),&ConvexPolygonShape::set_points); - ClassDB::bind_method(D_METHOD("get_points"),&ConvexPolygonShape::get_points); - - ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"points"), "set_points", "get_points") ; + ClassDB::bind_method(D_METHOD("set_points", "points"), &ConvexPolygonShape::set_points); + ClassDB::bind_method(D_METHOD("get_points"), &ConvexPolygonShape::get_points); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "points"), "set_points", "get_points"); } -ConvexPolygonShape::ConvexPolygonShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON)) { +ConvexPolygonShape::ConvexPolygonShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON)) { //set_points(Vector3(1,1,1)); } diff --git a/scene/resources/convex_polygon_shape.h b/scene/resources/convex_polygon_shape.h index 215de941c6..6701c41f0f 100644 --- a/scene/resources/convex_polygon_shape.h +++ b/scene/resources/convex_polygon_shape.h @@ -33,19 +33,18 @@ class ConvexPolygonShape : public Shape { - GDCLASS(ConvexPolygonShape,Shape); + GDCLASS(ConvexPolygonShape, Shape); PoolVector<Vector3> points; protected: - static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); -public: - void set_points(const PoolVector<Vector3>& p_points); +public: + void set_points(const PoolVector<Vector3> &p_points); PoolVector<Vector3> get_points() const; ConvexPolygonShape(); diff --git a/scene/resources/convex_polygon_shape_2d.cpp b/scene/resources/convex_polygon_shape_2d.cpp index 2a4b181611..311614b7c1 100644 --- a/scene/resources/convex_polygon_shape_2d.cpp +++ b/scene/resources/convex_polygon_shape_2d.cpp @@ -28,28 +28,26 @@ /*************************************************************************/ #include "convex_polygon_shape_2d.h" +#include "geometry.h" #include "servers/physics_2d_server.h" #include "servers/visual_server.h" -#include "geometry.h" void ConvexPolygonShape2D::_update_shape() { - Physics2DServer::get_singleton()->shape_set_data(get_rid(),points); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), points); emit_changed(); - } -void ConvexPolygonShape2D::set_point_cloud(const Vector<Vector2>& p_points) { +void ConvexPolygonShape2D::set_point_cloud(const Vector<Vector2> &p_points) { - - Vector<Point2> hull=Geometry::convex_hull_2d(p_points); - ERR_FAIL_COND(hull.size()<3); + Vector<Point2> hull = Geometry::convex_hull_2d(p_points); + ERR_FAIL_COND(hull.size() < 3); set_points(hull); } -void ConvexPolygonShape2D::set_points(const Vector<Vector2>& p_points) { +void ConvexPolygonShape2D::set_points(const Vector<Vector2> &p_points) { - points=p_points; + points = p_points; _update_shape(); } @@ -58,48 +56,41 @@ Vector<Vector2> ConvexPolygonShape2D::get_points() const { return points; } - void ConvexPolygonShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_point_cloud","point_cloud"),&ConvexPolygonShape2D::set_point_cloud); - ClassDB::bind_method(D_METHOD("set_points","points"),&ConvexPolygonShape2D::set_points); - ClassDB::bind_method(D_METHOD("get_points"),&ConvexPolygonShape2D::get_points); - - - - ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"points"),"set_points","get_points") ; + ClassDB::bind_method(D_METHOD("set_point_cloud", "point_cloud"), &ConvexPolygonShape2D::set_point_cloud); + ClassDB::bind_method(D_METHOD("set_points", "points"), &ConvexPolygonShape2D::set_points); + ClassDB::bind_method(D_METHOD("get_points"), &ConvexPolygonShape2D::get_points); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "points"), "set_points", "get_points"); } -void ConvexPolygonShape2D::draw(const RID& p_to_rid,const Color& p_color) { - +void ConvexPolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) { Vector<Color> col; col.push_back(p_color); - VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid,points,col); + VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col); } -Rect2 ConvexPolygonShape2D::get_rect() const { - +Rect2 ConvexPolygonShape2D::get_rect() const { Rect2 rect; - for(int i=0;i<points.size();i++) { - if (i==0) - rect.pos=points[i]; + for (int i = 0; i < points.size(); i++) { + if (i == 0) + rect.pos = points[i]; else rect.expand_to(points[i]); } return rect; - } -ConvexPolygonShape2D::ConvexPolygonShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONVEX_POLYGON)) { - +ConvexPolygonShape2D::ConvexPolygonShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONVEX_POLYGON)) { - int pcount =3; - for(int i=0;i<pcount;i++) - points.push_back(Vector2(Math::sin(i*Math_PI*2/pcount),-Math::cos(i*Math_PI*2/pcount))*10); + int pcount = 3; + for (int i = 0; i < pcount; i++) + points.push_back(Vector2(Math::sin(i * Math_PI * 2 / pcount), -Math::cos(i * Math_PI * 2 / pcount)) * 10); _update_shape(); } diff --git a/scene/resources/convex_polygon_shape_2d.h b/scene/resources/convex_polygon_shape_2d.h index 8a4ad0e6d8..edb302ba5e 100644 --- a/scene/resources/convex_polygon_shape_2d.h +++ b/scene/resources/convex_polygon_shape_2d.h @@ -32,21 +32,21 @@ #include "scene/resources/shape_2d.h" class ConvexPolygonShape2D : public Shape2D { - GDCLASS( ConvexPolygonShape2D, Shape2D ); + GDCLASS(ConvexPolygonShape2D, Shape2D); Vector<Vector2> points; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: - void set_point_cloud(const Vector<Vector2>& p_points); - void set_points(const Vector<Vector2>& p_points); +public: + void set_point_cloud(const Vector<Vector2> &p_points); + void set_points(const Vector<Vector2> &p_points); Vector<Vector2> get_points() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); - virtual Rect2 get_rect() const ; + virtual void draw(const RID &p_to_rid, const Color &p_color); + virtual Rect2 get_rect() const; ConvexPolygonShape2D(); }; diff --git a/scene/resources/curve.cpp b/scene/resources/curve.cpp index 9311ab4dd7..f85220ac23 100644 --- a/scene/resources/curve.cpp +++ b/scene/resources/curve.cpp @@ -29,19 +29,16 @@ #include "curve.h" #include "core_string_names.h" -template<class T> +template <class T> static _FORCE_INLINE_ T _bezier_interp(real_t t, T start, T control_1, T control_2, T end) { - /* Formula from Wikipedia article on Bezier curves. */ + /* Formula from Wikipedia article on Bezier curves. */ real_t omt = (1.0 - t); - real_t omt2 = omt*omt; - real_t omt3 = omt2*omt; - real_t t2 = t*t; - real_t t3 = t2*t; + real_t omt2 = omt * omt; + real_t omt3 = omt2 * omt; + real_t t2 = t * t; + real_t t3 = t2 * t; - return start * omt3 - + control_1 * omt2 * t * 3.0 - + control_2 * omt * t2 * 3.0 - + end * t3; + return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3; } #if 0 @@ -382,92 +379,80 @@ Curve2D::Curve2D() #endif - - - int Curve2D::get_point_count() const { return points.size(); } -void Curve2D::add_point(const Vector2& p_pos, const Vector2& p_in, const Vector2& p_out,int p_atpos) { +void Curve2D::add_point(const Vector2 &p_pos, const Vector2 &p_in, const Vector2 &p_out, int p_atpos) { Point n; - n.pos=p_pos; - n.in=p_in; - n.out=p_out; - if (p_atpos>=0 && p_atpos<points.size()) - points.insert(p_atpos,n); + n.pos = p_pos; + n.in = p_in; + n.out = p_out; + if (p_atpos >= 0 && p_atpos < points.size()) + points.insert(p_atpos, n); else points.push_back(n); - - baked_cache_dirty=true; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); } -void Curve2D::set_point_pos(int p_index, const Vector2& p_pos) { +void Curve2D::set_point_pos(int p_index, const Vector2 &p_pos) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].pos=p_pos; - baked_cache_dirty=true; + points[p_index].pos = p_pos; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } Vector2 Curve2D::get_point_pos(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),Vector2()); + ERR_FAIL_INDEX_V(p_index, points.size(), Vector2()); return points[p_index].pos; - } +void Curve2D::set_point_in(int p_index, const Vector2 &p_in) { -void Curve2D::set_point_in(int p_index, const Vector2& p_in) { - - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].in=p_in; - baked_cache_dirty=true; + points[p_index].in = p_in; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } Vector2 Curve2D::get_point_in(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),Vector2()); + ERR_FAIL_INDEX_V(p_index, points.size(), Vector2()); return points[p_index].in; - } -void Curve2D::set_point_out(int p_index, const Vector2& p_out) { +void Curve2D::set_point_out(int p_index, const Vector2 &p_out) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].out=p_out; - baked_cache_dirty=true; + points[p_index].out = p_out; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } Vector2 Curve2D::get_point_out(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),Vector2()); + ERR_FAIL_INDEX_V(p_index, points.size(), Vector2()); return points[p_index].out; - } - void Curve2D::remove_point(int p_index) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); points.remove(p_index); - baked_cache_dirty=true; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); } void Curve2D::clear_points() { if (!points.empty()) { points.clear(); - baked_cache_dirty=true; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); } } @@ -475,151 +460,138 @@ void Curve2D::clear_points() { Vector2 Curve2D::interpolate(int p_index, float p_offset) const { int pc = points.size(); - ERR_FAIL_COND_V(pc==0,Vector2()); + ERR_FAIL_COND_V(pc == 0, Vector2()); - if (p_index >= pc-1) - return points[pc-1].pos; - else if (p_index<0) + if (p_index >= pc - 1) + return points[pc - 1].pos; + else if (p_index < 0) return points[0].pos; Vector2 p0 = points[p_index].pos; - Vector2 p1 = p0+points[p_index].out; - Vector2 p3 = points[p_index+1].pos; - Vector2 p2 = p3+points[p_index+1].in; + Vector2 p1 = p0 + points[p_index].out; + Vector2 p3 = points[p_index + 1].pos; + Vector2 p2 = p3 + points[p_index + 1].in; - return _bezier_interp(p_offset,p0,p1,p2,p3); + return _bezier_interp(p_offset, p0, p1, p2, p3); } Vector2 Curve2D::interpolatef(real_t p_findex) const { + if (p_findex < 0) + p_findex = 0; + else if (p_findex >= points.size()) + p_findex = points.size(); - if (p_findex<0) - p_findex=0; - else if (p_findex>=points.size()) - p_findex=points.size(); - - return interpolate((int)p_findex,Math::fmod(p_findex,(real_t)1.0)); - + return interpolate((int)p_findex, Math::fmod(p_findex, (real_t)1.0)); } +void Curve2D::_bake_segment2d(Map<float, Vector2> &r_bake, float p_begin, float p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, float p_tol) const { -void Curve2D::_bake_segment2d(Map<float,Vector2>& r_bake, float p_begin, float p_end,const Vector2& p_a,const Vector2& p_out,const Vector2& p_b, const Vector2& p_in,int p_depth,int p_max_depth,float p_tol) const { - - float mp = p_begin+(p_end-p_begin)*0.5; - Vector2 beg = _bezier_interp(p_begin,p_a,p_a+p_out,p_b+p_in,p_b); - Vector2 mid = _bezier_interp(mp,p_a,p_a+p_out,p_b+p_in,p_b); - Vector2 end = _bezier_interp(p_end,p_a,p_a+p_out,p_b+p_in,p_b); + float mp = p_begin + (p_end - p_begin) * 0.5; + Vector2 beg = _bezier_interp(p_begin, p_a, p_a + p_out, p_b + p_in, p_b); + Vector2 mid = _bezier_interp(mp, p_a, p_a + p_out, p_b + p_in, p_b); + Vector2 end = _bezier_interp(p_end, p_a, p_a + p_out, p_b + p_in, p_b); - Vector2 na = (mid-beg).normalized(); - Vector2 nb = (end-mid).normalized(); + Vector2 na = (mid - beg).normalized(); + Vector2 nb = (end - mid).normalized(); float dp = na.dot(nb); - if (dp<Math::cos(Math::deg2rad(p_tol))) { + if (dp < Math::cos(Math::deg2rad(p_tol))) { - r_bake[mp]=mid; + r_bake[mp] = mid; } - if (p_depth<p_max_depth) { - _bake_segment2d(r_bake,p_begin,mp,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol); - _bake_segment2d(r_bake,mp,p_end,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol); + if (p_depth < p_max_depth) { + _bake_segment2d(r_bake, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol); + _bake_segment2d(r_bake, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol); } } - - void Curve2D::_bake() const { if (!baked_cache_dirty) return; - baked_max_ofs=0; - baked_cache_dirty=false; + baked_max_ofs = 0; + baked_cache_dirty = false; - if (points.size()==0) { + if (points.size() == 0) { baked_point_cache.resize(0); return; } - if (points.size()==1) { + if (points.size() == 1) { baked_point_cache.resize(1); - baked_point_cache.set(0,points[0].pos); + baked_point_cache.set(0, points[0].pos); return; } - - Vector2 pos=points[0].pos; + Vector2 pos = points[0].pos; List<Vector2> pointlist; pointlist.push_back(pos); //start always from origin - for(int i=0;i<points.size()-1;i++) { + for (int i = 0; i < points.size() - 1; i++) { float step = 0.1; // at least 10 substeps ought to be enough? float p = 0; - while(p<1.0) { - - float np=p+step; - if (np>1.0) - np=1.0; + while (p < 1.0) { + float np = p + step; + if (np > 1.0) + np = 1.0; - Vector2 npp = _bezier_interp(np, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos); + Vector2 npp = _bezier_interp(np, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos); float d = pos.distance_to(npp); - if (d>bake_interval) { + if (d > bake_interval) { // OK! between P and NP there _has_ to be Something, let's go searching! int iterations = 10; //lots of detail! float low = p; float hi = np; - float mid = low+(hi-low)*0.5; + float mid = low + (hi - low) * 0.5; - for(int j=0;j<iterations;j++) { + for (int j = 0; j < iterations; j++) { - - npp = _bezier_interp(mid, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos); + npp = _bezier_interp(mid, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos); d = pos.distance_to(npp); if (bake_interval < d) - hi=mid; + hi = mid; else - low=mid; - mid = low+(hi-low)*0.5; - + low = mid; + mid = low + (hi - low) * 0.5; } - pos=npp; - p=mid; + pos = npp; + p = mid; pointlist.push_back(pos); } else { - p=np; + p = np; } - } } - Vector2 lastpos = points[points.size()-1].pos; - + Vector2 lastpos = points[points.size() - 1].pos; float rem = pos.distance_to(lastpos); - baked_max_ofs=(pointlist.size()-1)*bake_interval+rem; + baked_max_ofs = (pointlist.size() - 1) * bake_interval + rem; pointlist.push_back(lastpos); baked_point_cache.resize(pointlist.size()); PoolVector2Array::Write w = baked_point_cache.write(); - int idx=0; - + int idx = 0; - for(List<Vector2>::Element *E=pointlist.front();E;E=E->next()) { + for (List<Vector2>::Element *E = pointlist.front(); E; E = E->next()) { - w[idx]=E->get(); + w[idx] = E->get(); idx++; } - } float Curve2D::get_baked_length() const { @@ -629,51 +601,50 @@ float Curve2D::get_baked_length() const { return baked_max_ofs; } -Vector2 Curve2D::interpolate_baked(float p_offset,bool p_cubic) const{ +Vector2 Curve2D::interpolate_baked(float p_offset, bool p_cubic) const { if (baked_cache_dirty) _bake(); //validate// int pc = baked_point_cache.size(); - if (pc==0) { + if (pc == 0) { ERR_EXPLAIN("No points in Curve2D"); - ERR_FAIL_COND_V(pc==0,Vector2()); + ERR_FAIL_COND_V(pc == 0, Vector2()); } - if (pc==1) + if (pc == 1) return baked_point_cache.get(0); - int bpc=baked_point_cache.size(); + int bpc = baked_point_cache.size(); PoolVector2Array::Read r = baked_point_cache.read(); - if (p_offset<0) + if (p_offset < 0) return r[0]; - if (p_offset>=baked_max_ofs) - return r[bpc-1]; + if (p_offset >= baked_max_ofs) + return r[bpc - 1]; - int idx = Math::floor((double)p_offset/(double)bake_interval); - float frac = Math::fmod(p_offset,(float)bake_interval); + int idx = Math::floor((double)p_offset / (double)bake_interval); + float frac = Math::fmod(p_offset, (float)bake_interval); - if (idx>=bpc-1) { - return r[bpc-1]; - } else if (idx==bpc-2) { - frac/=Math::fmod(baked_max_ofs,bake_interval); + if (idx >= bpc - 1) { + return r[bpc - 1]; + } else if (idx == bpc - 2) { + frac /= Math::fmod(baked_max_ofs, bake_interval); } else { - frac/=bake_interval; + frac /= bake_interval; } if (p_cubic) { - Vector2 pre = idx>0? r[idx-1] : r[idx]; - Vector2 post = (idx<(bpc-2))? r[idx+2] : r[idx+1]; - return r[idx].cubic_interpolate(r[idx+1],pre,post,frac); + Vector2 pre = idx > 0 ? r[idx - 1] : r[idx]; + Vector2 post = (idx < (bpc - 2)) ? r[idx + 2] : r[idx + 1]; + return r[idx].cubic_interpolate(r[idx + 1], pre, post, frac); } else { - return r[idx].linear_interpolate(r[idx+1],frac); + return r[idx].linear_interpolate(r[idx + 1], frac); } } - PoolVector2Array Curve2D::get_baked_points() const { if (baked_cache_dirty) @@ -682,16 +653,14 @@ PoolVector2Array Curve2D::get_baked_points() const { return baked_point_cache; } +void Curve2D::set_bake_interval(float p_tolerance) { -void Curve2D::set_bake_interval(float p_tolerance){ - - bake_interval=p_tolerance; - baked_cache_dirty=true; + bake_interval = p_tolerance; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } -float Curve2D::get_bake_interval() const{ +float Curve2D::get_bake_interval() const { return bake_interval; } @@ -701,143 +670,125 @@ Dictionary Curve2D::_get_data() const { Dictionary dc; PoolVector2Array d; - d.resize(points.size()*3); + d.resize(points.size() * 3); PoolVector2Array::Write w = d.write(); + for (int i = 0; i < points.size(); i++) { - for(int i=0;i<points.size();i++) { - - w[i*3+0]=points[i].in; - w[i*3+1]=points[i].out; - w[i*3+2]=points[i].pos; - + w[i * 3 + 0] = points[i].in; + w[i * 3 + 1] = points[i].out; + w[i * 3 + 2] = points[i].pos; } - w=PoolVector2Array::Write(); + w = PoolVector2Array::Write(); - dc["points"]=d; + dc["points"] = d; return dc; } -void Curve2D::_set_data(const Dictionary& p_data){ - +void Curve2D::_set_data(const Dictionary &p_data) { ERR_FAIL_COND(!p_data.has("points")); - PoolVector2Array rp=p_data["points"]; + PoolVector2Array rp = p_data["points"]; int pc = rp.size(); - ERR_FAIL_COND(pc%3!=0); - points.resize(pc/3); + ERR_FAIL_COND(pc % 3 != 0); + points.resize(pc / 3); PoolVector2Array::Read r = rp.read(); - for(int i=0;i<points.size();i++) { + for (int i = 0; i < points.size(); i++) { - points[i].in=r[i*3+0]; - points[i].out=r[i*3+1]; - points[i].pos=r[i*3+2]; + points[i].in = r[i * 3 + 0]; + points[i].out = r[i * 3 + 1]; + points[i].pos = r[i * 3 + 2]; } - baked_cache_dirty=true; - + baked_cache_dirty = true; } - -PoolVector2Array Curve2D::tesselate(int p_max_stages,float p_tolerance) const { +PoolVector2Array Curve2D::tesselate(int p_max_stages, float p_tolerance) const { PoolVector2Array tess; - - if (points.size()==0) { + if (points.size() == 0) { return tess; } - Vector< Map<float,Vector2> > midpoints; + Vector<Map<float, Vector2> > midpoints; - midpoints.resize(points.size()-1); + midpoints.resize(points.size() - 1); - int pc=1; - for(int i=0;i<points.size()-1;i++) { + int pc = 1; + for (int i = 0; i < points.size() - 1; i++) { - _bake_segment2d(midpoints[i],0,1,points[i].pos,points[i].out,points[i+1].pos,points[i+1].in,0,p_max_stages,p_tolerance); + _bake_segment2d(midpoints[i], 0, 1, points[i].pos, points[i].out, points[i + 1].pos, points[i + 1].in, 0, p_max_stages, p_tolerance); pc++; - pc+=midpoints[i].size(); - + pc += midpoints[i].size(); } tess.resize(pc); - PoolVector2Array::Write bpw=tess.write(); - bpw[0]=points[0].pos; - int pidx=0; + PoolVector2Array::Write bpw = tess.write(); + bpw[0] = points[0].pos; + int pidx = 0; - for(int i=0;i<points.size()-1;i++) { + for (int i = 0; i < points.size() - 1; i++) { - for(Map<float,Vector2>::Element *E=midpoints[i].front();E;E=E->next()) { + for (Map<float, Vector2>::Element *E = midpoints[i].front(); E; E = E->next()) { pidx++; bpw[pidx] = E->get(); } pidx++; - bpw[pidx] = points[i+1].pos; - + bpw[pidx] = points[i + 1].pos; } - bpw=PoolVector2Array::Write (); + bpw = PoolVector2Array::Write(); return tess; - } void Curve2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_point_count"),&Curve2D::get_point_count); - ClassDB::bind_method(D_METHOD("add_point","pos","in","out","atpos"),&Curve2D::add_point,DEFVAL(Vector2()),DEFVAL(Vector2()),DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("set_point_pos","idx","pos"),&Curve2D::set_point_pos); - ClassDB::bind_method(D_METHOD("get_point_pos","idx"),&Curve2D::get_point_pos); - ClassDB::bind_method(D_METHOD("set_point_in","idx","pos"),&Curve2D::set_point_in); - ClassDB::bind_method(D_METHOD("get_point_in","idx"),&Curve2D::get_point_in); - ClassDB::bind_method(D_METHOD("set_point_out","idx","pos"),&Curve2D::set_point_out); - ClassDB::bind_method(D_METHOD("get_point_out","idx"),&Curve2D::get_point_out); - ClassDB::bind_method(D_METHOD("remove_point","idx"),&Curve2D::remove_point); - ClassDB::bind_method(D_METHOD("clear_points"),&Curve2D::clear_points); - ClassDB::bind_method(D_METHOD("interpolate","idx","t"),&Curve2D::interpolate); - ClassDB::bind_method(D_METHOD("interpolatef","fofs"),&Curve2D::interpolatef); + ClassDB::bind_method(D_METHOD("get_point_count"), &Curve2D::get_point_count); + ClassDB::bind_method(D_METHOD("add_point", "pos", "in", "out", "atpos"), &Curve2D::add_point, DEFVAL(Vector2()), DEFVAL(Vector2()), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("set_point_pos", "idx", "pos"), &Curve2D::set_point_pos); + ClassDB::bind_method(D_METHOD("get_point_pos", "idx"), &Curve2D::get_point_pos); + ClassDB::bind_method(D_METHOD("set_point_in", "idx", "pos"), &Curve2D::set_point_in); + ClassDB::bind_method(D_METHOD("get_point_in", "idx"), &Curve2D::get_point_in); + ClassDB::bind_method(D_METHOD("set_point_out", "idx", "pos"), &Curve2D::set_point_out); + ClassDB::bind_method(D_METHOD("get_point_out", "idx"), &Curve2D::get_point_out); + ClassDB::bind_method(D_METHOD("remove_point", "idx"), &Curve2D::remove_point); + ClassDB::bind_method(D_METHOD("clear_points"), &Curve2D::clear_points); + ClassDB::bind_method(D_METHOD("interpolate", "idx", "t"), &Curve2D::interpolate); + ClassDB::bind_method(D_METHOD("interpolatef", "fofs"), &Curve2D::interpolatef); //ClassDB::bind_method(D_METHOD("bake","subdivs"),&Curve2D::bake,DEFVAL(10)); - ClassDB::bind_method(D_METHOD("set_bake_interval","distance"),&Curve2D::set_bake_interval); - ClassDB::bind_method(D_METHOD("get_bake_interval"),&Curve2D::get_bake_interval); - - ClassDB::bind_method(D_METHOD("get_baked_length"),&Curve2D::get_baked_length); - ClassDB::bind_method(D_METHOD("interpolate_baked","offset","cubic"),&Curve2D::interpolate_baked,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_baked_points"),&Curve2D::get_baked_points); - ClassDB::bind_method(D_METHOD("tesselate","max_stages","tolerance_degrees"),&Curve2D::tesselate,DEFVAL(5),DEFVAL(4)); + ClassDB::bind_method(D_METHOD("set_bake_interval", "distance"), &Curve2D::set_bake_interval); + ClassDB::bind_method(D_METHOD("get_bake_interval"), &Curve2D::get_bake_interval); - ClassDB::bind_method(D_METHOD("_get_data"),&Curve2D::_get_data); - ClassDB::bind_method(D_METHOD("_set_data"),&Curve2D::_set_data); + ClassDB::bind_method(D_METHOD("get_baked_length"), &Curve2D::get_baked_length); + ClassDB::bind_method(D_METHOD("interpolate_baked", "offset", "cubic"), &Curve2D::interpolate_baked, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_baked_points"), &Curve2D::get_baked_points); + ClassDB::bind_method(D_METHOD("tesselate", "max_stages", "tolerance_degrees"), &Curve2D::tesselate, DEFVAL(5), DEFVAL(4)); + ClassDB::bind_method(D_METHOD("_get_data"), &Curve2D::_get_data); + ClassDB::bind_method(D_METHOD("_set_data"), &Curve2D::_set_data); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "bake_interval",PROPERTY_HINT_RANGE,"0.01,512,0.01"), "set_bake_interval","get_bake_interval"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_data","_get_data"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bake_interval", PROPERTY_HINT_RANGE, "0.01,512,0.01"), "set_bake_interval", "get_bake_interval"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); /*ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_out"), "set_points_out","get_points_out"); ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_pos"), "set_points_pos","get_points_pos"); */ } - - - -Curve2D::Curve2D() -{ - baked_cache_dirty=false; - baked_max_ofs=0; -/* add_point(Vector2(-1,0,0)); +Curve2D::Curve2D() { + baked_cache_dirty = false; + baked_max_ofs = 0; + /* add_point(Vector2(-1,0,0)); add_point(Vector2(0,2,0)); add_point(Vector2(0,3,5));*/ - bake_interval=5; - + bake_interval = 5; } - - - /***********************************************************************************/ /***********************************************************************************/ /***********************************************************************************/ @@ -849,93 +800,82 @@ int Curve3D::get_point_count() const { return points.size(); } -void Curve3D::add_point(const Vector3& p_pos, const Vector3& p_in, const Vector3& p_out,int p_atpos) { +void Curve3D::add_point(const Vector3 &p_pos, const Vector3 &p_in, const Vector3 &p_out, int p_atpos) { Point n; - n.pos=p_pos; - n.in=p_in; - n.out=p_out; - if (p_atpos>=0 && p_atpos<points.size()) - points.insert(p_atpos,n); + n.pos = p_pos; + n.in = p_in; + n.out = p_out; + if (p_atpos >= 0 && p_atpos < points.size()) + points.insert(p_atpos, n); else points.push_back(n); - - baked_cache_dirty=true; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); } -void Curve3D::set_point_pos(int p_index, const Vector3& p_pos) { +void Curve3D::set_point_pos(int p_index, const Vector3 &p_pos) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].pos=p_pos; - baked_cache_dirty=true; + points[p_index].pos = p_pos; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } Vector3 Curve3D::get_point_pos(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),Vector3()); + ERR_FAIL_INDEX_V(p_index, points.size(), Vector3()); return points[p_index].pos; - } void Curve3D::set_point_tilt(int p_index, float p_tilt) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].tilt=p_tilt; - baked_cache_dirty=true; + points[p_index].tilt = p_tilt; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } float Curve3D::get_point_tilt(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),0); + ERR_FAIL_INDEX_V(p_index, points.size(), 0); return points[p_index].tilt; - } +void Curve3D::set_point_in(int p_index, const Vector3 &p_in) { -void Curve3D::set_point_in(int p_index, const Vector3& p_in) { - - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].in=p_in; - baked_cache_dirty=true; + points[p_index].in = p_in; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } Vector3 Curve3D::get_point_in(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),Vector3()); + ERR_FAIL_INDEX_V(p_index, points.size(), Vector3()); return points[p_index].in; - } -void Curve3D::set_point_out(int p_index, const Vector3& p_out) { +void Curve3D::set_point_out(int p_index, const Vector3 &p_out) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); - points[p_index].out=p_out; - baked_cache_dirty=true; + points[p_index].out = p_out; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } Vector3 Curve3D::get_point_out(int p_index) const { - ERR_FAIL_INDEX_V(p_index,points.size(),Vector3()); + ERR_FAIL_INDEX_V(p_index, points.size(), Vector3()); return points[p_index].out; - } - void Curve3D::remove_point(int p_index) { - ERR_FAIL_INDEX(p_index,points.size()); + ERR_FAIL_INDEX(p_index, points.size()); points.remove(p_index); - baked_cache_dirty=true; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); } @@ -943,7 +883,7 @@ void Curve3D::clear_points() { if (!points.empty()) { points.clear(); - baked_cache_dirty=true; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); } } @@ -951,158 +891,147 @@ void Curve3D::clear_points() { Vector3 Curve3D::interpolate(int p_index, float p_offset) const { int pc = points.size(); - ERR_FAIL_COND_V(pc==0,Vector3()); + ERR_FAIL_COND_V(pc == 0, Vector3()); - if (p_index >= pc-1) - return points[pc-1].pos; - else if (p_index<0) + if (p_index >= pc - 1) + return points[pc - 1].pos; + else if (p_index < 0) return points[0].pos; Vector3 p0 = points[p_index].pos; - Vector3 p1 = p0+points[p_index].out; - Vector3 p3 = points[p_index+1].pos; - Vector3 p2 = p3+points[p_index+1].in; + Vector3 p1 = p0 + points[p_index].out; + Vector3 p3 = points[p_index + 1].pos; + Vector3 p2 = p3 + points[p_index + 1].in; - return _bezier_interp(p_offset,p0,p1,p2,p3); + return _bezier_interp(p_offset, p0, p1, p2, p3); } Vector3 Curve3D::interpolatef(real_t p_findex) const { + if (p_findex < 0) + p_findex = 0; + else if (p_findex >= points.size()) + p_findex = points.size(); - if (p_findex<0) - p_findex=0; - else if (p_findex>=points.size()) - p_findex=points.size(); - - return interpolate((int)p_findex,Math::fmod(p_findex,(real_t)1.0)); - + return interpolate((int)p_findex, Math::fmod(p_findex, (real_t)1.0)); } +void Curve3D::_bake_segment3d(Map<float, Vector3> &r_bake, float p_begin, float p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, float p_tol) const { -void Curve3D::_bake_segment3d(Map<float,Vector3>& r_bake, float p_begin, float p_end,const Vector3& p_a,const Vector3& p_out,const Vector3& p_b, const Vector3& p_in,int p_depth,int p_max_depth,float p_tol) const { + float mp = p_begin + (p_end - p_begin) * 0.5; + Vector3 beg = _bezier_interp(p_begin, p_a, p_a + p_out, p_b + p_in, p_b); + Vector3 mid = _bezier_interp(mp, p_a, p_a + p_out, p_b + p_in, p_b); + Vector3 end = _bezier_interp(p_end, p_a, p_a + p_out, p_b + p_in, p_b); - float mp = p_begin+(p_end-p_begin)*0.5; - Vector3 beg = _bezier_interp(p_begin,p_a,p_a+p_out,p_b+p_in,p_b); - Vector3 mid = _bezier_interp(mp,p_a,p_a+p_out,p_b+p_in,p_b); - Vector3 end = _bezier_interp(p_end,p_a,p_a+p_out,p_b+p_in,p_b); - - Vector3 na = (mid-beg).normalized(); - Vector3 nb = (end-mid).normalized(); + Vector3 na = (mid - beg).normalized(); + Vector3 nb = (end - mid).normalized(); float dp = na.dot(nb); - if (dp<Math::cos(Math::deg2rad(p_tol))) { + if (dp < Math::cos(Math::deg2rad(p_tol))) { - r_bake[mp]=mid; + r_bake[mp] = mid; } - if (p_depth<p_max_depth) { - _bake_segment3d(r_bake,p_begin,mp,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol); - _bake_segment3d(r_bake,mp,p_end,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol); + if (p_depth < p_max_depth) { + _bake_segment3d(r_bake, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol); + _bake_segment3d(r_bake, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol); } } - - void Curve3D::_bake() const { if (!baked_cache_dirty) return; - baked_max_ofs=0; - baked_cache_dirty=false; + baked_max_ofs = 0; + baked_cache_dirty = false; - if (points.size()==0) { + if (points.size() == 0) { baked_point_cache.resize(0); baked_tilt_cache.resize(0); return; } - if (points.size()==1) { + if (points.size() == 1) { baked_point_cache.resize(1); - baked_point_cache.set(0,points[0].pos); + baked_point_cache.set(0, points[0].pos); baked_tilt_cache.resize(1); - baked_tilt_cache.set(0,points[0].tilt); + baked_tilt_cache.set(0, points[0].tilt); return; } - - Vector3 pos=points[0].pos; + Vector3 pos = points[0].pos; List<Plane> pointlist; - pointlist.push_back(Plane(pos,points[0].tilt)); + pointlist.push_back(Plane(pos, points[0].tilt)); - for(int i=0;i<points.size()-1;i++) { + for (int i = 0; i < points.size() - 1; i++) { float step = 0.1; // at least 10 substeps ought to be enough? float p = 0; - while(p<1.0) { - - float np=p+step; - if (np>1.0) - np=1.0; + while (p < 1.0) { + float np = p + step; + if (np > 1.0) + np = 1.0; - Vector3 npp = _bezier_interp(np, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos); + Vector3 npp = _bezier_interp(np, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos); float d = pos.distance_to(npp); - if (d>bake_interval) { + if (d > bake_interval) { // OK! between P and NP there _has_ to be Something, let's go searching! int iterations = 10; //lots of detail! float low = p; float hi = np; - float mid = low+(hi-low)*0.5; + float mid = low + (hi - low) * 0.5; - for(int j=0;j<iterations;j++) { + for (int j = 0; j < iterations; j++) { - - npp = _bezier_interp(mid, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos); + npp = _bezier_interp(mid, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos); d = pos.distance_to(npp); if (bake_interval < d) - hi=mid; + hi = mid; else - low=mid; - mid = low+(hi-low)*0.5; - + low = mid; + mid = low + (hi - low) * 0.5; } - pos=npp; - p=mid; + pos = npp; + p = mid; Plane post; - post.normal=pos; - post.d=Math::lerp(points[i].tilt,points[i+1].tilt,mid); + post.normal = pos; + post.d = Math::lerp(points[i].tilt, points[i + 1].tilt, mid); pointlist.push_back(post); } else { - p=np; + p = np; } - } } - Vector3 lastpos = points[points.size()-1].pos; - float lastilt = points[points.size()-1].tilt; + Vector3 lastpos = points[points.size() - 1].pos; + float lastilt = points[points.size() - 1].tilt; float rem = pos.distance_to(lastpos); - baked_max_ofs=(pointlist.size()-1)*bake_interval+rem; - pointlist.push_back(Plane(lastpos,lastilt)); + baked_max_ofs = (pointlist.size() - 1) * bake_interval + rem; + pointlist.push_back(Plane(lastpos, lastilt)); baked_point_cache.resize(pointlist.size()); PoolVector3Array::Write w = baked_point_cache.write(); - int idx=0; + int idx = 0; baked_tilt_cache.resize(pointlist.size()); PoolRealArray::Write wt = baked_tilt_cache.write(); - for(List<Plane>::Element *E=pointlist.front();E;E=E->next()) { + for (List<Plane>::Element *E = pointlist.front(); E; E = E->next()) { - w[idx]=E->get().normal; - wt[idx]=E->get().d; + w[idx] = E->get().normal; + wt[idx] = E->get().d; idx++; } - } float Curve3D::get_baked_length() const { @@ -1112,90 +1041,87 @@ float Curve3D::get_baked_length() const { return baked_max_ofs; } -Vector3 Curve3D::interpolate_baked(float p_offset,bool p_cubic) const{ +Vector3 Curve3D::interpolate_baked(float p_offset, bool p_cubic) const { if (baked_cache_dirty) _bake(); //validate// int pc = baked_point_cache.size(); - if (pc==0) { + if (pc == 0) { ERR_EXPLAIN("No points in Curve3D"); - ERR_FAIL_COND_V(pc==0,Vector3()); + ERR_FAIL_COND_V(pc == 0, Vector3()); } - if (pc==1) + if (pc == 1) return baked_point_cache.get(0); - int bpc=baked_point_cache.size(); + int bpc = baked_point_cache.size(); PoolVector3Array::Read r = baked_point_cache.read(); - if (p_offset<0) + if (p_offset < 0) return r[0]; - if (p_offset>=baked_max_ofs) - return r[bpc-1]; + if (p_offset >= baked_max_ofs) + return r[bpc - 1]; - int idx = Math::floor((double)p_offset/(double)bake_interval); - float frac = Math::fmod(p_offset,bake_interval); + int idx = Math::floor((double)p_offset / (double)bake_interval); + float frac = Math::fmod(p_offset, bake_interval); - if (idx>=bpc-1) { - return r[bpc-1]; - } else if (idx==bpc-2) { - frac/=Math::fmod(baked_max_ofs,bake_interval); + if (idx >= bpc - 1) { + return r[bpc - 1]; + } else if (idx == bpc - 2) { + frac /= Math::fmod(baked_max_ofs, bake_interval); } else { - frac/=bake_interval; + frac /= bake_interval; } if (p_cubic) { - Vector3 pre = idx>0? r[idx-1] : r[idx]; - Vector3 post = (idx<(bpc-2))? r[idx+2] : r[idx+1]; - return r[idx].cubic_interpolate(r[idx+1],pre,post,frac); + Vector3 pre = idx > 0 ? r[idx - 1] : r[idx]; + Vector3 post = (idx < (bpc - 2)) ? r[idx + 2] : r[idx + 1]; + return r[idx].cubic_interpolate(r[idx + 1], pre, post, frac); } else { - return r[idx].linear_interpolate(r[idx+1],frac); + return r[idx].linear_interpolate(r[idx + 1], frac); } } -float Curve3D::interpolate_baked_tilt(float p_offset) const{ +float Curve3D::interpolate_baked_tilt(float p_offset) const { if (baked_cache_dirty) _bake(); //validate// int pc = baked_tilt_cache.size(); - if (pc==0) { + if (pc == 0) { ERR_EXPLAIN("No tilts in Curve3D"); - ERR_FAIL_COND_V(pc==0,0); + ERR_FAIL_COND_V(pc == 0, 0); } - if (pc==1) + if (pc == 1) return baked_tilt_cache.get(0); - int bpc=baked_tilt_cache.size(); + int bpc = baked_tilt_cache.size(); PoolRealArray::Read r = baked_tilt_cache.read(); - if (p_offset<0) + if (p_offset < 0) return r[0]; - if (p_offset>=baked_max_ofs) - return r[bpc-1]; + if (p_offset >= baked_max_ofs) + return r[bpc - 1]; - int idx = Math::floor((double)p_offset/(double)bake_interval); - float frac = Math::fmod(p_offset,bake_interval); + int idx = Math::floor((double)p_offset / (double)bake_interval); + float frac = Math::fmod(p_offset, bake_interval); - if (idx>=bpc-1) { - return r[bpc-1]; - } else if (idx==bpc-2) { - frac/=Math::fmod(baked_max_ofs,bake_interval); + if (idx >= bpc - 1) { + return r[bpc - 1]; + } else if (idx == bpc - 2) { + frac /= Math::fmod(baked_max_ofs, bake_interval); } else { - frac/=bake_interval; + frac /= bake_interval; } - return Math::lerp(r[idx],r[idx+1],frac); - - + return Math::lerp(r[idx], r[idx + 1], frac); } - PoolVector3Array Curve3D::get_baked_points() const { if (baked_cache_dirty) @@ -1204,7 +1130,6 @@ PoolVector3Array Curve3D::get_baked_points() const { return baked_point_cache; } - PoolRealArray Curve3D::get_baked_tilts() const { if (baked_cache_dirty) @@ -1213,16 +1138,14 @@ PoolRealArray Curve3D::get_baked_tilts() const { return baked_tilt_cache; } +void Curve3D::set_bake_interval(float p_tolerance) { -void Curve3D::set_bake_interval(float p_tolerance){ - - bake_interval=p_tolerance; - baked_cache_dirty=true; + bake_interval = p_tolerance; + baked_cache_dirty = true; emit_signal(CoreStringNames::get_singleton()->changed); - } -float Curve3D::get_bake_interval() const{ +float Curve3D::get_bake_interval() const { return bake_interval; } @@ -1232,163 +1155,134 @@ Dictionary Curve3D::_get_data() const { Dictionary dc; PoolVector3Array d; - d.resize(points.size()*3); + d.resize(points.size() * 3); PoolVector3Array::Write w = d.write(); PoolRealArray t; t.resize(points.size()); PoolRealArray::Write wt = t.write(); + for (int i = 0; i < points.size(); i++) { - for(int i=0;i<points.size();i++) { - - w[i*3+0]=points[i].in; - w[i*3+1]=points[i].out; - w[i*3+2]=points[i].pos; - wt[i]=points[i].tilt; + w[i * 3 + 0] = points[i].in; + w[i * 3 + 1] = points[i].out; + w[i * 3 + 2] = points[i].pos; + wt[i] = points[i].tilt; } - w=PoolVector3Array::Write(); - wt=PoolRealArray::Write(); + w = PoolVector3Array::Write(); + wt = PoolRealArray::Write(); - dc["points"]=d; - dc["tilts"]=t; + dc["points"] = d; + dc["tilts"] = t; return dc; } -void Curve3D::_set_data(const Dictionary& p_data){ - +void Curve3D::_set_data(const Dictionary &p_data) { ERR_FAIL_COND(!p_data.has("points")); ERR_FAIL_COND(!p_data.has("tilts")); - PoolVector3Array rp=p_data["points"]; + PoolVector3Array rp = p_data["points"]; int pc = rp.size(); - ERR_FAIL_COND(pc%3!=0); - points.resize(pc/3); + ERR_FAIL_COND(pc % 3 != 0); + points.resize(pc / 3); PoolVector3Array::Read r = rp.read(); - PoolRealArray rtl=p_data["tilts"]; - PoolRealArray::Read rt=rtl.read(); + PoolRealArray rtl = p_data["tilts"]; + PoolRealArray::Read rt = rtl.read(); - for(int i=0;i<points.size();i++) { + for (int i = 0; i < points.size(); i++) { - points[i].in=r[i*3+0]; - points[i].out=r[i*3+1]; - points[i].pos=r[i*3+2]; - points[i].tilt=rt[i]; + points[i].in = r[i * 3 + 0]; + points[i].out = r[i * 3 + 1]; + points[i].pos = r[i * 3 + 2]; + points[i].tilt = rt[i]; } - baked_cache_dirty=true; - + baked_cache_dirty = true; } - -PoolVector3Array Curve3D::tesselate(int p_max_stages,float p_tolerance) const { +PoolVector3Array Curve3D::tesselate(int p_max_stages, float p_tolerance) const { PoolVector3Array tess; - - if (points.size()==0) { + if (points.size() == 0) { return tess; } - Vector< Map<float,Vector3> > midpoints; + Vector<Map<float, Vector3> > midpoints; - midpoints.resize(points.size()-1); + midpoints.resize(points.size() - 1); - int pc=1; - for(int i=0;i<points.size()-1;i++) { + int pc = 1; + for (int i = 0; i < points.size() - 1; i++) { - _bake_segment3d(midpoints[i],0,1,points[i].pos,points[i].out,points[i+1].pos,points[i+1].in,0,p_max_stages,p_tolerance); + _bake_segment3d(midpoints[i], 0, 1, points[i].pos, points[i].out, points[i + 1].pos, points[i + 1].in, 0, p_max_stages, p_tolerance); pc++; - pc+=midpoints[i].size(); - + pc += midpoints[i].size(); } tess.resize(pc); - PoolVector3Array::Write bpw=tess.write(); - bpw[0]=points[0].pos; - int pidx=0; + PoolVector3Array::Write bpw = tess.write(); + bpw[0] = points[0].pos; + int pidx = 0; - for(int i=0;i<points.size()-1;i++) { + for (int i = 0; i < points.size() - 1; i++) { - for(Map<float,Vector3>::Element *E=midpoints[i].front();E;E=E->next()) { + for (Map<float, Vector3>::Element *E = midpoints[i].front(); E; E = E->next()) { pidx++; bpw[pidx] = E->get(); } pidx++; - bpw[pidx] = points[i+1].pos; - + bpw[pidx] = points[i + 1].pos; } - bpw=PoolVector3Array::Write (); + bpw = PoolVector3Array::Write(); return tess; - } void Curve3D::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_point_count"),&Curve3D::get_point_count); - ClassDB::bind_method(D_METHOD("add_point","pos","in","out","atpos"),&Curve3D::add_point,DEFVAL(Vector3()),DEFVAL(Vector3()),DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("set_point_pos","idx","pos"),&Curve3D::set_point_pos); - ClassDB::bind_method(D_METHOD("get_point_pos","idx"),&Curve3D::get_point_pos); - ClassDB::bind_method(D_METHOD("set_point_tilt","idx","tilt"),&Curve3D::set_point_tilt); - ClassDB::bind_method(D_METHOD("get_point_tilt","idx"),&Curve3D::get_point_tilt); - ClassDB::bind_method(D_METHOD("set_point_in","idx","pos"),&Curve3D::set_point_in); - ClassDB::bind_method(D_METHOD("get_point_in","idx"),&Curve3D::get_point_in); - ClassDB::bind_method(D_METHOD("set_point_out","idx","pos"),&Curve3D::set_point_out); - ClassDB::bind_method(D_METHOD("get_point_out","idx"),&Curve3D::get_point_out); - ClassDB::bind_method(D_METHOD("remove_point","idx"),&Curve3D::remove_point); - ClassDB::bind_method(D_METHOD("clear_points"),&Curve3D::clear_points); - ClassDB::bind_method(D_METHOD("interpolate","idx","t"),&Curve3D::interpolate); - ClassDB::bind_method(D_METHOD("interpolatef","fofs"),&Curve3D::interpolatef); + ClassDB::bind_method(D_METHOD("get_point_count"), &Curve3D::get_point_count); + ClassDB::bind_method(D_METHOD("add_point", "pos", "in", "out", "atpos"), &Curve3D::add_point, DEFVAL(Vector3()), DEFVAL(Vector3()), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("set_point_pos", "idx", "pos"), &Curve3D::set_point_pos); + ClassDB::bind_method(D_METHOD("get_point_pos", "idx"), &Curve3D::get_point_pos); + ClassDB::bind_method(D_METHOD("set_point_tilt", "idx", "tilt"), &Curve3D::set_point_tilt); + ClassDB::bind_method(D_METHOD("get_point_tilt", "idx"), &Curve3D::get_point_tilt); + ClassDB::bind_method(D_METHOD("set_point_in", "idx", "pos"), &Curve3D::set_point_in); + ClassDB::bind_method(D_METHOD("get_point_in", "idx"), &Curve3D::get_point_in); + ClassDB::bind_method(D_METHOD("set_point_out", "idx", "pos"), &Curve3D::set_point_out); + ClassDB::bind_method(D_METHOD("get_point_out", "idx"), &Curve3D::get_point_out); + ClassDB::bind_method(D_METHOD("remove_point", "idx"), &Curve3D::remove_point); + ClassDB::bind_method(D_METHOD("clear_points"), &Curve3D::clear_points); + ClassDB::bind_method(D_METHOD("interpolate", "idx", "t"), &Curve3D::interpolate); + ClassDB::bind_method(D_METHOD("interpolatef", "fofs"), &Curve3D::interpolatef); //ClassDB::bind_method(D_METHOD("bake","subdivs"),&Curve3D::bake,DEFVAL(10)); - ClassDB::bind_method(D_METHOD("set_bake_interval","distance"),&Curve3D::set_bake_interval); - ClassDB::bind_method(D_METHOD("get_bake_interval"),&Curve3D::get_bake_interval); - - ClassDB::bind_method(D_METHOD("get_baked_length"),&Curve3D::get_baked_length); - ClassDB::bind_method(D_METHOD("interpolate_baked","offset","cubic"),&Curve3D::interpolate_baked,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_baked_points"),&Curve3D::get_baked_points); - ClassDB::bind_method(D_METHOD("get_baked_tilts"),&Curve3D::get_baked_tilts); - ClassDB::bind_method(D_METHOD("tesselate","max_stages","tolerance_degrees"),&Curve3D::tesselate,DEFVAL(5),DEFVAL(4)); + ClassDB::bind_method(D_METHOD("set_bake_interval", "distance"), &Curve3D::set_bake_interval); + ClassDB::bind_method(D_METHOD("get_bake_interval"), &Curve3D::get_bake_interval); - ClassDB::bind_method(D_METHOD("_get_data"),&Curve3D::_get_data); - ClassDB::bind_method(D_METHOD("_set_data"),&Curve3D::_set_data); + ClassDB::bind_method(D_METHOD("get_baked_length"), &Curve3D::get_baked_length); + ClassDB::bind_method(D_METHOD("interpolate_baked", "offset", "cubic"), &Curve3D::interpolate_baked, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_baked_points"), &Curve3D::get_baked_points); + ClassDB::bind_method(D_METHOD("get_baked_tilts"), &Curve3D::get_baked_tilts); + ClassDB::bind_method(D_METHOD("tesselate", "max_stages", "tolerance_degrees"), &Curve3D::tesselate, DEFVAL(5), DEFVAL(4)); + ClassDB::bind_method(D_METHOD("_get_data"), &Curve3D::_get_data); + ClassDB::bind_method(D_METHOD("_set_data"), &Curve3D::_set_data); - ADD_PROPERTY( PropertyInfo( Variant::REAL, "bake_interval",PROPERTY_HINT_RANGE,"0.01,512,0.01"), "set_bake_interval","get_bake_interval"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_data","_get_data"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "bake_interval", PROPERTY_HINT_RANGE, "0.01,512,0.01"), "set_bake_interval", "get_bake_interval"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); /*ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_out"), "set_points_out","get_points_out"); ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_pos"), "set_points_pos","get_points_pos"); */ } - - - -Curve3D::Curve3D() -{ - baked_cache_dirty=false; - baked_max_ofs=0; -/* add_point(Vector3(-1,0,0)); +Curve3D::Curve3D() { + baked_cache_dirty = false; + baked_max_ofs = 0; + /* add_point(Vector3(-1,0,0)); add_point(Vector3(0,2,0)); add_point(Vector3(0,3,5));*/ - bake_interval=0.2; - + bake_interval = 0.2; } - - - - - - - - - - - - - - - diff --git a/scene/resources/curve.h b/scene/resources/curve.h index 3362109354..2a8fab7f4c 100644 --- a/scene/resources/curve.h +++ b/scene/resources/curve.h @@ -81,10 +81,9 @@ public: #endif - class Curve2D : public Resource { - GDCLASS(Curve2D,Resource); + GDCLASS(Curve2D, Resource); struct Point { @@ -93,7 +92,6 @@ class Curve2D : public Resource { Vector2 pos; }; - Vector<Point> points; struct BakedPoint { @@ -106,31 +104,25 @@ class Curve2D : public Resource { mutable PoolVector2Array baked_point_cache; mutable float baked_max_ofs; - void _bake() const; float bake_interval; - void _bake_segment2d(Map<float,Vector2>& r_bake, float p_begin, float p_end,const Vector2& p_a,const Vector2& p_out,const Vector2& p_b, const Vector2& p_in,int p_depth,int p_max_depth,float p_tol) const; + void _bake_segment2d(Map<float, Vector2> &r_bake, float p_begin, float p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, float p_tol) const; Dictionary _get_data() const; void _set_data(const Dictionary &p_data); protected: - static void _bind_methods(); - - public: - - int get_point_count() const; - void add_point(const Vector2& p_pos, const Vector2& p_in=Vector2(), const Vector2& p_out=Vector2(),int p_atpos=-1); - void set_point_pos(int p_index, const Vector2& p_pos); + void add_point(const Vector2 &p_pos, const Vector2 &p_in = Vector2(), const Vector2 &p_out = Vector2(), int p_atpos = -1); + void set_point_pos(int p_index, const Vector2 &p_pos); Vector2 get_point_pos(int p_index) const; - void set_point_in(int p_index, const Vector2& p_in); + void set_point_in(int p_index, const Vector2 &p_in); Vector2 get_point_in(int p_index) const; - void set_point_out(int p_index, const Vector2& p_out); + void set_point_out(int p_index, const Vector2 &p_out); Vector2 get_point_out(int p_index) const; void remove_point(int p_index); void clear_points(); @@ -138,26 +130,21 @@ public: Vector2 interpolate(int p_index, float p_offset) const; Vector2 interpolatef(real_t p_findex) const; - void set_bake_interval(float p_distance); float get_bake_interval() const; - float get_baked_length() const; - Vector2 interpolate_baked(float p_offset,bool p_cubic=false) const; + Vector2 interpolate_baked(float p_offset, bool p_cubic = false) const; PoolVector2Array get_baked_points() const; //useful for going thru - PoolVector2Array tesselate(int p_max_stages=5,float p_tolerance=4) const; //useful for display - + PoolVector2Array tesselate(int p_max_stages = 5, float p_tolerance = 4) const; //useful for display Curve2D(); }; - - class Curve3D : public Resource { - GDCLASS(Curve3D,Resource); + GDCLASS(Curve3D, Resource); struct Point { @@ -166,10 +153,9 @@ class Curve3D : public Resource { Vector3 pos; float tilt; - Point() { tilt=0; } + Point() { tilt = 0; } }; - Vector<Point> points; struct BakedPoint { @@ -183,33 +169,27 @@ class Curve3D : public Resource { mutable PoolRealArray baked_tilt_cache; mutable float baked_max_ofs; - void _bake() const; float bake_interval; - void _bake_segment3d(Map<float,Vector3>& r_bake, float p_begin, float p_end,const Vector3& p_a,const Vector3& p_out,const Vector3& p_b, const Vector3& p_in,int p_depth,int p_max_depth,float p_tol) const; + void _bake_segment3d(Map<float, Vector3> &r_bake, float p_begin, float p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, float p_tol) const; Dictionary _get_data() const; void _set_data(const Dictionary &p_data); protected: - static void _bind_methods(); - - public: - - int get_point_count() const; - void add_point(const Vector3& p_pos, const Vector3& p_in=Vector3(), const Vector3& p_out=Vector3(),int p_atpos=-1); - void set_point_pos(int p_index, const Vector3& p_pos); + void add_point(const Vector3 &p_pos, const Vector3 &p_in = Vector3(), const Vector3 &p_out = Vector3(), int p_atpos = -1); + void set_point_pos(int p_index, const Vector3 &p_pos); Vector3 get_point_pos(int p_index) const; void set_point_tilt(int p_index, float p_tilt); float get_point_tilt(int p_index) const; - void set_point_in(int p_index, const Vector3& p_in); + void set_point_in(int p_index, const Vector3 &p_in); Vector3 get_point_in(int p_index) const; - void set_point_out(int p_index, const Vector3& p_out); + void set_point_out(int p_index, const Vector3 &p_out); Vector3 get_point_out(int p_index) const; void remove_point(int p_index); void clear_points(); @@ -217,19 +197,16 @@ public: Vector3 interpolate(int p_index, float p_offset) const; Vector3 interpolatef(real_t p_findex) const; - void set_bake_interval(float p_distance); float get_bake_interval() const; - float get_baked_length() const; - Vector3 interpolate_baked(float p_offset,bool p_cubic=false) const; + Vector3 interpolate_baked(float p_offset, bool p_cubic = false) const; float interpolate_baked_tilt(float p_offset) const; PoolVector3Array get_baked_points() const; //useful for going thru PoolRealArray get_baked_tilts() const; //useful for going thru - PoolVector3Array tesselate(int p_max_stages=5,float p_tolerance=4) const; //useful for display - + PoolVector3Array tesselate(int p_max_stages = 5, float p_tolerance = 4) const; //useful for display Curve3D(); }; diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp index dbe0f3e33e..60490d70ca 100644 --- a/scene/resources/default_theme/default_theme.cpp +++ b/scene/resources/default_theme/default_theme.cpp @@ -31,196 +31,182 @@ #include "scene/resources/theme.h" -#include "theme_data.h" #include "os/os.h" +#include "theme_data.h" -#include "font_lodpi.inc" #include "font_hidpi.inc" +#include "font_lodpi.inc" -typedef Map<const void*,Ref<ImageTexture> > TexCacheMap; +typedef Map<const void *, Ref<ImageTexture> > TexCacheMap; -static TexCacheMap *tex_cache; -static float scale=1; +static TexCacheMap *tex_cache; +static float scale = 1; -template<class T> -static Ref<StyleBoxTexture> make_stylebox(T p_src,float p_left, float p_top, float p_right, float p_botton,float p_margin_left=-1, float p_margin_top=-1, float p_margin_right=-1, float p_margin_botton=-1, bool p_draw_center=true) { +template <class T> +static Ref<StyleBoxTexture> make_stylebox(T p_src, float p_left, float p_top, float p_right, float p_botton, float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_botton = -1, bool p_draw_center = true) { Ref<ImageTexture> texture; - if (tex_cache->has(p_src)) { - texture=(*tex_cache)[p_src]; + texture = (*tex_cache)[p_src]; } else { - texture = Ref<ImageTexture>( memnew( ImageTexture ) ); + texture = Ref<ImageTexture>(memnew(ImageTexture)); Image img(p_src); - if (scale>1) { - Size2 orig_size = Size2(img.get_width(),img.get_height()); + if (scale > 1) { + Size2 orig_size = Size2(img.get_width(), img.get_height()); img.convert(Image::FORMAT_RGBA8); img.expand_x2_hq2x(); - if (scale!=2.0) { - img.resize(orig_size.x*scale,orig_size.y*scale); + if (scale != 2.0) { + img.resize(orig_size.x * scale, orig_size.y * scale); } - } else if (scale<1) { - Size2 orig_size = Size2(img.get_width(),img.get_height()); + } else if (scale < 1) { + Size2 orig_size = Size2(img.get_width(), img.get_height()); img.convert(Image::FORMAT_RGBA8); - img.resize(orig_size.x*scale,orig_size.y*scale); + img.resize(orig_size.x * scale, orig_size.y * scale); } - texture->create_from_image( img,ImageTexture::FLAG_FILTER ); - (*tex_cache)[p_src]=texture; + texture->create_from_image(img, ImageTexture::FLAG_FILTER); + (*tex_cache)[p_src] = texture; } - - Ref<StyleBoxTexture> style( memnew( StyleBoxTexture ) ); + Ref<StyleBoxTexture> style(memnew(StyleBoxTexture)); style->set_texture(texture); - style->set_margin_size( MARGIN_LEFT, p_left * scale); - style->set_margin_size( MARGIN_RIGHT, p_right * scale); - style->set_margin_size( MARGIN_BOTTOM, p_botton * scale); - style->set_margin_size( MARGIN_TOP, p_top * scale); - style->set_default_margin( MARGIN_LEFT, p_margin_left * scale); - style->set_default_margin( MARGIN_RIGHT, p_margin_right * scale); - style->set_default_margin( MARGIN_BOTTOM, p_margin_botton * scale); - style->set_default_margin( MARGIN_TOP, p_margin_top * scale); + style->set_margin_size(MARGIN_LEFT, p_left * scale); + style->set_margin_size(MARGIN_RIGHT, p_right * scale); + style->set_margin_size(MARGIN_BOTTOM, p_botton * scale); + style->set_margin_size(MARGIN_TOP, p_top * scale); + style->set_default_margin(MARGIN_LEFT, p_margin_left * scale); + style->set_default_margin(MARGIN_RIGHT, p_margin_right * scale); + style->set_default_margin(MARGIN_BOTTOM, p_margin_botton * scale); + style->set_default_margin(MARGIN_TOP, p_margin_top * scale); style->set_draw_center(p_draw_center); return style; } +static Ref<StyleBoxTexture> sb_expand(Ref<StyleBoxTexture> p_sbox, float p_left, float p_top, float p_right, float p_botton) { -static Ref<StyleBoxTexture> sb_expand(Ref<StyleBoxTexture> p_sbox,float p_left, float p_top, float p_right, float p_botton) { - - p_sbox->set_expand_margin_size(MARGIN_LEFT,p_left * scale); - p_sbox->set_expand_margin_size(MARGIN_TOP,p_top * scale); - p_sbox->set_expand_margin_size(MARGIN_RIGHT,p_right * scale); - p_sbox->set_expand_margin_size(MARGIN_BOTTOM,p_botton * scale); + p_sbox->set_expand_margin_size(MARGIN_LEFT, p_left * scale); + p_sbox->set_expand_margin_size(MARGIN_TOP, p_top * scale); + p_sbox->set_expand_margin_size(MARGIN_RIGHT, p_right * scale); + p_sbox->set_expand_margin_size(MARGIN_BOTTOM, p_botton * scale); return p_sbox; } -template<class T> +template <class T> static Ref<Texture> make_icon(T p_src) { - - Ref<ImageTexture> texture( memnew( ImageTexture ) ); + Ref<ImageTexture> texture(memnew(ImageTexture)); Image img = Image(p_src); - if (scale>1) { - Size2 orig_size = Size2(img.get_width(),img.get_height()); + if (scale > 1) { + Size2 orig_size = Size2(img.get_width(), img.get_height()); img.convert(Image::FORMAT_RGBA8); img.expand_x2_hq2x(); - if (scale!=2.0) { - img.resize(orig_size.x*scale,orig_size.y*scale); + if (scale != 2.0) { + img.resize(orig_size.x * scale, orig_size.y * scale); } - } else if (scale<1) { - Size2 orig_size = Size2(img.get_width(),img.get_height()); + } else if (scale < 1) { + Size2 orig_size = Size2(img.get_width(), img.get_height()); img.convert(Image::FORMAT_RGBA8); - img.resize(orig_size.x*scale,orig_size.y*scale); + img.resize(orig_size.x * scale, orig_size.y * scale); } - texture->create_from_image( img,ImageTexture::FLAG_FILTER ); + texture->create_from_image(img, ImageTexture::FLAG_FILTER); return texture; } -static Ref<Shader> make_shader(const char*vertex_code,const char*fragment_code,const char*lighting_code) { - Ref<Shader> shader = (memnew( Shader(Shader::MODE_CANVAS_ITEM) )); +static Ref<Shader> make_shader(const char *vertex_code, const char *fragment_code, const char *lighting_code) { + Ref<Shader> shader = (memnew(Shader(Shader::MODE_CANVAS_ITEM))); //shader->set_code(vertex_code, fragment_code, lighting_code); return shader; } -static Ref<BitmapFont> make_font(int p_height,int p_ascent, int p_valign, int p_charcount, const int *p_chars,const Ref<Texture> &p_texture) { - +static Ref<BitmapFont> make_font(int p_height, int p_ascent, int p_valign, int p_charcount, const int *p_chars, const Ref<Texture> &p_texture) { - Ref<BitmapFont> font( memnew( BitmapFont ) ); - font->add_texture( p_texture ); + Ref<BitmapFont> font(memnew(BitmapFont)); + font->add_texture(p_texture); - for (int i=0;i<p_charcount;i++) { + for (int i = 0; i < p_charcount; i++) { - const int *c = &p_chars[i*8]; + const int *c = &p_chars[i * 8]; - int chr=c[0]; + int chr = c[0]; Rect2 frect; - frect.pos.x=c[1]; - frect.pos.y=c[2]; - frect.size.x=c[3]; - frect.size.y=c[4]; - Point2 align( c[5], c[6]+p_valign); - int advance=c[7]; - - - font->add_char( chr, 0, frect, align,advance ); - + frect.pos.x = c[1]; + frect.pos.y = c[2]; + frect.size.x = c[3]; + frect.size.y = c[4]; + Point2 align(c[5], c[6] + p_valign); + int advance = c[7]; + + font->add_char(chr, 0, frect, align, advance); } - font->set_height( p_height ); - font->set_ascent( p_ascent ); + font->set_height(p_height); + font->set_ascent(p_ascent); return font; } +static Ref<BitmapFont> make_font2(int p_height, int p_ascent, int p_charcount, const int *p_char_rects, int p_kerning_count, const int *p_kernings, int p_w, int p_h, const unsigned char *p_img) { - -static Ref<BitmapFont> make_font2(int p_height,int p_ascent, int p_charcount, const int *p_char_rects,int p_kerning_count,const int *p_kernings,int p_w, int p_h, const unsigned char *p_img) { - - - Ref<BitmapFont> font( memnew( BitmapFont ) ); + Ref<BitmapFont> font(memnew(BitmapFont)); Image image(p_img); - Ref<ImageTexture> tex = memnew( ImageTexture ); + Ref<ImageTexture> tex = memnew(ImageTexture); tex->create_from_image(image); - font->add_texture( tex ); + font->add_texture(tex); - for (int i=0;i<p_charcount;i++) { + for (int i = 0; i < p_charcount; i++) { - const int *c = &p_char_rects[i*8]; + const int *c = &p_char_rects[i * 8]; - int chr=c[0]; + int chr = c[0]; Rect2 frect; - frect.pos.x=c[1]; - frect.pos.y=c[2]; - frect.size.x=c[3]; - frect.size.y=c[4]; - Point2 align( c[6], c[5]); - int advance=c[7]; - - font->add_char( chr, 0, frect, align,advance ); - + frect.pos.x = c[1]; + frect.pos.y = c[2]; + frect.size.x = c[3]; + frect.size.y = c[4]; + Point2 align(c[6], c[5]); + int advance = c[7]; + + font->add_char(chr, 0, frect, align, advance); } - for(int i=0;i<p_kerning_count;i++) { + for (int i = 0; i < p_kerning_count; i++) { - font->add_kerning_pair(p_kernings[i*3+0],p_kernings[i*3+1],p_kernings[i*3+2]); + font->add_kerning_pair(p_kernings[i * 3 + 0], p_kernings[i * 3 + 1], p_kernings[i * 3 + 2]); } - font->set_height( p_height ); - font->set_ascent( p_ascent ); + font->set_height(p_height); + font->set_ascent(p_ascent); return font; } +static Ref<StyleBox> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_botton = -1) { -static Ref<StyleBox> make_empty_stylebox(float p_margin_left=-1, float p_margin_top=-1, float p_margin_right=-1, float p_margin_botton=-1) { + Ref<StyleBox> style(memnew(StyleBoxEmpty)); - Ref<StyleBox> style( memnew( StyleBoxEmpty) ); - - style->set_default_margin( MARGIN_LEFT, p_margin_left * scale); - style->set_default_margin( MARGIN_RIGHT, p_margin_right * scale); - style->set_default_margin( MARGIN_BOTTOM, p_margin_botton * scale); - style->set_default_margin( MARGIN_TOP, p_margin_top * scale); + style->set_default_margin(MARGIN_LEFT, p_margin_left * scale); + style->set_default_margin(MARGIN_RIGHT, p_margin_right * scale); + style->set_default_margin(MARGIN_BOTTOM, p_margin_botton * scale); + style->set_default_margin(MARGIN_TOP, p_margin_top * scale); return style; } +void fill_default_theme(Ref<Theme> &t, const Ref<Font> &default_font, const Ref<Font> &large_font, Ref<Texture> &default_icon, Ref<StyleBox> &default_style, float p_scale) { + scale = p_scale; -void fill_default_theme(Ref<Theme>& t, const Ref<Font> & default_font, const Ref<Font> & large_font, Ref<Texture>& default_icon, Ref<StyleBox>& default_style, float p_scale) { - - scale=p_scale; - - tex_cache = memnew( TexCacheMap ); + tex_cache = memnew(TexCacheMap); //Ref<BitmapFont> default_font = make_font(_bi_font_normal_height,_bi_font_normal_ascent,_bi_font_normal_valign,_bi_font_normal_charcount,_bi_font_normal_characters,make_icon(font_normal_png)); @@ -230,356 +216,324 @@ void fill_default_theme(Ref<Theme>& t, const Ref<Font> & default_font, const Ref Color control_font_color_lower = Color::html("a0a0a0"); Color control_font_color_low = Color::html("b0b0b0"); Color control_font_color_hover = Color::html("f0f0f0"); - Color control_font_color_disabled = Color(0.9,0.9,0.9,0.2); + Color control_font_color_disabled = Color(0.9, 0.9, 0.9, 0.2); Color control_font_color_pressed = Color::html("ffffff"); Color font_color_selection = Color::html("7d7d7d"); - // Panel - t->set_stylebox("panel","Panel", make_stylebox( panel_bg_png,0,0,0,0) ); - - + t->set_stylebox("panel", "Panel", make_stylebox(panel_bg_png, 0, 0, 0, 0)); // Focus - Ref<StyleBoxTexture> focus = make_stylebox( focus_png,5,5,5,5); - for(int i=0;i<4;i++) { - focus->set_expand_margin_size(Margin(i),1 *scale); + Ref<StyleBoxTexture> focus = make_stylebox(focus_png, 5, 5, 5, 5); + for (int i = 0; i < 4; i++) { + focus->set_expand_margin_size(Margin(i), 1 * scale); } - - // Button - Ref<StyleBox> sb_button_normal = sb_expand( make_stylebox( button_normal_png,4,4,4,4,6,3,6,3),2,2,2,2); - Ref<StyleBox> sb_button_pressed = sb_expand( make_stylebox( button_pressed_png,4,4,4,4,6,3,6,3),2,2,2,2); - Ref<StyleBox> sb_button_hover = sb_expand( make_stylebox( button_hover_png,4,4,4,4,6,2,6,2),2,2,2,2); - Ref<StyleBox> sb_button_disabled = sb_expand( make_stylebox( button_disabled_png,4,4,4,4,6,2,6,2),2,2,2,2); - Ref<StyleBox> sb_button_focus = sb_expand( make_stylebox( button_focus_png,4,4,4,4,6,2,6,2),2,2,2,2); + Ref<StyleBox> sb_button_normal = sb_expand(make_stylebox(button_normal_png, 4, 4, 4, 4, 6, 3, 6, 3), 2, 2, 2, 2); + Ref<StyleBox> sb_button_pressed = sb_expand(make_stylebox(button_pressed_png, 4, 4, 4, 4, 6, 3, 6, 3), 2, 2, 2, 2); + Ref<StyleBox> sb_button_hover = sb_expand(make_stylebox(button_hover_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2); + Ref<StyleBox> sb_button_disabled = sb_expand(make_stylebox(button_disabled_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2); + Ref<StyleBox> sb_button_focus = sb_expand(make_stylebox(button_focus_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2); - t->set_stylebox("normal","Button", sb_button_normal); - t->set_stylebox("pressed","Button", sb_button_pressed); - t->set_stylebox("hover","Button", sb_button_hover); - t->set_stylebox("disabled","Button", sb_button_disabled); - t->set_stylebox("focus","Button", sb_button_focus); + t->set_stylebox("normal", "Button", sb_button_normal); + t->set_stylebox("pressed", "Button", sb_button_pressed); + t->set_stylebox("hover", "Button", sb_button_hover); + t->set_stylebox("disabled", "Button", sb_button_disabled); + t->set_stylebox("focus", "Button", sb_button_focus); - t->set_font("font","Button", default_font ); + t->set_font("font", "Button", default_font); - t->set_color("font_color","Button", control_font_color ); - t->set_color("font_color_pressed","Button", control_font_color_pressed ); - t->set_color("font_color_hover","Button", control_font_color_hover ); - t->set_color("font_color_disabled","Button", control_font_color_disabled ); + t->set_color("font_color", "Button", control_font_color); + t->set_color("font_color_pressed", "Button", control_font_color_pressed); + t->set_color("font_color_hover", "Button", control_font_color_hover); + t->set_color("font_color_disabled", "Button", control_font_color_disabled); - t->set_constant("hseparation","Button", 2 *scale); + t->set_constant("hseparation", "Button", 2 * scale); // LinkButton - t->set_font("font","LinkButton", default_font ); + t->set_font("font", "LinkButton", default_font); - t->set_color("font_color","LinkButton", control_font_color ); - t->set_color("font_color_pressed","LinkButton", control_font_color_pressed ); - t->set_color("font_color_hover","LinkButton", control_font_color_hover ); + t->set_color("font_color", "LinkButton", control_font_color); + t->set_color("font_color_pressed", "LinkButton", control_font_color_pressed); + t->set_color("font_color_hover", "LinkButton", control_font_color_hover); - t->set_constant("underline_spacing","LinkButton", 2 *scale); + t->set_constant("underline_spacing", "LinkButton", 2 * scale); // ColorPickerButton - t->set_stylebox("normal","ColorPickerButton", sb_button_normal); - t->set_stylebox("pressed","ColorPickerButton", sb_button_pressed); - t->set_stylebox("hover","ColorPickerButton", sb_button_hover); - t->set_stylebox("disabled","ColorPickerButton", sb_button_disabled); - t->set_stylebox("focus","ColorPickerButton", sb_button_focus); + t->set_stylebox("normal", "ColorPickerButton", sb_button_normal); + t->set_stylebox("pressed", "ColorPickerButton", sb_button_pressed); + t->set_stylebox("hover", "ColorPickerButton", sb_button_hover); + t->set_stylebox("disabled", "ColorPickerButton", sb_button_disabled); + t->set_stylebox("focus", "ColorPickerButton", sb_button_focus); - t->set_font("font","ColorPickerButton", default_font ); + t->set_font("font", "ColorPickerButton", default_font); - t->set_color("font_color","ColorPickerButton", Color(1,1,1,1) ); - t->set_color("font_color_pressed","ColorPickerButton", Color(0.8,0.8,0.8,1) ); - t->set_color("font_color_hover","ColorPickerButton", Color(1,1,1,1) ); - t->set_color("font_color_disabled","ColorPickerButton", Color(0.9,0.9,0.9,0.3) ); - - t->set_constant("hseparation","ColorPickerButton", 2 *scale); + t->set_color("font_color", "ColorPickerButton", Color(1, 1, 1, 1)); + t->set_color("font_color_pressed", "ColorPickerButton", Color(0.8, 0.8, 0.8, 1)); + t->set_color("font_color_hover", "ColorPickerButton", Color(1, 1, 1, 1)); + t->set_color("font_color_disabled", "ColorPickerButton", Color(0.9, 0.9, 0.9, 0.3)); + t->set_constant("hseparation", "ColorPickerButton", 2 * scale); // ToolButton - Ref<StyleBox> tb_empty = memnew( StyleBoxEmpty ); - tb_empty->set_default_margin(MARGIN_LEFT,6 *scale); - tb_empty->set_default_margin(MARGIN_RIGHT,6 *scale); - tb_empty->set_default_margin(MARGIN_TOP,4 *scale); - tb_empty->set_default_margin(MARGIN_BOTTOM,4 *scale); - - t->set_stylebox("normal","ToolButton", tb_empty); - t->set_stylebox("pressed","ToolButton", make_stylebox( button_pressed_png,4,4,4,4) ); - t->set_stylebox("hover","ToolButton", make_stylebox( button_normal_png,4,4,4,4) ); - t->set_stylebox("disabled","ToolButton", make_empty_stylebox(4,4,4,4) ); - t->set_stylebox("focus","ToolButton", focus ); - t->set_font("font","ToolButton", default_font ); - - t->set_color("font_color","ToolButton", control_font_color ); - t->set_color("font_color_pressed","ToolButton", control_font_color_pressed ); - t->set_color("font_color_hover","ToolButton", control_font_color_hover ); - t->set_color("font_color_disabled","ToolButton", Color(0.9,0.95,1,0.3) ); + Ref<StyleBox> tb_empty = memnew(StyleBoxEmpty); + tb_empty->set_default_margin(MARGIN_LEFT, 6 * scale); + tb_empty->set_default_margin(MARGIN_RIGHT, 6 * scale); + tb_empty->set_default_margin(MARGIN_TOP, 4 * scale); + tb_empty->set_default_margin(MARGIN_BOTTOM, 4 * scale); - t->set_constant("hseparation","ToolButton", 3 ); + t->set_stylebox("normal", "ToolButton", tb_empty); + t->set_stylebox("pressed", "ToolButton", make_stylebox(button_pressed_png, 4, 4, 4, 4)); + t->set_stylebox("hover", "ToolButton", make_stylebox(button_normal_png, 4, 4, 4, 4)); + t->set_stylebox("disabled", "ToolButton", make_empty_stylebox(4, 4, 4, 4)); + t->set_stylebox("focus", "ToolButton", focus); + t->set_font("font", "ToolButton", default_font); + t->set_color("font_color", "ToolButton", control_font_color); + t->set_color("font_color_pressed", "ToolButton", control_font_color_pressed); + t->set_color("font_color_hover", "ToolButton", control_font_color_hover); + t->set_color("font_color_disabled", "ToolButton", Color(0.9, 0.95, 1, 0.3)); + t->set_constant("hseparation", "ToolButton", 3); // OptionButton - Ref<StyleBox> sb_optbutton_normal = sb_expand( make_stylebox( option_button_normal_png,4,4,21,4,6,3,21,3),2,2,2,2); - Ref<StyleBox> sb_optbutton_pressed = sb_expand( make_stylebox( option_button_pressed_png,4,4,21,4,6,3,21,3),2,2,2,2); - Ref<StyleBox> sb_optbutton_hover = sb_expand( make_stylebox( option_button_hover_png,4,4,21,4,6,2,21,2),2,2,2,2); - Ref<StyleBox> sb_optbutton_disabled = sb_expand( make_stylebox( option_button_disabled_png,4,4,21,4,6,2,21,2),2,2,2,2); - Ref<StyleBox> sb_optbutton_focus = sb_expand( make_stylebox( button_focus_png,4,4,4,4,6,2,6,2),2,2,2,2); + Ref<StyleBox> sb_optbutton_normal = sb_expand(make_stylebox(option_button_normal_png, 4, 4, 21, 4, 6, 3, 21, 3), 2, 2, 2, 2); + Ref<StyleBox> sb_optbutton_pressed = sb_expand(make_stylebox(option_button_pressed_png, 4, 4, 21, 4, 6, 3, 21, 3), 2, 2, 2, 2); + Ref<StyleBox> sb_optbutton_hover = sb_expand(make_stylebox(option_button_hover_png, 4, 4, 21, 4, 6, 2, 21, 2), 2, 2, 2, 2); + Ref<StyleBox> sb_optbutton_disabled = sb_expand(make_stylebox(option_button_disabled_png, 4, 4, 21, 4, 6, 2, 21, 2), 2, 2, 2, 2); + Ref<StyleBox> sb_optbutton_focus = sb_expand(make_stylebox(button_focus_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2); - t->set_stylebox("normal","OptionButton", sb_optbutton_normal ); - t->set_stylebox("pressed","OptionButton", sb_optbutton_pressed ); - t->set_stylebox("hover","OptionButton", sb_optbutton_hover ); - t->set_stylebox("disabled","OptionButton", sb_optbutton_disabled ); - t->set_stylebox("focus","OptionButton", sb_button_focus ); + t->set_stylebox("normal", "OptionButton", sb_optbutton_normal); + t->set_stylebox("pressed", "OptionButton", sb_optbutton_pressed); + t->set_stylebox("hover", "OptionButton", sb_optbutton_hover); + t->set_stylebox("disabled", "OptionButton", sb_optbutton_disabled); + t->set_stylebox("focus", "OptionButton", sb_button_focus); - t->set_icon("arrow","OptionButton", make_icon( option_arrow_png ) ); + t->set_icon("arrow", "OptionButton", make_icon(option_arrow_png)); - t->set_font("font","OptionButton", default_font ); - - t->set_color("font_color","OptionButton", control_font_color ); - t->set_color("font_color_pressed","OptionButton", control_font_color_pressed ); - t->set_color("font_color_hover","OptionButton", control_font_color_hover ); - t->set_color("font_color_disabled","OptionButton", control_font_color_disabled ); - - t->set_constant("hseparation","OptionButton", 2 *scale); - t->set_constant("arrow_margin","OptionButton", 2 *scale); + t->set_font("font", "OptionButton", default_font); + t->set_color("font_color", "OptionButton", control_font_color); + t->set_color("font_color_pressed", "OptionButton", control_font_color_pressed); + t->set_color("font_color_hover", "OptionButton", control_font_color_hover); + t->set_color("font_color_disabled", "OptionButton", control_font_color_disabled); + t->set_constant("hseparation", "OptionButton", 2 * scale); + t->set_constant("arrow_margin", "OptionButton", 2 * scale); // MenuButton - t->set_stylebox("normal","MenuButton", sb_button_normal ); - t->set_stylebox("pressed","MenuButton", sb_button_pressed ); - t->set_stylebox("hover","MenuButton", sb_button_pressed ); - t->set_stylebox("disabled","MenuButton", make_empty_stylebox(0,0,0,0) ); - t->set_stylebox("focus","MenuButton", sb_button_focus ); + t->set_stylebox("normal", "MenuButton", sb_button_normal); + t->set_stylebox("pressed", "MenuButton", sb_button_pressed); + t->set_stylebox("hover", "MenuButton", sb_button_pressed); + t->set_stylebox("disabled", "MenuButton", make_empty_stylebox(0, 0, 0, 0)); + t->set_stylebox("focus", "MenuButton", sb_button_focus); - t->set_font("font","MenuButton", default_font ); + t->set_font("font", "MenuButton", default_font); - t->set_color("font_color","MenuButton", control_font_color ); - t->set_color("font_color_pressed","MenuButton", control_font_color_pressed ); - t->set_color("font_color_hover","MenuButton", control_font_color_hover ); - t->set_color("font_color_disabled","MenuButton", Color(1,1,1,0.3) ); + t->set_color("font_color", "MenuButton", control_font_color); + t->set_color("font_color_pressed", "MenuButton", control_font_color_pressed); + t->set_color("font_color_hover", "MenuButton", control_font_color_hover); + t->set_color("font_color_disabled", "MenuButton", Color(1, 1, 1, 0.3)); - t->set_constant("hseparation","MenuButton", 3 *scale); + t->set_constant("hseparation", "MenuButton", 3 * scale); // ButtonGroup - t->set_stylebox("panel","ButtonGroup", memnew( StyleBoxEmpty )); + t->set_stylebox("panel", "ButtonGroup", memnew(StyleBoxEmpty)); // CheckBox - Ref<StyleBox> cbx_empty = memnew( StyleBoxEmpty ); - cbx_empty->set_default_margin(MARGIN_LEFT,22 *scale); - cbx_empty->set_default_margin(MARGIN_RIGHT,4 *scale); - cbx_empty->set_default_margin(MARGIN_TOP,4 *scale); - cbx_empty->set_default_margin(MARGIN_BOTTOM,5 *scale); + Ref<StyleBox> cbx_empty = memnew(StyleBoxEmpty); + cbx_empty->set_default_margin(MARGIN_LEFT, 22 * scale); + cbx_empty->set_default_margin(MARGIN_RIGHT, 4 * scale); + cbx_empty->set_default_margin(MARGIN_TOP, 4 * scale); + cbx_empty->set_default_margin(MARGIN_BOTTOM, 5 * scale); Ref<StyleBox> cbx_focus = focus; - cbx_focus->set_default_margin(MARGIN_LEFT,4 *scale); - cbx_focus->set_default_margin(MARGIN_RIGHT,22 *scale); - cbx_focus->set_default_margin(MARGIN_TOP,4 *scale); - cbx_focus->set_default_margin(MARGIN_BOTTOM,5 *scale); + cbx_focus->set_default_margin(MARGIN_LEFT, 4 * scale); + cbx_focus->set_default_margin(MARGIN_RIGHT, 22 * scale); + cbx_focus->set_default_margin(MARGIN_TOP, 4 * scale); + cbx_focus->set_default_margin(MARGIN_BOTTOM, 5 * scale); - t->set_stylebox("normal","CheckBox", cbx_empty ); - t->set_stylebox("pressed","CheckBox", cbx_empty ); - t->set_stylebox("disabled","CheckBox", cbx_empty ); - t->set_stylebox("hover","CheckBox", cbx_empty ); - t->set_stylebox("focus","CheckBox", cbx_focus ); + t->set_stylebox("normal", "CheckBox", cbx_empty); + t->set_stylebox("pressed", "CheckBox", cbx_empty); + t->set_stylebox("disabled", "CheckBox", cbx_empty); + t->set_stylebox("hover", "CheckBox", cbx_empty); + t->set_stylebox("focus", "CheckBox", cbx_focus); t->set_icon("checked", "CheckBox", make_icon(checked_png)); t->set_icon("unchecked", "CheckBox", make_icon(unchecked_png)); t->set_icon("radio_checked", "CheckBox", make_icon(radio_checked_png)); t->set_icon("radio_unchecked", "CheckBox", make_icon(radio_unchecked_png)); - t->set_font("font","CheckBox", default_font ); - - t->set_color("font_color","CheckBox", control_font_color ); - t->set_color("font_color_pressed","CheckBox", control_font_color_pressed ); - t->set_color("font_color_hover","CheckBox", control_font_color_hover ); - t->set_color("font_color_disabled","CheckBox", control_font_color_disabled ); - - t->set_constant("hseparation","CheckBox",4 *scale); - t->set_constant("check_vadjust","CheckBox",0 *scale); + t->set_font("font", "CheckBox", default_font); + t->set_color("font_color", "CheckBox", control_font_color); + t->set_color("font_color_pressed", "CheckBox", control_font_color_pressed); + t->set_color("font_color_hover", "CheckBox", control_font_color_hover); + t->set_color("font_color_disabled", "CheckBox", control_font_color_disabled); + t->set_constant("hseparation", "CheckBox", 4 * scale); + t->set_constant("check_vadjust", "CheckBox", 0 * scale); // CheckButton - Ref<StyleBox> cb_empty = memnew( StyleBoxEmpty ); - cb_empty->set_default_margin(MARGIN_LEFT,6 *scale); - cb_empty->set_default_margin(MARGIN_RIGHT,70 *scale); - cb_empty->set_default_margin(MARGIN_TOP,4 *scale); - cb_empty->set_default_margin(MARGIN_BOTTOM,4 *scale); - - t->set_stylebox("normal","CheckButton", cb_empty ); - t->set_stylebox("pressed","CheckButton", cb_empty ); - t->set_stylebox("disabled","CheckButton", cb_empty ); - t->set_stylebox("hover","CheckButton", cb_empty ); - t->set_stylebox("focus","CheckButton", focus ); + Ref<StyleBox> cb_empty = memnew(StyleBoxEmpty); + cb_empty->set_default_margin(MARGIN_LEFT, 6 * scale); + cb_empty->set_default_margin(MARGIN_RIGHT, 70 * scale); + cb_empty->set_default_margin(MARGIN_TOP, 4 * scale); + cb_empty->set_default_margin(MARGIN_BOTTOM, 4 * scale); - t->set_icon("on","CheckButton", make_icon(toggle_on_png) ); - t->set_icon("off","CheckButton", make_icon(toggle_off_png)); + t->set_stylebox("normal", "CheckButton", cb_empty); + t->set_stylebox("pressed", "CheckButton", cb_empty); + t->set_stylebox("disabled", "CheckButton", cb_empty); + t->set_stylebox("hover", "CheckButton", cb_empty); + t->set_stylebox("focus", "CheckButton", focus); - t->set_font("font","CheckButton", default_font ); + t->set_icon("on", "CheckButton", make_icon(toggle_on_png)); + t->set_icon("off", "CheckButton", make_icon(toggle_off_png)); - t->set_color("font_color","CheckButton", control_font_color ); - t->set_color("font_color_pressed","CheckButton", control_font_color_pressed ); - t->set_color("font_color_hover","CheckButton", control_font_color_hover ); - t->set_color("font_color_disabled","CheckButton", control_font_color_disabled ); - - t->set_constant("hseparation","CheckButton",4 *scale); - t->set_constant("check_vadjust","CheckButton",0 *scale); + t->set_font("font", "CheckButton", default_font); + t->set_color("font_color", "CheckButton", control_font_color); + t->set_color("font_color_pressed", "CheckButton", control_font_color_pressed); + t->set_color("font_color_hover", "CheckButton", control_font_color_hover); + t->set_color("font_color_disabled", "CheckButton", control_font_color_disabled); + t->set_constant("hseparation", "CheckButton", 4 * scale); + t->set_constant("check_vadjust", "CheckButton", 0 * scale); // Label - t->set_font("font","Label", default_font ); - - t->set_color("font_color","Label", Color(1,1,1) ); - t->set_color("font_color_shadow","Label", Color(0,0,0,0) ); - - t->set_constant("shadow_offset_x","Label", 1 *scale); - t->set_constant("shadow_offset_y","Label", 1 *scale); - t->set_constant("shadow_as_outline","Label", 0 *scale); - t->set_constant("line_spacing","Label", 3 *scale); + t->set_font("font", "Label", default_font); + t->set_color("font_color", "Label", Color(1, 1, 1)); + t->set_color("font_color_shadow", "Label", Color(0, 0, 0, 0)); + t->set_constant("shadow_offset_x", "Label", 1 * scale); + t->set_constant("shadow_offset_y", "Label", 1 * scale); + t->set_constant("shadow_as_outline", "Label", 0 * scale); + t->set_constant("line_spacing", "Label", 3 * scale); // LineEdit - t->set_stylebox("normal","LineEdit", make_stylebox( line_edit_png,5,5,5,5) ); - t->set_stylebox("focus","LineEdit", focus ); - t->set_stylebox("read_only","LineEdit", make_stylebox( line_edit_disabled_png,6,6,6,6) ); + t->set_stylebox("normal", "LineEdit", make_stylebox(line_edit_png, 5, 5, 5, 5)); + t->set_stylebox("focus", "LineEdit", focus); + t->set_stylebox("read_only", "LineEdit", make_stylebox(line_edit_disabled_png, 6, 6, 6, 6)); - t->set_font("font","LineEdit", default_font ); - - t->set_color("font_color","LineEdit", control_font_color ); - t->set_color("font_color_selected","LineEdit", Color(0,0,0) ); - t->set_color("cursor_color","LineEdit", control_font_color_hover ); - t->set_color("selection_color","LineEdit", font_color_selection ); - - t->set_constant("minimum_spaces","LineEdit", 12 *scale); + t->set_font("font", "LineEdit", default_font); + t->set_color("font_color", "LineEdit", control_font_color); + t->set_color("font_color_selected", "LineEdit", Color(0, 0, 0)); + t->set_color("cursor_color", "LineEdit", control_font_color_hover); + t->set_color("selection_color", "LineEdit", font_color_selection); + t->set_constant("minimum_spaces", "LineEdit", 12 * scale); // ProgressBar - t->set_stylebox("bg","ProgressBar", make_stylebox( progress_bar_png,4,4,4,4,0,0,0,0) ); - t->set_stylebox("fg","ProgressBar", make_stylebox( progress_fill_png,6,6,6,6,2,1,2,1) ); - - t->set_font("font","ProgressBar", default_font ); - - t->set_color("font_color","ProgressBar", control_font_color_hover ); - t->set_color("font_color_shadow","ProgressBar", Color(0,0,0) ); + t->set_stylebox("bg", "ProgressBar", make_stylebox(progress_bar_png, 4, 4, 4, 4, 0, 0, 0, 0)); + t->set_stylebox("fg", "ProgressBar", make_stylebox(progress_fill_png, 6, 6, 6, 6, 2, 1, 2, 1)); + t->set_font("font", "ProgressBar", default_font); + t->set_color("font_color", "ProgressBar", control_font_color_hover); + t->set_color("font_color_shadow", "ProgressBar", Color(0, 0, 0)); // TextEdit - t->set_stylebox("normal","TextEdit", make_stylebox( tree_bg_png,3,3,3,3) ); - t->set_stylebox("focus","TextEdit", focus ); - t->set_stylebox("completion","TextEdit", make_stylebox( tree_bg_png,3,3,3,3) ); - - t->set_icon("tab","TextEdit", make_icon( tab_png) ); - - t->set_font("font","TextEdit", default_font ); - - t->set_color("background_color", "TextEdit", Color(0,0,0,0)); - t->set_color("completion_background_color", "TextEdit",Color::html("2C2A32")); - t->set_color("completion_selected_color", "TextEdit",Color::html("434244")); - t->set_color("completion_existing_color", "TextEdit",Color::html("21dfdfdf")); - t->set_color("completion_scroll_color","TextEdit", control_font_color_pressed ); - t->set_color("completion_font_color","TextEdit", Color::html("aaaaaa")); - t->set_color("font_color","TextEdit", control_font_color ); - t->set_color("font_color_selected","TextEdit", Color(0,0,0) ); - t->set_color("selection_color","TextEdit", font_color_selection ); - t->set_color("mark_color","TextEdit", Color(1.0,0.4,0.4,0.4) ); - t->set_color("breakpoint_color","TextEdit", Color(0.8,0.8,0.4,0.2) ); - t->set_color("current_line_color","TextEdit", Color(0.25,0.25,0.26,0.8) ); - t->set_color("caret_color","TextEdit", control_font_color ); + t->set_stylebox("normal", "TextEdit", make_stylebox(tree_bg_png, 3, 3, 3, 3)); + t->set_stylebox("focus", "TextEdit", focus); + t->set_stylebox("completion", "TextEdit", make_stylebox(tree_bg_png, 3, 3, 3, 3)); + + t->set_icon("tab", "TextEdit", make_icon(tab_png)); + + t->set_font("font", "TextEdit", default_font); + + t->set_color("background_color", "TextEdit", Color(0, 0, 0, 0)); + t->set_color("completion_background_color", "TextEdit", Color::html("2C2A32")); + t->set_color("completion_selected_color", "TextEdit", Color::html("434244")); + t->set_color("completion_existing_color", "TextEdit", Color::html("21dfdfdf")); + t->set_color("completion_scroll_color", "TextEdit", control_font_color_pressed); + t->set_color("completion_font_color", "TextEdit", Color::html("aaaaaa")); + t->set_color("font_color", "TextEdit", control_font_color); + t->set_color("font_color_selected", "TextEdit", Color(0, 0, 0)); + t->set_color("selection_color", "TextEdit", font_color_selection); + t->set_color("mark_color", "TextEdit", Color(1.0, 0.4, 0.4, 0.4)); + t->set_color("breakpoint_color", "TextEdit", Color(0.8, 0.8, 0.4, 0.2)); + t->set_color("current_line_color", "TextEdit", Color(0.25, 0.25, 0.26, 0.8)); + t->set_color("caret_color", "TextEdit", control_font_color); t->set_color("caret_background_color", "TextEdit", Color::html("000000")); - t->set_color("symbol_color","TextEdit", control_font_color_hover ); - t->set_color("brace_mismatch_color","TextEdit", Color(1,0.2,0.2) ); - t->set_color("line_number_color","TextEdit",Color::html("66aaaaaa")); - t->set_color("function_color","TextEdit",Color::html("66a2ce")); - t->set_color("member_variable_color","TextEdit",Color::html("e64e59")); - t->set_color("number_color","TextEdit",Color::html("EB9532")); - t->set_color("word_highlighted_color","TextEdit",Color(0.8,0.9,0.9,0.15)); - - t->set_constant("completion_lines","TextEdit", 7 ); - t->set_constant("completion_max_width","TextEdit", 50 ); - t->set_constant("completion_scroll_width","TextEdit", 3 ); - t->set_constant("line_spacing","TextEdit",4 *scale); + t->set_color("symbol_color", "TextEdit", control_font_color_hover); + t->set_color("brace_mismatch_color", "TextEdit", Color(1, 0.2, 0.2)); + t->set_color("line_number_color", "TextEdit", Color::html("66aaaaaa")); + t->set_color("function_color", "TextEdit", Color::html("66a2ce")); + t->set_color("member_variable_color", "TextEdit", Color::html("e64e59")); + t->set_color("number_color", "TextEdit", Color::html("EB9532")); + t->set_color("word_highlighted_color", "TextEdit", Color(0.8, 0.9, 0.9, 0.15)); + t->set_constant("completion_lines", "TextEdit", 7); + t->set_constant("completion_max_width", "TextEdit", 50); + t->set_constant("completion_scroll_width", "TextEdit", 3); + t->set_constant("line_spacing", "TextEdit", 4 * scale); - Ref<Texture> empty_icon = memnew( ImageTexture ); + Ref<Texture> empty_icon = memnew(ImageTexture); // HScrollBar - t->set_stylebox("scroll","HScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) ); - t->set_stylebox("scroll_focus","HScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) ); - t->set_stylebox("grabber","HScrollBar", make_stylebox( scroll_grabber_png,5,5,5,5,2,2,2,2) ); - t->set_stylebox("grabber_hilite","HScrollBar", make_stylebox( scroll_grabber_hl_png,5,5,5,5,2,2,2,2) ); - - t->set_icon("increment","HScrollBar",empty_icon); - t->set_icon("increment_hilite","HScrollBar",empty_icon); - t->set_icon("decrement","HScrollBar",empty_icon); - t->set_icon("decrement_hilite","HScrollBar",empty_icon); - + t->set_stylebox("scroll", "HScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0)); + t->set_stylebox("scroll_focus", "HScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0)); + t->set_stylebox("grabber", "HScrollBar", make_stylebox(scroll_grabber_png, 5, 5, 5, 5, 2, 2, 2, 2)); + t->set_stylebox("grabber_hilite", "HScrollBar", make_stylebox(scroll_grabber_hl_png, 5, 5, 5, 5, 2, 2, 2, 2)); + t->set_icon("increment", "HScrollBar", empty_icon); + t->set_icon("increment_hilite", "HScrollBar", empty_icon); + t->set_icon("decrement", "HScrollBar", empty_icon); + t->set_icon("decrement_hilite", "HScrollBar", empty_icon); // VScrollBar - t->set_stylebox("scroll","VScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) ); - t->set_stylebox("scroll_focus","VScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) ); - t->set_stylebox("grabber","VScrollBar", make_stylebox( scroll_grabber_png,5,5,5,5,2,2,2,2) ); - t->set_stylebox("grabber_hilite","VScrollBar", make_stylebox( scroll_grabber_hl_png,5,5,5,5,2,2,2,2) ); - - t->set_icon("increment","VScrollBar",empty_icon); - t->set_icon("increment_hilite","VScrollBar",empty_icon); - t->set_icon("decrement","VScrollBar",empty_icon); - t->set_icon("decrement_hilite","VScrollBar",empty_icon); - + t->set_stylebox("scroll", "VScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0)); + t->set_stylebox("scroll_focus", "VScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0)); + t->set_stylebox("grabber", "VScrollBar", make_stylebox(scroll_grabber_png, 5, 5, 5, 5, 2, 2, 2, 2)); + t->set_stylebox("grabber_hilite", "VScrollBar", make_stylebox(scroll_grabber_hl_png, 5, 5, 5, 5, 2, 2, 2, 2)); + t->set_icon("increment", "VScrollBar", empty_icon); + t->set_icon("increment_hilite", "VScrollBar", empty_icon); + t->set_icon("decrement", "VScrollBar", empty_icon); + t->set_icon("decrement_hilite", "VScrollBar", empty_icon); // HSlider - t->set_stylebox("slider","HSlider", make_stylebox( hslider_bg_png,4,4,4,4) ); - t->set_stylebox("grabber_hilite","HSlider", make_stylebox( hslider_grabber_hl_png,6,6,6,6) ); - t->set_stylebox("focus","HSlider", focus ); - - t->set_icon("grabber","HSlider", make_icon( hslider_grabber_png ) ); - t->set_icon("grabber_hilite","HSlider", make_icon( hslider_grabber_hl_png ) ); - t->set_icon("tick","HSlider", make_icon( hslider_tick_png ) ); - - + t->set_stylebox("slider", "HSlider", make_stylebox(hslider_bg_png, 4, 4, 4, 4)); + t->set_stylebox("grabber_hilite", "HSlider", make_stylebox(hslider_grabber_hl_png, 6, 6, 6, 6)); + t->set_stylebox("focus", "HSlider", focus); + t->set_icon("grabber", "HSlider", make_icon(hslider_grabber_png)); + t->set_icon("grabber_hilite", "HSlider", make_icon(hslider_grabber_hl_png)); + t->set_icon("tick", "HSlider", make_icon(hslider_tick_png)); // VSlider - t->set_stylebox("slider","VSlider", make_stylebox( vslider_bg_png,4,4,4,4) ); - t->set_stylebox("grabber_hilite","VSlider", make_stylebox( vslider_grabber_hl_png,6,6,6,6) ); - t->set_stylebox("focus","HSlider", focus ); - - t->set_icon("grabber","VSlider", make_icon( vslider_grabber_png) ); - t->set_icon("grabber_hilite","VSlider", make_icon( vslider_grabber_hl_png ) ); - t->set_icon("tick","VSlider", make_icon( vslider_tick_png ) ); - + t->set_stylebox("slider", "VSlider", make_stylebox(vslider_bg_png, 4, 4, 4, 4)); + t->set_stylebox("grabber_hilite", "VSlider", make_stylebox(vslider_grabber_hl_png, 6, 6, 6, 6)); + t->set_stylebox("focus", "HSlider", focus); + t->set_icon("grabber", "VSlider", make_icon(vslider_grabber_png)); + t->set_icon("grabber_hilite", "VSlider", make_icon(vslider_grabber_hl_png)); + t->set_icon("tick", "VSlider", make_icon(vslider_tick_png)); // SpinBox - t->set_icon("updown","SpinBox",make_icon(spinbox_updown_png)); - - + t->set_icon("updown", "SpinBox", make_icon(spinbox_updown_png)); // WindowDialog @@ -597,381 +551,349 @@ void fill_default_theme(Ref<Theme>& t, const Ref<Font> & default_font, const Ref t->set_constant("close_h_ofs", "WindowDialog", 18 * scale); t->set_constant("close_v_ofs", "WindowDialog", 18 * scale); - // File Dialog - t->set_icon("reload","FileDialog",make_icon( icon_reload_png )); - + t->set_icon("reload", "FileDialog", make_icon(icon_reload_png)); // Popup - Ref<StyleBoxTexture> style_pp = sb_expand( make_stylebox( popup_bg_png,5,5,5,5,4,4,4,4),2,2,2,2); + Ref<StyleBoxTexture> style_pp = sb_expand(make_stylebox(popup_bg_png, 5, 5, 5, 5, 4, 4, 4, 4), 2, 2, 2, 2); - Ref<StyleBoxTexture> selected = make_stylebox( selection_png,6,6,6,6); - for(int i=0;i<4;i++) { - selected->set_expand_margin_size(Margin(i),2 *scale); + Ref<StyleBoxTexture> selected = make_stylebox(selection_png, 6, 6, 6, 6); + for (int i = 0; i < 4; i++) { + selected->set_expand_margin_size(Margin(i), 2 * scale); } - t->set_stylebox("panel","PopupPanel", style_pp ); - - - + t->set_stylebox("panel", "PopupPanel", style_pp); // PopupMenu - t->set_stylebox("panel","PopupMenu", make_stylebox( popup_bg_png,4,4,4,4,10,10,10,10) ); - t->set_stylebox("panel_disabled","PopupMenu", make_stylebox( popup_bg_disabled_png,4,4,4,4) ); - t->set_stylebox("hover","PopupMenu", selected ); - t->set_stylebox("separator","PopupMenu", make_stylebox( vseparator_png,3,3,3,3) ); - - t->set_icon("checked","PopupMenu", make_icon(checked_png) ); - t->set_icon("unchecked","PopupMenu", make_icon(unchecked_png) ); - t->set_icon("submenu","PopupMenu", make_icon(submenu_png) ); + t->set_stylebox("panel", "PopupMenu", make_stylebox(popup_bg_png, 4, 4, 4, 4, 10, 10, 10, 10)); + t->set_stylebox("panel_disabled", "PopupMenu", make_stylebox(popup_bg_disabled_png, 4, 4, 4, 4)); + t->set_stylebox("hover", "PopupMenu", selected); + t->set_stylebox("separator", "PopupMenu", make_stylebox(vseparator_png, 3, 3, 3, 3)); - t->set_font("font","PopupMenu", default_font ); + t->set_icon("checked", "PopupMenu", make_icon(checked_png)); + t->set_icon("unchecked", "PopupMenu", make_icon(unchecked_png)); + t->set_icon("submenu", "PopupMenu", make_icon(submenu_png)); - t->set_color("font_color","PopupMenu", control_font_color ); - t->set_color("font_color_accel","PopupMenu", Color(0.7,0.7,0.7,0.8) ); - t->set_color("font_color_disabled","PopupMenu", Color(0.4,0.4,0.4,0.8) ); - t->set_color("font_color_hover","PopupMenu", control_font_color ); + t->set_font("font", "PopupMenu", default_font); - t->set_constant("hseparation","PopupMenu",4 *scale); - t->set_constant("vseparation","PopupMenu",4 *scale); + t->set_color("font_color", "PopupMenu", control_font_color); + t->set_color("font_color_accel", "PopupMenu", Color(0.7, 0.7, 0.7, 0.8)); + t->set_color("font_color_disabled", "PopupMenu", Color(0.4, 0.4, 0.4, 0.8)); + t->set_color("font_color_hover", "PopupMenu", control_font_color); + t->set_constant("hseparation", "PopupMenu", 4 * scale); + t->set_constant("vseparation", "PopupMenu", 4 * scale); // GraphNode - Ref<StyleBoxTexture> graphsb = make_stylebox(graph_node_png,6,24,6,5,16,24,16,5); - Ref<StyleBoxTexture> graphsbcomment = make_stylebox(graph_node_comment_png,6,24,6,5,16,24,16,5); - Ref<StyleBoxTexture> graphsbcommentselected = make_stylebox(graph_node_comment_focus_png,6,24,6,5,16,24,16,5); - Ref<StyleBoxTexture> graphsbselected = make_stylebox(graph_node_selected_png,6,24,6,5,16,24,16,5); - Ref<StyleBoxTexture> graphsbdefault = make_stylebox(graph_node_default_png,4,4,4,4,6,4,4,4); - Ref<StyleBoxTexture> graphsbdeffocus = make_stylebox(graph_node_default_focus_png,4,4,4,4,6,4,4,4); - Ref<StyleBoxTexture> graph_bpoint = make_stylebox(graph_node_breakpoint_png,6,24,6,5,16,24,16,5); - Ref<StyleBoxTexture> graph_position = make_stylebox(graph_node_position_png,6,24,6,5,16,24,16,5); + Ref<StyleBoxTexture> graphsb = make_stylebox(graph_node_png, 6, 24, 6, 5, 16, 24, 16, 5); + Ref<StyleBoxTexture> graphsbcomment = make_stylebox(graph_node_comment_png, 6, 24, 6, 5, 16, 24, 16, 5); + Ref<StyleBoxTexture> graphsbcommentselected = make_stylebox(graph_node_comment_focus_png, 6, 24, 6, 5, 16, 24, 16, 5); + Ref<StyleBoxTexture> graphsbselected = make_stylebox(graph_node_selected_png, 6, 24, 6, 5, 16, 24, 16, 5); + Ref<StyleBoxTexture> graphsbdefault = make_stylebox(graph_node_default_png, 4, 4, 4, 4, 6, 4, 4, 4); + Ref<StyleBoxTexture> graphsbdeffocus = make_stylebox(graph_node_default_focus_png, 4, 4, 4, 4, 6, 4, 4, 4); + Ref<StyleBoxTexture> graph_bpoint = make_stylebox(graph_node_breakpoint_png, 6, 24, 6, 5, 16, 24, 16, 5); + Ref<StyleBoxTexture> graph_position = make_stylebox(graph_node_position_png, 6, 24, 6, 5, 16, 24, 16, 5); //graphsb->set_expand_margin_size(MARGIN_LEFT,10); //graphsb->set_expand_margin_size(MARGIN_RIGHT,10); - t->set_stylebox("frame","GraphNode", graphsb ); - t->set_stylebox("selectedframe","GraphNode", graphsbselected ); - t->set_stylebox("defaultframe", "GraphNode", graphsbdefault ); - t->set_stylebox("defaultfocus", "GraphNode", graphsbdeffocus ); - t->set_stylebox("comment", "GraphNode", graphsbcomment ); - t->set_stylebox("commentfocus", "GraphNode", graphsbcommentselected ); - t->set_stylebox("breakpoint", "GraphNode", graph_bpoint ); - t->set_stylebox("position", "GraphNode", graph_position ); - t->set_constant("separation","GraphNode", 1 *scale); - t->set_icon("port","GraphNode", make_icon( graph_port_png ) ); - t->set_icon("close","GraphNode", make_icon( graph_node_close_png ) ); - t->set_icon("resizer","GraphNode", make_icon( window_resizer_png ) ); - t->set_font("title_font","GraphNode", default_font ); - t->set_color("title_color","GraphNode", Color(0,0,0,1)); - t->set_constant("title_offset","GraphNode", 20 *scale); - t->set_constant("close_offset","GraphNode", 18 *scale); - t->set_constant("port_offset","GraphNode", 3 *scale); - + t->set_stylebox("frame", "GraphNode", graphsb); + t->set_stylebox("selectedframe", "GraphNode", graphsbselected); + t->set_stylebox("defaultframe", "GraphNode", graphsbdefault); + t->set_stylebox("defaultfocus", "GraphNode", graphsbdeffocus); + t->set_stylebox("comment", "GraphNode", graphsbcomment); + t->set_stylebox("commentfocus", "GraphNode", graphsbcommentselected); + t->set_stylebox("breakpoint", "GraphNode", graph_bpoint); + t->set_stylebox("position", "GraphNode", graph_position); + t->set_constant("separation", "GraphNode", 1 * scale); + t->set_icon("port", "GraphNode", make_icon(graph_port_png)); + t->set_icon("close", "GraphNode", make_icon(graph_node_close_png)); + t->set_icon("resizer", "GraphNode", make_icon(window_resizer_png)); + t->set_font("title_font", "GraphNode", default_font); + t->set_color("title_color", "GraphNode", Color(0, 0, 0, 1)); + t->set_constant("title_offset", "GraphNode", 20 * scale); + t->set_constant("close_offset", "GraphNode", 18 * scale); + t->set_constant("port_offset", "GraphNode", 3 * scale); // Tree - Ref<StyleBoxTexture> tree_selected = make_stylebox( selection_png,4,4,4,4,8,0,8,0); - Ref<StyleBoxTexture> tree_selected_oof = make_stylebox( selection_oof_png,4,4,4,4,8,0,8,0); - - t->set_stylebox("bg","Tree", make_stylebox( tree_bg_png,4,4,4,5) ); - t->set_stylebox("bg_focus","Tree", focus ); - t->set_stylebox("selected","Tree", tree_selected_oof ); - t->set_stylebox("selected_focus","Tree", tree_selected ); - t->set_stylebox("cursor","Tree", focus ); - t->set_stylebox("cursor_unfocused","Tree", focus ); - t->set_stylebox("button_pressed","Tree",make_stylebox( button_pressed_png,4,4,4,4)); - t->set_stylebox("title_button_normal","Tree", make_stylebox( tree_title_png,4,4,4,4) ); - t->set_stylebox("title_button_pressed","Tree", make_stylebox( tree_title_pressed_png,4,4,4,4) ); - t->set_stylebox("title_button_hover","Tree", make_stylebox( tree_title_png,4,4,4,4) ); - - t->set_icon("checked","Tree",make_icon(checked_png)); - t->set_icon("unchecked","Tree",make_icon(unchecked_png)); - t->set_icon("updown","Tree",make_icon(updown_png)); - t->set_icon("select_arrow","Tree",make_icon(dropdown_png)); - t->set_icon("arrow","Tree",make_icon(arrow_down_png)); - t->set_icon("arrow_collapsed","Tree",make_icon(arrow_right_png)); - - t->set_font("title_button_font","Tree", default_font ); - t->set_font("font","Tree", default_font ); - - t->set_color("title_button_color","Tree", control_font_color ); - t->set_color("font_color","Tree", control_font_color_low ); - t->set_color("font_color_selected","Tree", control_font_color_pressed ); - t->set_color("selection_color","Tree", Color(0.1,0.1,1,0.8) ); - t->set_color("cursor_color","Tree", Color(0,0,0) ); - t->set_color("guide_color","Tree", Color(0,0,0,0.1) ); - t->set_color("drop_position_color","Tree", Color(1,0.3,0.2) ); - t->set_color("relationship_line_color", "Tree", Color::html("464646") ); - - t->set_constant("hseparation","Tree",4 *scale); - t->set_constant("vseparation","Tree",4 *scale); - t->set_constant("guide_width","Tree",2 *scale); - t->set_constant("item_margin","Tree",12 *scale); - t->set_constant("button_margin","Tree",4 *scale); + Ref<StyleBoxTexture> tree_selected = make_stylebox(selection_png, 4, 4, 4, 4, 8, 0, 8, 0); + Ref<StyleBoxTexture> tree_selected_oof = make_stylebox(selection_oof_png, 4, 4, 4, 4, 8, 0, 8, 0); + + t->set_stylebox("bg", "Tree", make_stylebox(tree_bg_png, 4, 4, 4, 5)); + t->set_stylebox("bg_focus", "Tree", focus); + t->set_stylebox("selected", "Tree", tree_selected_oof); + t->set_stylebox("selected_focus", "Tree", tree_selected); + t->set_stylebox("cursor", "Tree", focus); + t->set_stylebox("cursor_unfocused", "Tree", focus); + t->set_stylebox("button_pressed", "Tree", make_stylebox(button_pressed_png, 4, 4, 4, 4)); + t->set_stylebox("title_button_normal", "Tree", make_stylebox(tree_title_png, 4, 4, 4, 4)); + t->set_stylebox("title_button_pressed", "Tree", make_stylebox(tree_title_pressed_png, 4, 4, 4, 4)); + t->set_stylebox("title_button_hover", "Tree", make_stylebox(tree_title_png, 4, 4, 4, 4)); + + t->set_icon("checked", "Tree", make_icon(checked_png)); + t->set_icon("unchecked", "Tree", make_icon(unchecked_png)); + t->set_icon("updown", "Tree", make_icon(updown_png)); + t->set_icon("select_arrow", "Tree", make_icon(dropdown_png)); + t->set_icon("arrow", "Tree", make_icon(arrow_down_png)); + t->set_icon("arrow_collapsed", "Tree", make_icon(arrow_right_png)); + + t->set_font("title_button_font", "Tree", default_font); + t->set_font("font", "Tree", default_font); + + t->set_color("title_button_color", "Tree", control_font_color); + t->set_color("font_color", "Tree", control_font_color_low); + t->set_color("font_color_selected", "Tree", control_font_color_pressed); + t->set_color("selection_color", "Tree", Color(0.1, 0.1, 1, 0.8)); + t->set_color("cursor_color", "Tree", Color(0, 0, 0)); + t->set_color("guide_color", "Tree", Color(0, 0, 0, 0.1)); + t->set_color("drop_position_color", "Tree", Color(1, 0.3, 0.2)); + t->set_color("relationship_line_color", "Tree", Color::html("464646")); + + t->set_constant("hseparation", "Tree", 4 * scale); + t->set_constant("vseparation", "Tree", 4 * scale); + t->set_constant("guide_width", "Tree", 2 * scale); + t->set_constant("item_margin", "Tree", 12 * scale); + t->set_constant("button_margin", "Tree", 4 * scale); t->set_constant("draw_relationship_lines", "Tree", 0); t->set_constant("scroll_border", "Tree", 4); t->set_constant("scroll_speed", "Tree", 12); - // ItemList - Ref<StyleBoxTexture> item_selected = make_stylebox( selection_png,4,4,4,4,8,2,8,2); - Ref<StyleBoxTexture> item_selected_oof = make_stylebox( selection_oof_png,4,4,4,4,8,2,8,2); - - t->set_stylebox("bg","ItemList", make_stylebox( tree_bg_png,4,4,4,5) ); - t->set_stylebox("bg_focus","ItemList", focus ); - t->set_constant("hseparation","ItemList",4); - t->set_constant("vseparation","ItemList",2); - t->set_constant("icon_margin","ItemList",4); - t->set_constant("line_separation","ItemList",2 *scale); - t->set_font("font","ItemList", default_font ); - t->set_color("font_color","ItemList", control_font_color_lower ); - t->set_color("font_color_selected","ItemList", control_font_color_pressed ); - t->set_color("guide_color","ItemList", Color(0,0,0,0.1) ); - t->set_stylebox("selected","ItemList", item_selected_oof ); - t->set_stylebox("selected_focus","ItemList", item_selected ); - t->set_stylebox("cursor","ItemList", focus ); - t->set_stylebox("cursor_unfocused","ItemList", focus ); - + Ref<StyleBoxTexture> item_selected = make_stylebox(selection_png, 4, 4, 4, 4, 8, 2, 8, 2); + Ref<StyleBoxTexture> item_selected_oof = make_stylebox(selection_oof_png, 4, 4, 4, 4, 8, 2, 8, 2); + + t->set_stylebox("bg", "ItemList", make_stylebox(tree_bg_png, 4, 4, 4, 5)); + t->set_stylebox("bg_focus", "ItemList", focus); + t->set_constant("hseparation", "ItemList", 4); + t->set_constant("vseparation", "ItemList", 2); + t->set_constant("icon_margin", "ItemList", 4); + t->set_constant("line_separation", "ItemList", 2 * scale); + t->set_font("font", "ItemList", default_font); + t->set_color("font_color", "ItemList", control_font_color_lower); + t->set_color("font_color_selected", "ItemList", control_font_color_pressed); + t->set_color("guide_color", "ItemList", Color(0, 0, 0, 0.1)); + t->set_stylebox("selected", "ItemList", item_selected_oof); + t->set_stylebox("selected_focus", "ItemList", item_selected); + t->set_stylebox("cursor", "ItemList", focus); + t->set_stylebox("cursor_unfocused", "ItemList", focus); // TabContainer - Ref<StyleBoxTexture> tc_sb = sb_expand( make_stylebox( tab_container_bg_png,4,4,4,4,4,4,4,4),3,3,3,3); + Ref<StyleBoxTexture> tc_sb = sb_expand(make_stylebox(tab_container_bg_png, 4, 4, 4, 4, 4, 4, 4, 4), 3, 3, 3, 3); - tc_sb->set_expand_margin_size(MARGIN_TOP,2 *scale); - tc_sb->set_default_margin(MARGIN_TOP,8 *scale); + tc_sb->set_expand_margin_size(MARGIN_TOP, 2 * scale); + tc_sb->set_default_margin(MARGIN_TOP, 8 * scale); - t->set_stylebox("tab_fg","TabContainer", sb_expand( make_stylebox( tab_current_png,4,4,4,1,16,4,16,4),2,2,2,2) ); - t->set_stylebox("tab_bg","TabContainer", sb_expand( make_stylebox( tab_behind_png,5,5,5,1,16,6,16,4),3,0,3,3) ); + t->set_stylebox("tab_fg", "TabContainer", sb_expand(make_stylebox(tab_current_png, 4, 4, 4, 1, 16, 4, 16, 4), 2, 2, 2, 2)); + t->set_stylebox("tab_bg", "TabContainer", sb_expand(make_stylebox(tab_behind_png, 5, 5, 5, 1, 16, 6, 16, 4), 3, 0, 3, 3)); t->set_stylebox("tab_disabled", "TabContainer", sb_expand(make_stylebox(tab_disabled_png, 5, 5, 5, 1, 16, 6, 16, 4), 3, 0, 3, 3)); - t->set_stylebox("panel","TabContainer", tc_sb ); + t->set_stylebox("panel", "TabContainer", tc_sb); - t->set_icon("increment","TabContainer",make_icon( scroll_button_right_png)); - t->set_icon("increment_hilite","TabContainer",make_icon( scroll_button_right_hl_png)); - t->set_icon("decrement","TabContainer",make_icon( scroll_button_left_png)); - t->set_icon("decrement_hilite","TabContainer",make_icon( scroll_button_left_hl_png)); - t->set_icon("menu","TabContainer",make_icon( tab_menu_png)); - t->set_icon("menu_hilite","TabContainer",make_icon( tab_menu_hl_png)); + t->set_icon("increment", "TabContainer", make_icon(scroll_button_right_png)); + t->set_icon("increment_hilite", "TabContainer", make_icon(scroll_button_right_hl_png)); + t->set_icon("decrement", "TabContainer", make_icon(scroll_button_left_png)); + t->set_icon("decrement_hilite", "TabContainer", make_icon(scroll_button_left_hl_png)); + t->set_icon("menu", "TabContainer", make_icon(tab_menu_png)); + t->set_icon("menu_hilite", "TabContainer", make_icon(tab_menu_hl_png)); - t->set_font("font","TabContainer", default_font ); + t->set_font("font", "TabContainer", default_font); - t->set_color("font_color_fg","TabContainer", control_font_color_hover ); - t->set_color("font_color_bg","TabContainer", control_font_color_low ); + t->set_color("font_color_fg", "TabContainer", control_font_color_hover); + t->set_color("font_color_bg", "TabContainer", control_font_color_low); t->set_color("font_color_disabled", "TabContainer", control_font_color_disabled); - t->set_constant("side_margin","TabContainer", 8 *scale); - t->set_constant("top_margin","TabContainer", 24 *scale); - t->set_constant("label_valign_fg","TabContainer", 0 *scale); - t->set_constant("label_valign_bg","TabContainer", 2 *scale); - t->set_constant("hseparation","TabContainer", 4 *scale); - - + t->set_constant("side_margin", "TabContainer", 8 * scale); + t->set_constant("top_margin", "TabContainer", 24 * scale); + t->set_constant("label_valign_fg", "TabContainer", 0 * scale); + t->set_constant("label_valign_bg", "TabContainer", 2 * scale); + t->set_constant("hseparation", "TabContainer", 4 * scale); // Tabs - t->set_stylebox("tab_fg","Tabs", sb_expand( make_stylebox( tab_current_png,4,3,4,1,16,3,16,2),2,2,2,2) ); - t->set_stylebox("tab_bg","Tabs", sb_expand( make_stylebox( tab_behind_png,5,4,5,1,16,5,16,2),3,3,3,3) ); + t->set_stylebox("tab_fg", "Tabs", sb_expand(make_stylebox(tab_current_png, 4, 3, 4, 1, 16, 3, 16, 2), 2, 2, 2, 2)); + t->set_stylebox("tab_bg", "Tabs", sb_expand(make_stylebox(tab_behind_png, 5, 4, 5, 1, 16, 5, 16, 2), 3, 3, 3, 3)); t->set_stylebox("tab_disabled", "Tabs", sb_expand(make_stylebox(tab_disabled_png, 5, 4, 5, 1, 16, 5, 16, 2), 3, 3, 3, 3)); - t->set_stylebox("panel","Tabs",tc_sb ); - t->set_stylebox("button_pressed","Tabs", make_stylebox( button_pressed_png,4,4,4,4) ); - t->set_stylebox("button","Tabs", make_stylebox( button_normal_png,4,4,4,4) ); + t->set_stylebox("panel", "Tabs", tc_sb); + t->set_stylebox("button_pressed", "Tabs", make_stylebox(button_pressed_png, 4, 4, 4, 4)); + t->set_stylebox("button", "Tabs", make_stylebox(button_normal_png, 4, 4, 4, 4)); - t->set_icon("increment","Tabs",make_icon( scroll_button_right_png)); - t->set_icon("increment_hilite","Tabs",make_icon( scroll_button_right_hl_png)); - t->set_icon("decrement","Tabs",make_icon( scroll_button_left_png)); - t->set_icon("decrement_hilite","Tabs",make_icon( scroll_button_left_hl_png)); - t->set_icon("close","Tabs",make_icon( tab_close_png)); + t->set_icon("increment", "Tabs", make_icon(scroll_button_right_png)); + t->set_icon("increment_hilite", "Tabs", make_icon(scroll_button_right_hl_png)); + t->set_icon("decrement", "Tabs", make_icon(scroll_button_left_png)); + t->set_icon("decrement_hilite", "Tabs", make_icon(scroll_button_left_hl_png)); + t->set_icon("close", "Tabs", make_icon(tab_close_png)); - t->set_font("font","Tabs", default_font ); + t->set_font("font", "Tabs", default_font); - t->set_color("font_color_fg","Tabs", control_font_color_hover ); - t->set_color("font_color_bg","Tabs", control_font_color_low ); + t->set_color("font_color_fg", "Tabs", control_font_color_hover); + t->set_color("font_color_bg", "Tabs", control_font_color_low); t->set_color("font_color_disabled", "Tabs", control_font_color_disabled); - t->set_constant("top_margin","Tabs", 24 *scale); - t->set_constant("label_valign_fg","Tabs", 0 *scale); - t->set_constant("label_valign_bg","Tabs", 2 *scale); - t->set_constant("hseparation","Tabs", 4 *scale); - - + t->set_constant("top_margin", "Tabs", 24 * scale); + t->set_constant("label_valign_fg", "Tabs", 0 * scale); + t->set_constant("label_valign_bg", "Tabs", 2 * scale); + t->set_constant("hseparation", "Tabs", 4 * scale); // Separators - t->set_stylebox("separator","HSeparator", make_stylebox( vseparator_png,3,3,3,3) ); - t->set_stylebox("separator","VSeparator", make_stylebox( hseparator_png,3,3,3,3) ); - - t->set_icon("close","Icons", make_icon(icon_close_png)); - t->set_font("normal","Fonts", default_font ); - t->set_font("large","Fonts", large_font ); + t->set_stylebox("separator", "HSeparator", make_stylebox(vseparator_png, 3, 3, 3, 3)); + t->set_stylebox("separator", "VSeparator", make_stylebox(hseparator_png, 3, 3, 3, 3)); - t->set_constant("separation","HSeparator", 4 *scale); - t->set_constant("separation","VSeparator", 4 *scale); + t->set_icon("close", "Icons", make_icon(icon_close_png)); + t->set_font("normal", "Fonts", default_font); + t->set_font("large", "Fonts", large_font); + t->set_constant("separation", "HSeparator", 4 * scale); + t->set_constant("separation", "VSeparator", 4 * scale); // Dialogs - t->set_constant("margin","Dialogs",8 *scale); - t->set_constant("button_margin","Dialogs",32 *scale); - - + t->set_constant("margin", "Dialogs", 8 * scale); + t->set_constant("button_margin", "Dialogs", 32 * scale); // FileDialog - t->set_icon("folder","FileDialog",make_icon(icon_folder_png)); - t->set_color("files_disabled","FileDialog",Color(0,0,0,0.7)); - - + t->set_icon("folder", "FileDialog", make_icon(icon_folder_png)); + t->set_color("files_disabled", "FileDialog", Color(0, 0, 0, 0.7)); // colorPicker - t->set_constant("value_height","ColorPicker", 23 *scale); - t->set_constant("value_width","ColorPicker", 50 *scale); - t->set_constant("color_width","ColorPicker", 100 *scale); - t->set_constant("label_width","ColorPicker", 20 *scale); - t->set_constant("hseparator","ColorPicker", 4 *scale); + t->set_constant("value_height", "ColorPicker", 23 * scale); + t->set_constant("value_width", "ColorPicker", 50 * scale); + t->set_constant("color_width", "ColorPicker", 100 * scale); + t->set_constant("label_width", "ColorPicker", 20 * scale); + t->set_constant("hseparator", "ColorPicker", 4 * scale); - t->set_icon("screen_picker","ColorPicker", make_icon( icon_color_pick_png ) ); - t->set_icon("add_preset","ColorPicker", make_icon( icon_add_png ) ); - t->set_icon("color_hue", "ColorPicker", make_icon( color_picker_hue_png)); - t->set_icon("color_sample", "ColorPicker", make_icon( color_picker_sample_png)); + t->set_icon("screen_picker", "ColorPicker", make_icon(icon_color_pick_png)); + t->set_icon("add_preset", "ColorPicker", make_icon(icon_add_png)); + t->set_icon("color_hue", "ColorPicker", make_icon(color_picker_hue_png)); + t->set_icon("color_sample", "ColorPicker", make_icon(color_picker_sample_png)); // TooltipPanel - Ref<StyleBoxTexture> style_tt = make_stylebox( tooltip_bg_png,4,4,4,4); - for(int i=0;i<4;i++) - style_tt->set_expand_margin_size((Margin)i,4 *scale); - - t->set_stylebox("panel","TooltipPanel", style_tt ); - - t->set_font("font","TooltipLabel", default_font ); + Ref<StyleBoxTexture> style_tt = make_stylebox(tooltip_bg_png, 4, 4, 4, 4); + for (int i = 0; i < 4; i++) + style_tt->set_expand_margin_size((Margin)i, 4 * scale); - t->set_color("font_color","TooltipLabel", Color(0,0,0) ); - t->set_color("font_color_shadow","TooltipLabel", Color(0,0,0,0.1) ); + t->set_stylebox("panel", "TooltipPanel", style_tt); - t->set_constant("shadow_offset_x","TooltipLabel", 1 ); - t->set_constant("shadow_offset_y","TooltipLabel", 1 ); + t->set_font("font", "TooltipLabel", default_font); + t->set_color("font_color", "TooltipLabel", Color(0, 0, 0)); + t->set_color("font_color_shadow", "TooltipLabel", Color(0, 0, 0, 0.1)); + t->set_constant("shadow_offset_x", "TooltipLabel", 1); + t->set_constant("shadow_offset_y", "TooltipLabel", 1); // RichTextLabel - t->set_stylebox("focus","RichTextLabel", focus ); + t->set_stylebox("focus", "RichTextLabel", focus); - t->set_font("normal_font","RichTextLabel", default_font ); - t->set_font("bold_font","RichTextLabel", default_font ); - t->set_font("italics_font","RichTextLabel", default_font ); - t->set_font("bold_italics_font","RichTextLabel", default_font ); - t->set_font("mono_font","RichTextLabel", default_font ); - - t->set_color("default_color","RichTextLabel", control_font_color ); - t->set_color("font_color_selected","RichTextLabel", font_color_selection ); - t->set_color("selection_color","RichTextLabel", Color(0.1,0.1,1,0.8) ); - - t->set_constant("line_separation","RichTextLabel", 1 *scale); - t->set_constant("table_hseparation","RichTextLabel", 3 *scale); - t->set_constant("table_vseparation","RichTextLabel", 3 *scale); + t->set_font("normal_font", "RichTextLabel", default_font); + t->set_font("bold_font", "RichTextLabel", default_font); + t->set_font("italics_font", "RichTextLabel", default_font); + t->set_font("bold_italics_font", "RichTextLabel", default_font); + t->set_font("mono_font", "RichTextLabel", default_font); + t->set_color("default_color", "RichTextLabel", control_font_color); + t->set_color("font_color_selected", "RichTextLabel", font_color_selection); + t->set_color("selection_color", "RichTextLabel", Color(0.1, 0.1, 1, 0.8)); + t->set_constant("line_separation", "RichTextLabel", 1 * scale); + t->set_constant("table_hseparation", "RichTextLabel", 3 * scale); + t->set_constant("table_vseparation", "RichTextLabel", 3 * scale); // Containers - t->set_stylebox("bg","VSplitContainer", make_stylebox( vsplit_bg_png,1,1,1,1) ); - t->set_stylebox("bg","HSplitContainer", make_stylebox( hsplit_bg_png,1,1,1,1) ); - - t->set_icon("grabber","VSplitContainer",make_icon(vsplitter_png)); - t->set_icon("grabber","HSplitContainer",make_icon(hsplitter_png)); - - t->set_constant("separation","HBoxContainer",4 *scale); - t->set_constant("separation","VBoxContainer",4 *scale); - t->set_constant("margin_left","MarginContainer",8 *scale); - t->set_constant("margin_top","MarginContainer",0 *scale); - t->set_constant("margin_right","MarginContainer",0 *scale); - t->set_constant("margin_bottom","MarginContainer",0 *scale); - t->set_constant("hseparation","GridContainer",4 *scale); - t->set_constant("vseparation","GridContainer",4 *scale); - t->set_constant("separation","HSplitContainer",12 *scale); - t->set_constant("separation","VSplitContainer",12 *scale); - t->set_constant("autohide","HSplitContainer",1 *scale); - t->set_constant("autohide","VSplitContainer",1 *scale); - - + t->set_stylebox("bg", "VSplitContainer", make_stylebox(vsplit_bg_png, 1, 1, 1, 1)); + t->set_stylebox("bg", "HSplitContainer", make_stylebox(hsplit_bg_png, 1, 1, 1, 1)); + + t->set_icon("grabber", "VSplitContainer", make_icon(vsplitter_png)); + t->set_icon("grabber", "HSplitContainer", make_icon(hsplitter_png)); + + t->set_constant("separation", "HBoxContainer", 4 * scale); + t->set_constant("separation", "VBoxContainer", 4 * scale); + t->set_constant("margin_left", "MarginContainer", 8 * scale); + t->set_constant("margin_top", "MarginContainer", 0 * scale); + t->set_constant("margin_right", "MarginContainer", 0 * scale); + t->set_constant("margin_bottom", "MarginContainer", 0 * scale); + t->set_constant("hseparation", "GridContainer", 4 * scale); + t->set_constant("vseparation", "GridContainer", 4 * scale); + t->set_constant("separation", "HSplitContainer", 12 * scale); + t->set_constant("separation", "VSplitContainer", 12 * scale); + t->set_constant("autohide", "HSplitContainer", 1 * scale); + t->set_constant("autohide", "VSplitContainer", 1 * scale); // HButtonArray - t->set_stylebox("normal","HButtonArray", sb_button_normal); - t->set_stylebox("selected","HButtonArray", sb_button_pressed); - t->set_stylebox("hover","HButtonArray", sb_button_hover); - - t->set_font("font","HButtonArray", default_font); - t->set_font("font_selected","HButtonArray", default_font); + t->set_stylebox("normal", "HButtonArray", sb_button_normal); + t->set_stylebox("selected", "HButtonArray", sb_button_pressed); + t->set_stylebox("hover", "HButtonArray", sb_button_hover); - t->set_color("font_color","HButtonArray", control_font_color_low ); - t->set_color("font_color_selected","HButtonArray", control_font_color_hover ); + t->set_font("font", "HButtonArray", default_font); + t->set_font("font_selected", "HButtonArray", default_font); - t->set_constant("icon_separator","HButtonArray", 2 *scale ); - t->set_constant("button_separator","HButtonArray", 4 *scale ); + t->set_color("font_color", "HButtonArray", control_font_color_low); + t->set_color("font_color_selected", "HButtonArray", control_font_color_hover); - t->set_stylebox("focus","HButtonArray", focus ); + t->set_constant("icon_separator", "HButtonArray", 2 * scale); + t->set_constant("button_separator", "HButtonArray", 4 * scale); + t->set_stylebox("focus", "HButtonArray", focus); // VButtonArray - t->set_stylebox("normal","VButtonArray", sb_button_normal); - t->set_stylebox("selected","VButtonArray", sb_button_pressed); - t->set_stylebox("hover","VButtonArray", sb_button_hover); - - t->set_font("font","VButtonArray", default_font); - t->set_font("font_selected","VButtonArray", default_font); + t->set_stylebox("normal", "VButtonArray", sb_button_normal); + t->set_stylebox("selected", "VButtonArray", sb_button_pressed); + t->set_stylebox("hover", "VButtonArray", sb_button_hover); - t->set_color("font_color","VButtonArray", control_font_color_low ); - t->set_color("font_color_selected","VButtonArray", control_font_color_hover ); + t->set_font("font", "VButtonArray", default_font); + t->set_font("font_selected", "VButtonArray", default_font); - t->set_constant("icon_separator","VButtonArray", 2 *scale); - t->set_constant("button_separator","VButtonArray", 4 *scale); + t->set_color("font_color", "VButtonArray", control_font_color_low); + t->set_color("font_color_selected", "VButtonArray", control_font_color_hover); - t->set_stylebox("focus","VButtonArray", focus ); + t->set_constant("icon_separator", "VButtonArray", 2 * scale); + t->set_constant("button_separator", "VButtonArray", 4 * scale); + t->set_stylebox("focus", "VButtonArray", focus); // ReferenceRect - Ref<StyleBoxTexture> ttnc = make_stylebox( full_panel_bg_png,8,8,8,8); + Ref<StyleBoxTexture> ttnc = make_stylebox(full_panel_bg_png, 8, 8, 8, 8); ttnc->set_draw_center(false); - t->set_stylebox("border","ReferenceRect", make_stylebox( reference_border_png,4,4,4,4) ); - t->set_stylebox("panelnc","Panel", ttnc ); - t->set_stylebox("panelf","Panel", tc_sb ); - - Ref<StyleBoxTexture> sb_pc = make_stylebox( tab_container_bg_png,4,4,4,4,7,7,7,7); - t->set_stylebox("panel","PanelContainer", sb_pc ); - - + t->set_stylebox("border", "ReferenceRect", make_stylebox(reference_border_png, 4, 4, 4, 4)); + t->set_stylebox("panelnc", "Panel", ttnc); + t->set_stylebox("panelf", "Panel", tc_sb); - t->set_icon("minus","GraphEdit", make_icon(icon_zoom_less_png) ); - t->set_icon("reset","GraphEdit", make_icon(icon_zoom_reset_png) ); - t->set_icon("more","GraphEdit", make_icon(icon_zoom_more_png) ); - t->set_icon("snap","GraphEdit", make_icon(icon_snap_png) ); - t->set_stylebox("bg","GraphEdit", make_stylebox( tree_bg_png,4,4,4,5) ); - t->set_color("grid_minor","GraphEdit", Color(1,1,1,0.05) ); - t->set_color("grid_major","GraphEdit", Color(1,1,1,0.2) ); - t->set_constant("bezier_len_pos","GraphEdit", 80*scale ); - t->set_constant("bezier_len_neg","GraphEdit", 160*scale ); + Ref<StyleBoxTexture> sb_pc = make_stylebox(tab_container_bg_png, 4, 4, 4, 4, 7, 7, 7, 7); + t->set_stylebox("panel", "PanelContainer", sb_pc); + t->set_icon("minus", "GraphEdit", make_icon(icon_zoom_less_png)); + t->set_icon("reset", "GraphEdit", make_icon(icon_zoom_reset_png)); + t->set_icon("more", "GraphEdit", make_icon(icon_zoom_more_png)); + t->set_icon("snap", "GraphEdit", make_icon(icon_snap_png)); + t->set_stylebox("bg", "GraphEdit", make_stylebox(tree_bg_png, 4, 4, 4, 5)); + t->set_color("grid_minor", "GraphEdit", Color(1, 1, 1, 0.05)); + t->set_color("grid_major", "GraphEdit", Color(1, 1, 1, 0.2)); + t->set_constant("bezier_len_pos", "GraphEdit", 80 * scale); + t->set_constant("bezier_len_neg", "GraphEdit", 160 * scale); - - t->set_icon( "logo","Icons", make_icon(logo_png) ); - + t->set_icon("logo", "Icons", make_icon(logo_png)); // Theme - default_icon= make_icon(error_icon_png) ; - default_style = make_stylebox( error_icon_png,2,2,2,2) ; - - memdelete( tex_cache ); + default_icon = make_icon(error_icon_png); + default_style = make_stylebox(error_icon_png, 2, 2, 2, 2); + memdelete(tex_cache); } -void make_default_theme(bool p_hidpi,Ref<Font> p_font) { +void make_default_theme(bool p_hidpi, Ref<Font> p_font) { Ref<Theme> t; t.instance(); @@ -980,27 +902,25 @@ void make_default_theme(bool p_hidpi,Ref<Font> p_font) { Ref<Texture> default_icon; Ref<BitmapFont> default_font; if (p_font.is_valid()) { - default_font=p_font; + default_font = p_font; } else if (p_hidpi) { - default_font=make_font2(_hidpi_font_height,_hidpi_font_ascent,_hidpi_font_charcount,&_hidpi_font_charrects[0][0],_hidpi_font_kerning_pair_count,&_hidpi_font_kerning_pairs[0][0],_hidpi_font_img_width,_hidpi_font_img_height,_hidpi_font_img_data); + default_font = make_font2(_hidpi_font_height, _hidpi_font_ascent, _hidpi_font_charcount, &_hidpi_font_charrects[0][0], _hidpi_font_kerning_pair_count, &_hidpi_font_kerning_pairs[0][0], _hidpi_font_img_width, _hidpi_font_img_height, _hidpi_font_img_data); } else { - default_font=make_font2(_lodpi_font_height,_lodpi_font_ascent,_lodpi_font_charcount,&_lodpi_font_charrects[0][0],_lodpi_font_kerning_pair_count,&_lodpi_font_kerning_pairs[0][0],_lodpi_font_img_width,_lodpi_font_img_height,_lodpi_font_img_data); + default_font = make_font2(_lodpi_font_height, _lodpi_font_ascent, _lodpi_font_charcount, &_lodpi_font_charrects[0][0], _lodpi_font_kerning_pair_count, &_lodpi_font_kerning_pairs[0][0], _lodpi_font_img_width, _lodpi_font_img_height, _lodpi_font_img_data); } - Ref<BitmapFont> large_font=default_font; - fill_default_theme(t,default_font,large_font,default_icon,default_style,p_hidpi?2.0:1.0); - - Theme::set_default( t ); - Theme::set_default_icon( default_icon ); - Theme::set_default_style( default_style ); - Theme::set_default_font( default_font ); + Ref<BitmapFont> large_font = default_font; + fill_default_theme(t, default_font, large_font, default_icon, default_style, p_hidpi ? 2.0 : 1.0); + Theme::set_default(t); + Theme::set_default_icon(default_icon); + Theme::set_default_style(default_style); + Theme::set_default_font(default_font); } void clear_default_theme() { - Theme::set_default( Ref<Theme>() ); - Theme::set_default_icon( Ref< Texture >() ); - Theme::set_default_style( Ref< StyleBox >() ); - Theme::set_default_font( Ref< Font >() ); - + Theme::set_default(Ref<Theme>()); + Theme::set_default_icon(Ref<Texture>()); + Theme::set_default_style(Ref<StyleBox>()); + Theme::set_default_font(Ref<Font>()); } diff --git a/scene/resources/default_theme/default_theme.h b/scene/resources/default_theme/default_theme.h index 01141ed0a0..fc557e4270 100644 --- a/scene/resources/default_theme/default_theme.h +++ b/scene/resources/default_theme/default_theme.h @@ -35,7 +35,7 @@ @author Juan Linietsky <reduzio@gmail.com> */ -void fill_default_theme(Ref<Theme>& theme,const Ref<Font> & default_font,const Ref<Font> & large_font,Ref<Texture>& default_icon, Ref<StyleBox>& default_style,float p_scale); +void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const Ref<Font> &large_font, Ref<Texture> &default_icon, Ref<StyleBox> &default_style, float p_scale); void make_default_theme(bool p_hidpi, Ref<Font> p_font); void clear_default_theme(); diff --git a/scene/resources/dynamic_font.cpp b/scene/resources/dynamic_font.cpp index 02149f5748..08ebb954b2 100644 --- a/scene/resources/dynamic_font.cpp +++ b/scene/resources/dynamic_font.cpp @@ -30,9 +30,9 @@ #include "dynamic_font.h" #include "os/file_access.h" -bool DynamicFontData::CacheID::operator< (CacheID right) const{ +bool DynamicFontData::CacheID::operator<(CacheID right) const { - if (size<right.size) + if (size < right.size) return true; if (mipmaps != right.mipmaps) return right.mipmaps; @@ -41,37 +41,34 @@ bool DynamicFontData::CacheID::operator< (CacheID right) const{ return false; } -Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_id){ - +Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_id) { if (size_cache.has(p_id)) { - return Ref<DynamicFontAtSize>( size_cache[p_id] ); + return Ref<DynamicFontAtSize>(size_cache[p_id]); } - Ref<DynamicFontAtSize> dfas; dfas.instance(); - dfas->font=Ref<DynamicFontData>( this ); + dfas->font = Ref<DynamicFontData>(this); - size_cache[p_id]=dfas.ptr(); - dfas->id=p_id; + size_cache[p_id] = dfas.ptr(); + dfas->id = p_id; dfas->_load(); return dfas; - } -void DynamicFontData::set_font_ptr(const uint8_t* p_font_mem,int p_font_mem_size) { +void DynamicFontData::set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size) { - font_mem=p_font_mem; - font_mem_size=p_font_mem_size; + font_mem = p_font_mem; + font_mem_size = p_font_mem_size; } -void DynamicFontData::set_font_path(const String& p_path) { +void DynamicFontData::set_font_path(const String &p_path) { - font_path=p_path; + font_path = p_path; } String DynamicFontData::get_font_path() const { @@ -80,73 +77,67 @@ String DynamicFontData::get_font_path() const { void DynamicFontData::set_force_autohinter(bool p_force) { - force_autohinter=p_force; + force_autohinter = p_force; } void DynamicFontData::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_font_path","path"),&DynamicFontData::set_font_path); - ClassDB::bind_method(D_METHOD("get_font_path"),&DynamicFontData::get_font_path); + ClassDB::bind_method(D_METHOD("set_font_path", "path"), &DynamicFontData::set_font_path); + ClassDB::bind_method(D_METHOD("get_font_path"), &DynamicFontData::get_font_path); - ADD_PROPERTY(PropertyInfo(Variant::STRING,"font_path",PROPERTY_HINT_FILE,"*.ttf,*.otf"),"set_font_path","get_font_path"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_path", PROPERTY_HINT_FILE, "*.ttf,*.otf"), "set_font_path", "get_font_path"); } -DynamicFontData::DynamicFontData() -{ +DynamicFontData::DynamicFontData() { - force_autohinter=false; - font_mem=NULL; - font_mem_size=0; + force_autohinter = false; + font_mem = NULL; + font_mem_size = 0; } -DynamicFontData::~DynamicFontData() -{ - +DynamicFontData::~DynamicFontData() { } - - //////////////////// Error DynamicFontAtSize::_load() { - - int error = FT_Init_FreeType( &library ); + int error = FT_Init_FreeType(&library); ERR_EXPLAIN(TTR("Error initializing FreeType.")); - ERR_FAIL_COND_V( error !=0, ERR_CANT_CREATE ); + ERR_FAIL_COND_V(error != 0, ERR_CANT_CREATE); - if (font->font_path!=String()) { + if (font->font_path != String()) { - FileAccess *f=FileAccess::open(font->font_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); + FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); - memset(&stream,0,sizeof(FT_StreamRec)); - stream.base=NULL; - stream.size=f->get_len(); - stream.pos=0; - stream.descriptor.pointer=f; - stream.read=_ft_stream_io; - stream.close=_ft_stream_close; + memset(&stream, 0, sizeof(FT_StreamRec)); + stream.base = NULL; + stream.size = f->get_len(); + stream.pos = 0; + stream.descriptor.pointer = f; + stream.read = _ft_stream_io; + stream.close = _ft_stream_close; FT_Open_Args fargs; - memset(&fargs,0,sizeof(FT_Open_Args)); - fargs.flags=FT_OPEN_STREAM; - fargs.stream=&stream; - error = FT_Open_Face( library,&fargs,0,&face); + memset(&fargs, 0, sizeof(FT_Open_Args)); + fargs.flags = FT_OPEN_STREAM; + fargs.stream = &stream; + error = FT_Open_Face(library, &fargs, 0, &face); } else if (font->font_mem) { - memset(&stream,0,sizeof(FT_StreamRec)); - stream.base=(unsigned char*)font->font_mem; - stream.size=font->font_mem_size; - stream.pos=0; + memset(&stream, 0, sizeof(FT_StreamRec)); + stream.base = (unsigned char *)font->font_mem; + stream.size = font->font_mem_size; + stream.pos = 0; FT_Open_Args fargs; - memset(&fargs,0,sizeof(FT_Open_Args)); - fargs.memory_base=(unsigned char*)font->font_mem; - fargs.memory_size=font->font_mem_size; - fargs.flags= FT_OPEN_MEMORY; - fargs.stream=&stream; - error = FT_Open_Face( library,&fargs,0,&face); + memset(&fargs, 0, sizeof(FT_Open_Args)); + fargs.memory_base = (unsigned char *)font->font_mem; + fargs.memory_size = font->font_mem_size; + fargs.flags = FT_OPEN_MEMORY; + fargs.stream = &stream; + error = FT_Open_Face(library, &fargs, 0, &face); } else { ERR_EXPLAIN("DynamicFont uninitialized"); @@ -155,19 +146,17 @@ Error DynamicFontAtSize::_load() { //error = FT_New_Face( library, src_path.utf8().get_data(),0,&face ); - if ( error == FT_Err_Unknown_File_Format ) { + if (error == FT_Err_Unknown_File_Format) { ERR_EXPLAIN(TTR("Unknown font format.")); - FT_Done_FreeType( library ); + FT_Done_FreeType(library); - } else if ( error ) { + } else if (error) { ERR_EXPLAIN(TTR("Error loading font.")); - FT_Done_FreeType( library ); - + FT_Done_FreeType(library); } - ERR_FAIL_COND_V(error,ERR_FILE_CANT_OPEN); - + ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN); /*error = FT_Set_Char_Size(face,0,64*size,512,512); @@ -177,26 +166,26 @@ Error DynamicFontAtSize::_load() { ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER ); }*/ - error = FT_Set_Pixel_Sizes(face,0,id.size); + error = FT_Set_Pixel_Sizes(face, 0, id.size); - ascent=face->size->metrics.ascender>>6; - descent=-face->size->metrics.descender>>6; - linegap=0; - texture_flags=0; + ascent = face->size->metrics.ascender >> 6; + descent = -face->size->metrics.descender >> 6; + linegap = 0; + texture_flags = 0; if (id.mipmaps) - texture_flags|=Texture::FLAG_MIPMAPS; + texture_flags |= Texture::FLAG_MIPMAPS; if (id.filter) - texture_flags|=Texture::FLAG_FILTER; + texture_flags |= Texture::FLAG_FILTER; //print_line("ASCENT: "+itos(ascent)+" descent "+itos(descent)+" hinted: "+itos(face->face_flags&FT_FACE_FLAG_HINTER)); - valid=true; + valid = true; return OK; } float DynamicFontAtSize::get_height() const { - return ascent+descent; + return ascent + descent; } float DynamicFontAtSize::get_ascent() const { @@ -208,23 +197,23 @@ float DynamicFontAtSize::get_descent() const { return descent; } -Size2 DynamicFontAtSize::get_char_size(CharType p_char,CharType p_next,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const { +Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const { if (!valid) - return Size2(1,1); - const_cast<DynamicFontAtSize*>(this)->_update_char(p_char); + return Size2(1, 1); + const_cast<DynamicFontAtSize *>(this)->_update_char(p_char); const Character *c = char_map.getptr(p_char); - ERR_FAIL_COND_V(!c,Size2()); + ERR_FAIL_COND_V(!c, Size2()); - Size2 ret(0,get_height()); + Size2 ret(0, get_height()); if (!c->found) { //not found, try in fallbacks - for(int i=0;i<p_fallbacks.size();i++) { + for (int i = 0; i < p_fallbacks.size(); i++) { - DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr()); + DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr()); if (!fb->valid) continue; @@ -235,83 +224,79 @@ Size2 DynamicFontAtSize::get_char_size(CharType p_char,CharType p_next,const Vec if (!ch->found) continue; - c=ch; + c = ch; break; } //not found, try 0xFFFD to display 'not found'. if (!c->found) { - const_cast<DynamicFontAtSize*>(this)->_update_char(0xFFFD); + const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD); c = char_map.getptr(0xFFFD); - ERR_FAIL_COND_V(!c,Size2()); - + ERR_FAIL_COND_V(!c, Size2()); } } if (c->found) { - ret.x=c->advance; + ret.x = c->advance; } - if (p_next) { - FT_Vector delta; - FT_Get_Kerning( face, p_char,p_next, FT_KERNING_DEFAULT, &delta ); + FT_Vector delta; + FT_Get_Kerning(face, p_char, p_next, FT_KERNING_DEFAULT, &delta); - if (delta.x==0) { - for(int i=0;i<p_fallbacks.size();i++) { + if (delta.x == 0) { + for (int i = 0; i < p_fallbacks.size(); i++) { - DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr()); + DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr()); if (!fb->valid) continue; - FT_Get_Kerning( fb->face, p_char,p_next, FT_KERNING_DEFAULT, &delta ); + FT_Get_Kerning(fb->face, p_char, p_next, FT_KERNING_DEFAULT, &delta); - if (delta.x==0) + if (delta.x == 0) continue; - ret.x+=delta.x>>6; + ret.x += delta.x >> 6; break; } } else { - ret.x+=delta.x>>6; + ret.x += delta.x >> 6; } - - } return ret; } -void DynamicFontAtSize::set_texture_flags(uint32_t p_flags){ - - texture_flags=p_flags; - for(int i=0;i<textures.size();i++) { +void DynamicFontAtSize::set_texture_flags(uint32_t p_flags) { + + texture_flags = p_flags; + for (int i = 0; i < textures.size(); i++) { Ref<ImageTexture> &tex = textures[i].texture; if (!tex.is_null()) tex->set_flags(p_flags); } } -float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const { +float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const { if (!valid) return 0; - const_cast<DynamicFontAtSize*>(this)->_update_char(p_char); + const_cast<DynamicFontAtSize *>(this)->_update_char(p_char); - const Character * c = char_map.getptr(p_char); + const Character *c = char_map.getptr(p_char); - float advance=0; + float advance = 0; if (!c->found) { //not found, try in fallbacks - bool used_fallback=false; + bool used_fallback = false; - for(int i=0;i<p_fallbacks.size();i++) { + for (int i = 0; i < p_fallbacks.size(); i++) { - DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr()); + DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr()); if (!fb->valid) continue; @@ -322,93 +307,87 @@ float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2& p_pos, CharT if (!ch->found) continue; - Point2 cpos=p_pos; - cpos.x+=ch->h_align; - cpos.y-=get_ascent(); - cpos.y+=ch->v_align; - ERR_FAIL_COND_V( ch->texture_idx<-1 || ch->texture_idx>=fb->textures.size(),0); - if (ch->texture_idx!=-1) - VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, ch->rect.size ), fb->textures[ch->texture_idx].texture->get_rid(),ch->rect, p_modulate ); - advance=ch->advance; - used_fallback=true; + Point2 cpos = p_pos; + cpos.x += ch->h_align; + cpos.y -= get_ascent(); + cpos.y += ch->v_align; + ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= fb->textures.size(), 0); + if (ch->texture_idx != -1) + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, ch->rect.size), fb->textures[ch->texture_idx].texture->get_rid(), ch->rect, p_modulate); + advance = ch->advance; + used_fallback = true; break; } //not found, try 0xFFFD to display 'not found'. if (!used_fallback) { - const_cast<DynamicFontAtSize*>(this)->_update_char(0xFFFD); + const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD); c = char_map.getptr(0xFFFD); - } } if (c->found) { - - Point2 cpos=p_pos; - cpos.x+=c->h_align; - cpos.y-=get_ascent(); - cpos.y+=c->v_align; - ERR_FAIL_COND_V( c->texture_idx<-1 || c->texture_idx>=textures.size(),0); - if (c->texture_idx!=-1) - VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, c->rect.size ), textures[c->texture_idx].texture->get_rid(),c->rect, p_modulate ); - advance=c->advance; + Point2 cpos = p_pos; + cpos.x += c->h_align; + cpos.y -= get_ascent(); + cpos.y += c->v_align; + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0); + if (c->texture_idx != -1) + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx].texture->get_rid(), c->rect, p_modulate); + advance = c->advance; //textures[c->texture_idx].texture->draw(p_canvas_item,Vector2()); } - if (p_next) { - FT_Vector delta; - FT_Get_Kerning( face, p_char,p_next, FT_KERNING_DEFAULT, &delta ); + FT_Vector delta; + FT_Get_Kerning(face, p_char, p_next, FT_KERNING_DEFAULT, &delta); - if (delta.x==0) { - for(int i=0;i<p_fallbacks.size();i++) { + if (delta.x == 0) { + for (int i = 0; i < p_fallbacks.size(); i++) { - DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr()); + DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr()); if (!fb->valid) continue; - FT_Get_Kerning( fb->face, p_char,p_next, FT_KERNING_DEFAULT, &delta ); + FT_Get_Kerning(fb->face, p_char, p_next, FT_KERNING_DEFAULT, &delta); - if (delta.x==0) + if (delta.x == 0) continue; - advance+=delta.x>>6; + advance += delta.x >> 6; break; } } else { - advance+=delta.x>>6; + advance += delta.x >> 6; } } return advance; } -unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ) { - +unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) { - FileAccess *f=(FileAccess*)stream->descriptor.pointer; + FileAccess *f = (FileAccess *)stream->descriptor.pointer; - if (f->get_pos()!=offset) { + if (f->get_pos() != offset) { f->seek(offset); - } - if (count==0) + if (count == 0) return 0; - return f->get_buffer(buffer,count); + return f->get_buffer(buffer, count); } void DynamicFontAtSize::_ft_stream_close(FT_Stream stream) { - FileAccess *f=(FileAccess*)stream->descriptor.pointer; + FileAccess *f = (FileAccess *)stream->descriptor.pointer; f->close(); memdelete(f); } - void DynamicFontAtSize::_update_char(CharType p_char) { if (char_map.has(p_char)) @@ -418,154 +397,146 @@ void DynamicFontAtSize::_update_char(CharType p_char) { FT_GlyphSlot slot = face->glyph; - if (FT_Get_Char_Index( face, p_char)==0) { + if (FT_Get_Char_Index(face, p_char) == 0) { //not found Character ch; - ch.texture_idx=-1; - ch.advance=0; - ch.h_align=0; - ch.v_align=0; - ch.found=false; + ch.texture_idx = -1; + ch.advance = 0; + ch.h_align = 0; + ch.v_align = 0; + ch.found = false; - char_map[p_char]=ch; + char_map[p_char] = ch; return; } - int error = FT_Load_Char( face, p_char, FT_LOAD_RENDER|(font->force_autohinter?FT_LOAD_FORCE_AUTOHINT:0) ); + int error = FT_Load_Char(face, p_char, FT_LOAD_RENDER | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); if (!error) { - error = FT_Render_Glyph( face->glyph, ft_render_mode_normal ); + error = FT_Render_Glyph(face->glyph, ft_render_mode_normal); } if (error) { - int advance=0; + int advance = 0; //stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0); //print_line("char has no bitmap: "+itos(p_char)+" but advance is "+itos(advance*scale)); Character ch; - ch.texture_idx=-1; - ch.advance=advance; - ch.h_align=0; - ch.v_align=0; - ch.found=false; - - char_map[p_char]=ch; + ch.texture_idx = -1; + ch.advance = advance; + ch.h_align = 0; + ch.v_align = 0; + ch.found = false; + char_map[p_char] = ch; return; } - - int w = slot->bitmap.width; int h = slot->bitmap.rows; //int p = slot->bitmap.pitch; - int yofs=slot->bitmap_top; - int xofs=slot->bitmap_left; - int advance=slot->advance.x>>6; + int yofs = slot->bitmap_top; + int xofs = slot->bitmap_left; + int advance = slot->advance.x >> 6; + int mw = w + rect_margin * 2; + int mh = h + rect_margin * 2; - int mw=w+rect_margin*2; - int mh=h+rect_margin*2; + if (mw > 4096 || mh > 4096) { - if (mw>4096 || mh>4096) { - - ERR_FAIL_COND(mw>4096); - ERR_FAIL_COND(mh>4096); + ERR_FAIL_COND(mw > 4096); + ERR_FAIL_COND(mh > 4096); } //find a texture to fit this... - int tex_index=-1; - int tex_x=0; - int tex_y=0; + int tex_index = -1; + int tex_x = 0; + int tex_y = 0; - for(int i=0;i<textures.size();i++) { + for (int i = 0; i < textures.size(); i++) { - CharTexture &ct=textures[i]; + CharTexture &ct = textures[i]; if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture continue; - tex_y=0x7FFFFFFF; - tex_x=0; + tex_y = 0x7FFFFFFF; + tex_x = 0; - for(int j=0;j<ct.texture_size-mw;j++) { + for (int j = 0; j < ct.texture_size - mw; j++) { - int max_y=0; + int max_y = 0; - for(int k=j;k<j+mw;k++) { + for (int k = j; k < j + mw; k++) { int y = ct.offsets[k]; - if (y>max_y) - max_y=y; + if (y > max_y) + max_y = y; } - if (max_y<tex_y) { - tex_y=max_y; - tex_x=j; + if (max_y < tex_y) { + tex_y = max_y; + tex_x = j; } } - if (tex_y==0x7FFFFFFF || tex_y+mh > ct.texture_size) + if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size) continue; //fail, could not fit it here - tex_index=i; + tex_index = i; break; } //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" X: "+itos(tex_x)+" Y: "+itos(tex_y)); - if (tex_index==-1) { + if (tex_index == -1) { //could not find texture to fit, create one tex_x = 0; tex_y = 0; - int texsize = MAX(id.size*8,256); - if (mw>texsize) - texsize=mw; //special case, adapt to it? - if (mh>texsize) - texsize=mh; //special case, adapt to it? - - texsize=nearest_power_of_2(texsize); + int texsize = MAX(id.size * 8, 256); + if (mw > texsize) + texsize = mw; //special case, adapt to it? + if (mh > texsize) + texsize = mh; //special case, adapt to it? - texsize=MIN(texsize,4096); + texsize = nearest_power_of_2(texsize); + texsize = MIN(texsize, 4096); CharTexture tex; - tex.texture_size=texsize; - tex.imgdata.resize(texsize*texsize*2); //grayscale alpha + tex.texture_size = texsize; + tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha { //zero texture PoolVector<uint8_t>::Write w = tex.imgdata.write(); - ERR_FAIL_COND(texsize*texsize*2 > tex.imgdata.size()); - for(int i=0;i<texsize*texsize*2;i++) { - w[i]=0; + ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size()); + for (int i = 0; i < texsize * texsize * 2; i++) { + w[i] = 0; } } tex.offsets.resize(texsize); - for(int i=0;i<texsize;i++) //zero offsets - tex.offsets[i]=0; + for (int i = 0; i < texsize; i++) //zero offsets + tex.offsets[i] = 0; textures.push_back(tex); - tex_index=textures.size()-1; - + tex_index = textures.size() - 1; } - //fit character in char texture - CharTexture &tex=textures[tex_index]; + CharTexture &tex = textures[tex_index]; { PoolVector<uint8_t>::Write wr = tex.imgdata.write(); + for (int i = 0; i < h; i++) { + for (int j = 0; j < w; j++) { - for(int i=0;i<h;i++) { - for(int j=0;j<w;j++) { - - int ofs = ( (i+tex_y+rect_margin)*tex.texture_size+j+tex_x+rect_margin)*2; + int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2; ERR_FAIL_COND(ofs >= tex.imgdata.size()); - wr[ofs+0]=255; //grayscale as 1 - wr[ofs+1]=slot->bitmap.buffer[i*slot->bitmap.width+j]; + wr[ofs + 0] = 255; //grayscale as 1 + wr[ofs + 1] = slot->bitmap.buffer[i * slot->bitmap.width + j]; } } } @@ -573,237 +544,224 @@ void DynamicFontAtSize::_update_char(CharType p_char) { //blit to image and texture { - Image img(tex.texture_size,tex.texture_size,0,Image::FORMAT_LA8,tex.imgdata); + Image img(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata); if (tex.texture.is_null()) { tex.texture.instance(); - tex.texture->create_from_image(img,Texture::FLAG_VIDEO_SURFACE|texture_flags); + tex.texture->create_from_image(img, Texture::FLAG_VIDEO_SURFACE | texture_flags); } else { tex.texture->set_data(img); //update } - } - // update height array - for(int k=tex_x;k<tex_x+mw;k++) { + for (int k = tex_x; k < tex_x + mw; k++) { - tex.offsets[k]=tex_y+mh; + tex.offsets[k] = tex_y + mh; } - Character chr; - chr.h_align=xofs; - chr.v_align=ascent-yofs;// + ascent - descent; - chr.advance=advance; - chr.texture_idx=tex_index; - chr.found=true; - + chr.h_align = xofs; + chr.v_align = ascent - yofs; // + ascent - descent; + chr.advance = advance; + chr.texture_idx = tex_index; + chr.found = true; - chr.rect=Rect2(tex_x+rect_margin,tex_y+rect_margin,w,h); + chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h); //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" RECT: "+chr.rect+" X OFS: "+itos(xofs)+" Y OFS: "+itos(yofs)); - char_map[p_char]=chr; - - + char_map[p_char] = chr; } DynamicFontAtSize::DynamicFontAtSize() { - valid=false; - rect_margin=1; - ascent=1; - descent=1; - linegap=1; - texture_flags=0; + valid = false; + rect_margin = 1; + ascent = 1; + descent = 1; + linegap = 1; + texture_flags = 0; } -DynamicFontAtSize::~DynamicFontAtSize(){ +DynamicFontAtSize::~DynamicFontAtSize() { if (valid) { - FT_Done_FreeType( library ); + FT_Done_FreeType(library); font->size_cache.erase(id); } } ///////////////////////// +void DynamicFont::_reload_cache() { -void DynamicFont::_reload_cache(){ - - ERR_FAIL_COND(cache_id.size<1); + ERR_FAIL_COND(cache_id.size < 1); if (!data.is_valid()) return; - data_at_size=data->_get_dynamic_font_at_size(cache_id); - for (int i=0;i<fallbacks.size();i++){ - fallback_data_at_size[i]=fallbacks[i]->_get_dynamic_font_at_size(cache_id); + data_at_size = data->_get_dynamic_font_at_size(cache_id); + for (int i = 0; i < fallbacks.size(); i++) { + fallback_data_at_size[i] = fallbacks[i]->_get_dynamic_font_at_size(cache_id); } emit_changed(); _change_notify(); } -void DynamicFont::set_font_data(const Ref<DynamicFontData>& p_data) { +void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) { - data=p_data; + data = p_data; if (data.is_valid()) - data_at_size=data->_get_dynamic_font_at_size(cache_id); + data_at_size = data->_get_dynamic_font_at_size(cache_id); else - data_at_size=Ref<DynamicFontAtSize>(); + data_at_size = Ref<DynamicFontAtSize>(); emit_changed(); } - -Ref<DynamicFontData> DynamicFont::get_font_data() const{ +Ref<DynamicFontData> DynamicFont::get_font_data() const { return data; } -void DynamicFont::set_size(int p_size){ +void DynamicFont::set_size(int p_size) { - if (cache_id.size==p_size) + if (cache_id.size == p_size) return; - cache_id.size=p_size; + cache_id.size = p_size; _reload_cache(); } -int DynamicFont::get_size() const{ +int DynamicFont::get_size() const { return cache_id.size; } -bool DynamicFont::get_use_mipmaps() const{ +bool DynamicFont::get_use_mipmaps() const { return cache_id.mipmaps; } -void DynamicFont::set_use_mipmaps(bool p_enable){ +void DynamicFont::set_use_mipmaps(bool p_enable) { - if (cache_id.mipmaps==p_enable) + if (cache_id.mipmaps == p_enable) return; - cache_id.mipmaps=p_enable; + cache_id.mipmaps = p_enable; _reload_cache(); } -bool DynamicFont::get_use_filter() const{ +bool DynamicFont::get_use_filter() const { return cache_id.filter; } -void DynamicFont::set_use_filter(bool p_enable){ +void DynamicFont::set_use_filter(bool p_enable) { - if (cache_id.filter==p_enable) + if (cache_id.filter == p_enable) return; - cache_id.filter=p_enable; + cache_id.filter = p_enable; _reload_cache(); } -int DynamicFont::get_spacing(int p_type) const{ +int DynamicFont::get_spacing(int p_type) const { - if (p_type == SPACING_TOP){ + if (p_type == SPACING_TOP) { return spacing_top; - }else if (p_type == SPACING_BOTTOM){ + } else if (p_type == SPACING_BOTTOM) { return spacing_bottom; - }else if (p_type == SPACING_CHAR){ + } else if (p_type == SPACING_CHAR) { return spacing_char; - }else if (p_type == SPACING_SPACE){ + } else if (p_type == SPACING_SPACE) { return spacing_space; } return 0; } -void DynamicFont::set_spacing(int p_type, int p_value){ +void DynamicFont::set_spacing(int p_type, int p_value) { - if (p_type == SPACING_TOP){ - spacing_top=p_value; - }else if (p_type == SPACING_BOTTOM){ - spacing_bottom=p_value; - }else if (p_type == SPACING_CHAR){ - spacing_char=p_value; - }else if (p_type == SPACING_SPACE){ - spacing_space=p_value; + if (p_type == SPACING_TOP) { + spacing_top = p_value; + } else if (p_type == SPACING_BOTTOM) { + spacing_bottom = p_value; + } else if (p_type == SPACING_CHAR) { + spacing_char = p_value; + } else if (p_type == SPACING_SPACE) { + spacing_space = p_value; } emit_changed(); _change_notify(); } -float DynamicFont::get_height() const{ +float DynamicFont::get_height() const { if (!data_at_size.is_valid()) return 1; - return data_at_size->get_height()+spacing_top+spacing_bottom; + return data_at_size->get_height() + spacing_top + spacing_bottom; } -float DynamicFont::get_ascent() const{ +float DynamicFont::get_ascent() const { if (!data_at_size.is_valid()) return 1; - return data_at_size->get_ascent()+spacing_top; + return data_at_size->get_ascent() + spacing_top; } -float DynamicFont::get_descent() const{ +float DynamicFont::get_descent() const { if (!data_at_size.is_valid()) return 1; - return data_at_size->get_descent()+spacing_bottom; - + return data_at_size->get_descent() + spacing_bottom; } -Size2 DynamicFont::get_char_size(CharType p_char,CharType p_next) const{ +Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const { if (!data_at_size.is_valid()) - return Size2(1,1); + return Size2(1, 1); - Size2 ret=data_at_size->get_char_size(p_char,p_next,fallback_data_at_size); - if (p_char==' ') - ret.width+=spacing_space+spacing_char; + Size2 ret = data_at_size->get_char_size(p_char, p_next, fallback_data_at_size); + if (p_char == ' ') + ret.width += spacing_space + spacing_char; else if (p_next) - ret.width+=spacing_char; + ret.width += spacing_char; return ret; - } -bool DynamicFont::is_distance_field_hint() const{ +bool DynamicFont::is_distance_field_hint() const { return false; } -float DynamicFont::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate) const { +float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const { if (!data_at_size.is_valid()) return 0; - return data_at_size->draw_char(p_canvas_item,p_pos,p_char,p_next,p_modulate,fallback_data_at_size)+spacing_char; - + return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate, fallback_data_at_size) + spacing_char; } -void DynamicFont::set_fallback(int p_idx,const Ref<DynamicFontData>& p_data) { +void DynamicFont::set_fallback(int p_idx, const Ref<DynamicFontData> &p_data) { ERR_FAIL_COND(p_data.is_null()); - ERR_FAIL_INDEX(p_idx,fallbacks.size()); - fallbacks[p_idx]=p_data; - fallback_data_at_size[p_idx]=fallbacks[p_idx]->_get_dynamic_font_at_size(cache_id); - + ERR_FAIL_INDEX(p_idx, fallbacks.size()); + fallbacks[p_idx] = p_data; + fallback_data_at_size[p_idx] = fallbacks[p_idx]->_get_dynamic_font_at_size(cache_id); } -void DynamicFont::add_fallback(const Ref<DynamicFontData>& p_data) { +void DynamicFont::add_fallback(const Ref<DynamicFontData> &p_data) { ERR_FAIL_COND(p_data.is_null()); fallbacks.push_back(p_data); - fallback_data_at_size.push_back(fallbacks[fallbacks.size()-1]->_get_dynamic_font_at_size(cache_id)); //const.. + fallback_data_at_size.push_back(fallbacks[fallbacks.size() - 1]->_get_dynamic_font_at_size(cache_id)); //const.. _change_notify(); emit_changed(); _change_notify(); - } int DynamicFont::get_fallback_count() const { @@ -811,37 +769,37 @@ int DynamicFont::get_fallback_count() const { } Ref<DynamicFontData> DynamicFont::get_fallback(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,fallbacks.size(),Ref<DynamicFontData>()); + ERR_FAIL_INDEX_V(p_idx, fallbacks.size(), Ref<DynamicFontData>()); return fallbacks[p_idx]; } void DynamicFont::remove_fallback(int p_idx) { - ERR_FAIL_INDEX(p_idx,fallbacks.size()); + ERR_FAIL_INDEX(p_idx, fallbacks.size()); fallbacks.remove(p_idx); fallback_data_at_size.remove(p_idx); emit_changed(); _change_notify(); } -bool DynamicFont::_set(const StringName& p_name, const Variant& p_value) { +bool DynamicFont::_set(const StringName &p_name, const Variant &p_value) { String str = p_name; if (str.begins_with("fallback/")) { - int idx = str.get_slicec('/',1).to_int(); + int idx = str.get_slicec('/', 1).to_int(); Ref<DynamicFontData> fd = p_value; if (fd.is_valid()) { - if (idx==fallbacks.size()) { + if (idx == fallbacks.size()) { add_fallback(fd); return true; - } else if (idx>=0 && idx<fallbacks.size()) { - set_fallback(idx,fd); + } else if (idx >= 0 && idx < fallbacks.size()) { + set_fallback(idx, fd); return true; } else { return false; } - } else if (idx>=0 && idx<fallbacks.size()) { + } else if (idx >= 0 && idx < fallbacks.size()) { remove_fallback(idx); return true; } @@ -850,100 +808,95 @@ bool DynamicFont::_set(const StringName& p_name, const Variant& p_value) { return false; } -bool DynamicFont::_get(const StringName& p_name,Variant &r_ret) const{ +bool DynamicFont::_get(const StringName &p_name, Variant &r_ret) const { String str = p_name; if (str.begins_with("fallback/")) { - int idx = str.get_slicec('/',1).to_int(); + int idx = str.get_slicec('/', 1).to_int(); - if (idx==fallbacks.size()) { - r_ret=Ref<DynamicFontData>(); + if (idx == fallbacks.size()) { + r_ret = Ref<DynamicFontData>(); return true; - } else if (idx>=0 && idx<fallbacks.size()) { - r_ret=get_fallback(idx); + } else if (idx >= 0 && idx < fallbacks.size()) { + r_ret = get_fallback(idx); return true; } } return false; } -void DynamicFont::_get_property_list( List<PropertyInfo> *p_list) const{ +void DynamicFont::_get_property_list(List<PropertyInfo> *p_list) const { - for(int i=0;i<fallbacks.size();i++) { - p_list->push_back(PropertyInfo(Variant::OBJECT,"fallback/"+itos(i),PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData")); + for (int i = 0; i < fallbacks.size(); i++) { + p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData")); } - p_list->push_back(PropertyInfo(Variant::OBJECT,"fallback/"+itos(fallbacks.size()),PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData")); + p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(fallbacks.size()), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData")); } - void DynamicFont::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_font_data","data:DynamicFontData"),&DynamicFont::set_font_data); - ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"),&DynamicFont::get_font_data); - - ClassDB::bind_method(D_METHOD("set_size","data"),&DynamicFont::set_size); - ClassDB::bind_method(D_METHOD("get_size"),&DynamicFont::get_size); - - ClassDB::bind_method(D_METHOD("set_use_mipmaps","enable"),&DynamicFont::set_use_mipmaps); - ClassDB::bind_method(D_METHOD("get_use_mipmaps"),&DynamicFont::get_use_mipmaps); - ClassDB::bind_method(D_METHOD("set_use_filter","enable"),&DynamicFont::set_use_filter); - ClassDB::bind_method(D_METHOD("get_use_filter"),&DynamicFont::get_use_filter); - ClassDB::bind_method(D_METHOD("set_spacing","type","value"),&DynamicFont::set_spacing); - ClassDB::bind_method(D_METHOD("get_spacing","type"),&DynamicFont::get_spacing); - - ClassDB::bind_method(D_METHOD("add_fallback","data:DynamicFontData"),&DynamicFont::add_fallback); - ClassDB::bind_method(D_METHOD("set_fallback","idx","data:DynamicFontData"),&DynamicFont::set_fallback); - ClassDB::bind_method(D_METHOD("get_fallback:DynamicFontData","idx"),&DynamicFont::get_fallback); - ClassDB::bind_method(D_METHOD("remove_fallback","idx"),&DynamicFont::remove_fallback); - ClassDB::bind_method(D_METHOD("get_fallback_count"),&DynamicFont::get_fallback_count); - - - ADD_GROUP("Settings",""); - ADD_PROPERTY(PropertyInfo(Variant::INT,"size"),"set_size","get_size"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_mipmaps"),"set_use_mipmaps","get_use_mipmaps"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_filter"),"set_use_filter","get_use_filter"); - ADD_GROUP("Extra Spacing","extra_spacing"); - ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_top"),"set_spacing","get_spacing",SPACING_TOP); - ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_bottom"),"set_spacing","get_spacing",SPACING_BOTTOM); - ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_char"),"set_spacing","get_spacing",SPACING_CHAR); - ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_space"),"set_spacing","get_spacing",SPACING_SPACE); - ADD_GROUP("Font",""); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"font_data",PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData"),"set_font_data","get_font_data"); - - BIND_CONSTANT( SPACING_TOP ); - BIND_CONSTANT( SPACING_BOTTOM ); - BIND_CONSTANT( SPACING_CHAR ); - BIND_CONSTANT( SPACING_SPACE ); + ClassDB::bind_method(D_METHOD("set_font_data", "data:DynamicFontData"), &DynamicFont::set_font_data); + ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"), &DynamicFont::get_font_data); + + ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size); + ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size); + + ClassDB::bind_method(D_METHOD("set_use_mipmaps", "enable"), &DynamicFont::set_use_mipmaps); + ClassDB::bind_method(D_METHOD("get_use_mipmaps"), &DynamicFont::get_use_mipmaps); + ClassDB::bind_method(D_METHOD("set_use_filter", "enable"), &DynamicFont::set_use_filter); + ClassDB::bind_method(D_METHOD("get_use_filter"), &DynamicFont::get_use_filter); + ClassDB::bind_method(D_METHOD("set_spacing", "type", "value"), &DynamicFont::set_spacing); + ClassDB::bind_method(D_METHOD("get_spacing", "type"), &DynamicFont::get_spacing); + + ClassDB::bind_method(D_METHOD("add_fallback", "data:DynamicFontData"), &DynamicFont::add_fallback); + ClassDB::bind_method(D_METHOD("set_fallback", "idx", "data:DynamicFontData"), &DynamicFont::set_fallback); + ClassDB::bind_method(D_METHOD("get_fallback:DynamicFontData", "idx"), &DynamicFont::get_fallback); + ClassDB::bind_method(D_METHOD("remove_fallback", "idx"), &DynamicFont::remove_fallback); + ClassDB::bind_method(D_METHOD("get_fallback_count"), &DynamicFont::get_fallback_count); + + ADD_GROUP("Settings", ""); + ADD_PROPERTY(PropertyInfo(Variant::INT, "size"), "set_size", "get_size"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "get_use_mipmaps"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_filter"), "set_use_filter", "get_use_filter"); + ADD_GROUP("Extra Spacing", "extra_spacing"); + ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_top"), "set_spacing", "get_spacing", SPACING_TOP); + ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_bottom"), "set_spacing", "get_spacing", SPACING_BOTTOM); + ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_char"), "set_spacing", "get_spacing", SPACING_CHAR); + ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_space"), "set_spacing", "get_spacing", SPACING_SPACE); + ADD_GROUP("Font", ""); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font_data", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data"); + + BIND_CONSTANT(SPACING_TOP); + BIND_CONSTANT(SPACING_BOTTOM); + BIND_CONSTANT(SPACING_CHAR); + BIND_CONSTANT(SPACING_SPACE); } DynamicFont::DynamicFont() { - spacing_top=0; - spacing_bottom=0; - spacing_char=0; - spacing_space=0; + spacing_top = 0; + spacing_bottom = 0; + spacing_char = 0; + spacing_space = 0; } DynamicFont::~DynamicFont() { - } ///////////////////////// - -RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; Ref<DynamicFontData> dfont; dfont.instance(); dfont->set_font_path(p_path); - if (r_error) - *r_error=OK; + *r_error = OK; return dfont; } @@ -954,18 +907,17 @@ void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_ p_extensions->push_back("otf"); } -bool ResourceFormatLoaderDynamicFont::handles_type(const String& p_type) const { +bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const { - return (p_type=="DynamicFontData"); + return (p_type == "DynamicFontData"); } String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const { String el = p_path.get_extension().to_lower(); - if (el=="ttf" || el=="otf") + if (el == "ttf" || el == "otf") return "DynamicFontData"; return ""; } - #endif diff --git a/scene/resources/dynamic_font.h b/scene/resources/dynamic_font.h index 321ec7e332..9502943909 100644 --- a/scene/resources/dynamic_font.h +++ b/scene/resources/dynamic_font.h @@ -30,54 +30,55 @@ #define DYNAMIC_FONT_H #ifdef FREETYPE_ENABLED -#include "scene/resources/font.h" -#include "os/thread_safe.h" #include "io/resource_loader.h" +#include "os/thread_safe.h" +#include "scene/resources/font.h" #include <ft2build.h> #include FT_FREETYPE_H - class DynamicFontAtSize; class DynamicFont; class DynamicFontData : public Resource { - GDCLASS(DynamicFontData,Resource); + GDCLASS(DynamicFontData, Resource); public: - - struct CacheID{ + struct CacheID { int size; bool mipmaps; bool filter; - bool operator< (CacheID right) const; - CacheID() { size=16; mipmaps=false; filter=false; } + bool operator<(CacheID right) const; + CacheID() { + size = 16; + mipmaps = false; + filter = false; + } }; private: - const uint8_t *font_mem; int font_mem_size; bool force_autohinter; String font_path; - Map<CacheID,DynamicFontAtSize*> size_cache; + Map<CacheID, DynamicFontAtSize *> size_cache; friend class DynamicFontAtSize; -friend class DynamicFont; + friend class DynamicFont; Ref<DynamicFontAtSize> _get_dynamic_font_at_size(CacheID p_cache); -protected: +protected: static void _bind_methods(); -public: - void set_font_ptr(const uint8_t* p_font_mem,int p_font_mem_size); - void set_font_path(const String& p_path); +public: + void set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size); + void set_font_path(const String &p_path); String get_font_path() const; void set_force_autohinter(bool p_force); @@ -85,15 +86,14 @@ public: ~DynamicFontData(); }; - class DynamicFontAtSize : public Reference { - GDCLASS(DynamicFontAtSize,Reference) + GDCLASS(DynamicFontAtSize, Reference) _THREAD_SAFE_CLASS_ - FT_Library library; /* handle to library */ - FT_Face face; /* handle to face object */ + FT_Library library; /* handle to library */ + FT_Face face; /* handle to face object */ FT_StreamRec stream; int ascent; @@ -124,39 +124,35 @@ class DynamicFontAtSize : public Reference { float h_align; float advance; - Character() { texture_idx=0; v_align=0; } + Character() { + texture_idx = 0; + v_align = 0; + } }; + static unsigned long _ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count); + static void _ft_stream_close(FT_Stream stream); - static unsigned long _ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ); - static void _ft_stream_close(FT_Stream stream); - - HashMap< CharType, Character > char_map; + HashMap<CharType, Character> char_map; _FORCE_INLINE_ void _update_char(CharType p_char); -friend class DynamicFontData; + friend class DynamicFontData; Ref<DynamicFontData> font; DynamicFontData::CacheID id; - - Error _load(); -protected: - - +protected: public: - - float get_height() const; float get_ascent() const; float get_descent() const; - Size2 get_char_size(CharType p_char,CharType p_next,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const; + Size2 get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const; - float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const; + float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const; void set_texture_flags(uint32_t p_flags); @@ -168,11 +164,10 @@ public: class DynamicFont : public Font { - GDCLASS( DynamicFont, Font ); + GDCLASS(DynamicFont, Font); public: - - enum SpacingType{ + enum SpacingType { SPACING_TOP, SPACING_BOTTOM, SPACING_CHAR, @@ -180,13 +175,11 @@ public: }; private: - Ref<DynamicFontData> data; Ref<DynamicFontAtSize> data_at_size; - Vector< Ref<DynamicFontData> > fallbacks; - Vector< Ref<DynamicFontAtSize> > fallback_data_at_size; - + Vector<Ref<DynamicFontData> > fallbacks; + Vector<Ref<DynamicFontAtSize> > fallback_data_at_size; DynamicFontData::CacheID cache_id; bool valid; @@ -196,18 +189,16 @@ private: int spacing_space; protected: - void _reload_cache(); - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); public: - - void set_font_data(const Ref<DynamicFontData>& p_data); + void set_font_data(const Ref<DynamicFontData> &p_data); Ref<DynamicFontData> get_font_data() const; void set_size(int p_size); @@ -222,8 +213,8 @@ public: int get_spacing(int p_type) const; void set_spacing(int p_type, int p_value); - void add_fallback(const Ref<DynamicFontData>& p_data); - void set_fallback(int p_idx,const Ref<DynamicFontData>& p_data); + void add_fallback(const Ref<DynamicFontData> &p_data); + void set_fallback(int p_idx, const Ref<DynamicFontData> &p_data); int get_fallback_count() const; Ref<DynamicFontData> get_fallback(int p_idx) const; void remove_fallback(int p_idx); @@ -233,32 +224,26 @@ public: virtual float get_ascent() const; virtual float get_descent() const; - virtual Size2 get_char_size(CharType p_char,CharType p_next=0) const; + virtual Size2 get_char_size(CharType p_char, CharType p_next = 0) const; virtual bool is_distance_field_hint() const; - virtual float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const; + virtual float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const; DynamicFont(); ~DynamicFont(); - }; - - ///////////// class ResourceFormatLoaderDynamicFont : public ResourceFormatLoader { public: - - virtual RES load(const String &p_path,const String& p_original_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; - 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; - }; - #endif #endif diff --git a/scene/resources/dynamic_font_stb.cpp b/scene/resources/dynamic_font_stb.cpp index 2d659a7e97..7b62ccc369 100644 --- a/scene/resources/dynamic_font_stb.cpp +++ b/scene/resources/dynamic_font_stb.cpp @@ -31,24 +31,24 @@ #ifndef FREETYPE_ENABLED #define STB_TRUETYPE_IMPLEMENTATION -#include "stb_truetype.h" #include "os/file_access.h" +#include "stb_truetype.h" void DynamicFontData::lock() { - fr=font_data.read(); + fr = font_data.read(); - if (fr.ptr()!=last_data_ptr) { + if (fr.ptr() != last_data_ptr) { - last_data_ptr=fr.ptr(); + last_data_ptr = fr.ptr(); if (!stbtt_InitFont(&info, last_data_ptr, 0)) { - valid=false; + valid = false; } else { - valid=true; + valid = true; } - last_data_ptr=fr.ptr(); + last_data_ptr = fr.ptr(); } } @@ -57,26 +57,26 @@ void DynamicFontData::unlock() { fr = PoolVector<uint8_t>::Read(); } -void DynamicFontData::set_font_data(const PoolVector<uint8_t>& p_font) { +void DynamicFontData::set_font_data(const PoolVector<uint8_t> &p_font) { //clear caches and stuff - ERR_FAIL_COND(font_data.size()) ; - font_data=p_font; + ERR_FAIL_COND(font_data.size()); + font_data = p_font; lock(); if (valid) { stbtt_GetFontVMetrics(&info, &ascent, &descent, &linegap); - descent=-descent + linegap; + descent = -descent + linegap; - for(int i=32;i<1024;i++) { - for(int j=32;j<1024;j++) { + for (int i = 32; i < 1024; i++) { + for (int j = 32; j < 1024; j++) { - int kern = stbtt_GetCodepointKernAdvance(&info, i,j); - if (kern!=0) { + int kern = stbtt_GetCodepointKernAdvance(&info, i, j); + if (kern != 0) { KerningPairKey kpk; - kpk.A=i; - kpk.B=j; - kerning_map[kpk]=kern; + kpk.A = i; + kpk.B = j; + kerning_map[kpk] = kern; } } } @@ -90,21 +90,20 @@ void DynamicFontData::set_font_data(const PoolVector<uint8_t>& p_font) { Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(int p_size) { - ERR_FAIL_COND_V(!valid,Ref<DynamicFontAtSize>()); + ERR_FAIL_COND_V(!valid, Ref<DynamicFontAtSize>()); if (size_cache.has(p_size)) { - return Ref<DynamicFontAtSize>( size_cache[p_size] ); + return Ref<DynamicFontAtSize>(size_cache[p_size]); } - Ref<DynamicFontAtSize> dfas; dfas.instance(); - dfas->font=Ref<DynamicFontData>( this ); + dfas->font = Ref<DynamicFontData>(this); - size_cache[p_size]=dfas.ptr(); + size_cache[p_size] = dfas.ptr(); - dfas->size=p_size; + dfas->size = p_size; lock(); @@ -113,100 +112,90 @@ Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(int p_size) { unlock(); return dfas; - } -DynamicFontData::DynamicFontData() -{ - last_data_ptr=NULL; - valid=false; +DynamicFontData::DynamicFontData() { + last_data_ptr = NULL; + valid = false; } -DynamicFontData::~DynamicFontData() -{ - +DynamicFontData::~DynamicFontData() { } - - //////////////////// float DynamicFontAtSize::get_height() const { - return (font->ascent+font->descent)*scale; + return (font->ascent + font->descent) * scale; } float DynamicFontAtSize::get_ascent() const { - return font->ascent*scale; + return font->ascent * scale; } float DynamicFontAtSize::get_descent() const { - return font->descent*scale; + return font->descent * scale; } -Size2 DynamicFontAtSize::get_char_size(CharType p_char,CharType p_next) const { +Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next) const { - const_cast<DynamicFontAtSize*>(this)->_update_char(p_char); + const_cast<DynamicFontAtSize *>(this)->_update_char(p_char); const Character *c = char_map.getptr(p_char); - ERR_FAIL_COND_V(!c,Size2()); + ERR_FAIL_COND_V(!c, Size2()); - Size2 ret( c->advance, get_height()); + Size2 ret(c->advance, get_height()); if (p_next) { DynamicFontData::KerningPairKey kpk; - kpk.A=p_char; - kpk.B=p_next; + kpk.A = p_char; + kpk.B = p_next; - const Map<DynamicFontData::KerningPairKey,int>::Element *K=font->kerning_map.find(kpk); + const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk); if (K) { - ret.x+=K->get()*scale; + ret.x += K->get() * scale; } - } return ret; } +float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const { -float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate) const { + const_cast<DynamicFontAtSize *>(this)->_update_char(p_char); - const_cast<DynamicFontAtSize*>(this)->_update_char(p_char); - - const Character * c = char_map.getptr(p_char); + const Character *c = char_map.getptr(p_char); if (!c) { return 0; } - Point2 cpos=p_pos; - cpos.x+=c->h_align; - cpos.y-=get_ascent(); - cpos.y+=c->v_align; - ERR_FAIL_COND_V( c->texture_idx<-1 || c->texture_idx>=textures.size(),0); - if (c->texture_idx!=-1) - VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, c->rect.size ), textures[c->texture_idx].texture->get_rid(),c->rect, p_modulate ); + Point2 cpos = p_pos; + cpos.x += c->h_align; + cpos.y -= get_ascent(); + cpos.y += c->v_align; + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0); + if (c->texture_idx != -1) + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx].texture->get_rid(), c->rect, p_modulate); //textures[c->texture_idx].texture->draw(p_canvas_item,Vector2()); float ret = c->advance; if (p_next) { DynamicFontData::KerningPairKey kpk; - kpk.A=p_char; - kpk.B=p_next; + kpk.A = p_char; + kpk.B = p_next; - const Map<DynamicFontData::KerningPairKey,int>::Element *K=font->kerning_map.find(kpk); + const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk); if (K) { - ret+=K->get()*scale; + ret += K->get() * scale; } - } return ret; } - void DynamicFontAtSize::_update_char(CharType p_char) { if (char_map.has(p_char)) @@ -214,9 +203,8 @@ void DynamicFontAtSize::_update_char(CharType p_char) { font->lock(); - - int w,h,xofs,yofs; - unsigned char * cpbitmap = stbtt_GetCodepointBitmap(&font->info, scale, scale, p_char, &w, &h, &xofs, &yofs ); + int w, h, xofs, yofs; + unsigned char *cpbitmap = stbtt_GetCodepointBitmap(&font->info, scale, scale, p_char, &w, &h, &xofs, &yofs); if (!cpbitmap) { //no glyph @@ -225,123 +213,120 @@ void DynamicFontAtSize::_update_char(CharType p_char) { stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0); //print_line("char has no bitmap: "+itos(p_char)+" but advance is "+itos(advance*scale)); Character ch; - ch.texture_idx=-1; - ch.advance=advance*scale; - ch.h_align=0; - ch.v_align=0; + ch.texture_idx = -1; + ch.advance = advance * scale; + ch.h_align = 0; + ch.v_align = 0; - char_map[p_char]=ch; + char_map[p_char] = ch; font->unlock(); return; } - int mw=w+rect_margin*2; - int mh=h+rect_margin*2; + int mw = w + rect_margin * 2; + int mh = h + rect_margin * 2; - if (mw>4096 || mh>4096) { + if (mw > 4096 || mh > 4096) { - stbtt_FreeBitmap(cpbitmap,NULL); + stbtt_FreeBitmap(cpbitmap, NULL); font->unlock(); - ERR_FAIL_COND(mw>4096); - ERR_FAIL_COND(mh>4096); + ERR_FAIL_COND(mw > 4096); + ERR_FAIL_COND(mh > 4096); } //find a texture to fit this... - int tex_index=-1; - int tex_x=0; - int tex_y=0; + int tex_index = -1; + int tex_x = 0; + int tex_y = 0; - for(int i=0;i<textures.size();i++) { + for (int i = 0; i < textures.size(); i++) { - CharTexture &ct=textures[i]; + CharTexture &ct = textures[i]; if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture continue; - tex_y=0x7FFFFFFF; - tex_x=0; + tex_y = 0x7FFFFFFF; + tex_x = 0; - for(int j=0;j<ct.texture_size-mw;j++) { + for (int j = 0; j < ct.texture_size - mw; j++) { - int max_y=0; + int max_y = 0; - for(int k=j;k<j+mw;k++) { + for (int k = j; k < j + mw; k++) { int y = ct.offsets[k]; - if (y>max_y) - max_y=y; + if (y > max_y) + max_y = y; } - if (max_y<tex_y) { - tex_y=max_y; - tex_x=j; + if (max_y < tex_y) { + tex_y = max_y; + tex_x = j; } } - if (tex_y==0x7FFFFFFF || tex_y+mh > ct.texture_size) + if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size) continue; //fail, could not fit it here - tex_index=i; + tex_index = i; break; } //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" X: "+itos(tex_x)+" Y: "+itos(tex_y)); - if (tex_index==-1) { + if (tex_index == -1) { //could not find texture to fit, create one tex_x = 0; tex_y = 0; - int texsize = MAX(size*8,256); - if (mw>texsize) - texsize=mw; //special case, adapt to it? - if (mh>texsize) - texsize=mh; //special case, adapt to it? - - texsize=nearest_power_of_2(texsize); + int texsize = MAX(size * 8, 256); + if (mw > texsize) + texsize = mw; //special case, adapt to it? + if (mh > texsize) + texsize = mh; //special case, adapt to it? - texsize=MIN(texsize,4096); + texsize = nearest_power_of_2(texsize); + texsize = MIN(texsize, 4096); CharTexture tex; - tex.texture_size=texsize; - tex.imgdata.resize(texsize*texsize*2); //grayscale alpha + tex.texture_size = texsize; + tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha { //zero texture PoolVector<uint8_t>::Write w = tex.imgdata.write(); - ERR_FAIL_COND(texsize*texsize*2 > tex.imgdata.size()); - for(int i=0;i<texsize*texsize*2;i++) { - w[i]=0; + ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size()); + for (int i = 0; i < texsize * texsize * 2; i++) { + w[i] = 0; } } tex.offsets.resize(texsize); - for(int i=0;i<texsize;i++) //zero offsets - tex.offsets[i]=0; + for (int i = 0; i < texsize; i++) //zero offsets + tex.offsets[i] = 0; textures.push_back(tex); - tex_index=textures.size()-1; - + tex_index = textures.size() - 1; } - //fit character in char texture - CharTexture &tex=textures[tex_index]; + CharTexture &tex = textures[tex_index]; { PoolVector<uint8_t>::Write wr = tex.imgdata.write(); - for(int i=0;i<h;i++) { - for(int j=0;j<w;j++) { + for (int i = 0; i < h; i++) { + for (int j = 0; j < w; j++) { - int ofs = ( (i+tex_y+rect_margin)*tex.texture_size+j+tex_x+rect_margin)*2; + int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2; ERR_FAIL_COND(ofs >= tex.imgdata.size()); - wr[ofs+0]=255; //grayscale as 1 - wr[ofs+1]=cpbitmap[i*w+j]; //alpha as 0 + wr[ofs + 0] = 255; //grayscale as 1 + wr[ofs + 1] = cpbitmap[i * w + j]; //alpha as 0 } } } @@ -349,53 +334,49 @@ void DynamicFontAtSize::_update_char(CharType p_char) { //blit to image and texture { - Image img(tex.texture_size,tex.texture_size,0,Image::FORMAT_LA8,tex.imgdata); + Image img(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata); if (tex.texture.is_null()) { tex.texture.instance(); - tex.texture->create_from_image(img,Texture::FLAG_FILTER); + tex.texture->create_from_image(img, Texture::FLAG_FILTER); } else { tex.texture->set_data(img); //update } - } - // update height array - for(int k=tex_x;k<tex_x+mw;k++) { + for (int k = tex_x; k < tex_x + mw; k++) { - tex.offsets[k]=tex_y+mh; + tex.offsets[k] = tex_y + mh; } int advance; stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0); Character chr; - chr.h_align=xofs; - chr.v_align=yofs + get_ascent(); - chr.advance=advance*scale; - chr.texture_idx=tex_index; + chr.h_align = xofs; + chr.v_align = yofs + get_ascent(); + chr.advance = advance * scale; + chr.texture_idx = tex_index; - - chr.rect=Rect2(tex_x+rect_margin,tex_y+rect_margin,w,h); + chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h); //print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" RECT: "+chr.rect+" X OFS: "+itos(xofs)+" Y OFS: "+itos(yofs)); - char_map[p_char]=chr; + char_map[p_char] = chr; - stbtt_FreeBitmap(cpbitmap,NULL); + stbtt_FreeBitmap(cpbitmap, NULL); font->unlock(); - } DynamicFontAtSize::DynamicFontAtSize() { - rect_margin=1; + rect_margin = 1; } -DynamicFontAtSize::~DynamicFontAtSize(){ +DynamicFontAtSize::~DynamicFontAtSize() { ERR_FAIL_COND(!font.ptr()); font->size_cache.erase(size); @@ -403,48 +384,45 @@ DynamicFontAtSize::~DynamicFontAtSize(){ ///////////////////////// - void DynamicFont::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_font_data","data:DynamicFontData"),&DynamicFont::set_font_data); - ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"),&DynamicFont::get_font_data); + ClassDB::bind_method(D_METHOD("set_font_data", "data:DynamicFontData"), &DynamicFont::set_font_data); + ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"), &DynamicFont::get_font_data); - ClassDB::bind_method(D_METHOD("set_size","data"),&DynamicFont::set_size); - ClassDB::bind_method(D_METHOD("get_size"),&DynamicFont::get_size); + ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size); + ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size); - ADD_PROPERTY(PropertyInfo(Variant::INT,"font/size"),"set_size","get_size"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"font/font",PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData"),"set_font_data","get_font_data"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "font/size"), "set_size", "get_size"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font/font", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data"); } +void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) { -void DynamicFont::set_font_data(const Ref<DynamicFontData>& p_data) { - - data=p_data; - data_at_size=data->_get_dynamic_font_at_size(size); + data = p_data; + data_at_size = data->_get_dynamic_font_at_size(size); } -Ref<DynamicFontData> DynamicFont::get_font_data() const{ +Ref<DynamicFontData> DynamicFont::get_font_data() const { return data; } -void DynamicFont::set_size(int p_size){ +void DynamicFont::set_size(int p_size) { - if (size==p_size) + if (size == p_size) return; - size=p_size; - ERR_FAIL_COND(p_size<1); + size = p_size; + ERR_FAIL_COND(p_size < 1); if (!data.is_valid()) return; - data_at_size=data->_get_dynamic_font_at_size(size); - + data_at_size = data->_get_dynamic_font_at_size(size); } -int DynamicFont::get_size() const{ +int DynamicFont::get_size() const { return size; } -float DynamicFont::get_height() const{ +float DynamicFont::get_height() const { if (!data_at_size.is_valid()) return 1; @@ -452,7 +430,7 @@ float DynamicFont::get_height() const{ return data_at_size->get_height(); } -float DynamicFont::get_ascent() const{ +float DynamicFont::get_ascent() const { if (!data_at_size.is_valid()) return 1; @@ -460,68 +438,62 @@ float DynamicFont::get_ascent() const{ return data_at_size->get_ascent(); } -float DynamicFont::get_descent() const{ +float DynamicFont::get_descent() const { if (!data_at_size.is_valid()) return 1; return data_at_size->get_descent(); - } -Size2 DynamicFont::get_char_size(CharType p_char,CharType p_next) const{ +Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const { if (!data_at_size.is_valid()) - return Size2(1,1); - - return data_at_size->get_char_size(p_char,p_next); + return Size2(1, 1); + return data_at_size->get_char_size(p_char, p_next); } -bool DynamicFont::is_distance_field_hint() const{ +bool DynamicFont::is_distance_field_hint() const { return false; } -float DynamicFont::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate) const { +float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const { if (!data_at_size.is_valid()) return 0; - return data_at_size->draw_char(p_canvas_item,p_pos,p_char,p_next,p_modulate); - + return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate); } DynamicFont::DynamicFont() { - size=16; + size = 16; } DynamicFont::~DynamicFont() { - } ///////////////////////// - -RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; - + *r_error = ERR_FILE_CANT_OPEN; - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,RES()); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, RES()); PoolVector<uint8_t> data; data.resize(f->get_len()); - ERR_FAIL_COND_V(data.size()==0,RES()); + ERR_FAIL_COND_V(data.size() == 0, RES()); { PoolVector<uint8_t>::Write w = data.write(); - f->get_buffer(w.ptr(),data.size()); + f->get_buffer(w.ptr(), data.size()); } Ref<DynamicFontData> dfd; @@ -529,7 +501,7 @@ RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String& p_ dfd->set_font_data(data); if (r_error) - *r_error=OK; + *r_error = OK; return dfd; } @@ -539,15 +511,15 @@ void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_ p_extensions->push_back("ttf"); } -bool ResourceFormatLoaderDynamicFont::handles_type(const String& p_type) const { +bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const { - return (p_type=="DynamicFontData"); + return (p_type == "DynamicFontData"); } String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const { String el = p_path.extension().to_lower(); - if (el=="ttf") + if (el == "ttf") return "DynamicFontData"; return ""; } diff --git a/scene/resources/dynamic_font_stb.h b/scene/resources/dynamic_font_stb.h index 4eb0575d8e..0c17e3a8b3 100644 --- a/scene/resources/dynamic_font_stb.h +++ b/scene/resources/dynamic_font_stb.h @@ -32,43 +32,40 @@ #ifndef FREETYPE_ENABLED #include "font.h" -#include "stb_truetype.h" #include "io/resource_loader.h" - - +#include "stb_truetype.h" class DynamicFontAtSize; class DynamicFont; class DynamicFontData : public Resource { - GDCLASS(DynamicFontData,Resource); + GDCLASS(DynamicFontData, Resource); bool valid; PoolVector<uint8_t> font_data; PoolVector<uint8_t>::Read fr; - const uint8_t* last_data_ptr; + const uint8_t *last_data_ptr; struct KerningPairKey { union { struct { - uint32_t A,B; + uint32_t A, B; }; uint64_t pair; }; - _FORCE_INLINE_ bool operator<(const KerningPairKey& p_r) const { return pair<p_r.pair; } + _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; } }; - Map<KerningPairKey,int> kerning_map; + Map<KerningPairKey, int> kerning_map; + Map<int, DynamicFontAtSize *> size_cache; - Map<int,DynamicFontAtSize*> size_cache; - -friend class DynamicFontAtSize; + friend class DynamicFontAtSize; stbtt_fontinfo info; int ascent; @@ -78,22 +75,19 @@ friend class DynamicFontAtSize; void lock(); void unlock(); -friend class DynamicFont; - + friend class DynamicFont; Ref<DynamicFontAtSize> _get_dynamic_font_at_size(int p_size); -public: - void set_font_data(const PoolVector<uint8_t>& p_font); +public: + void set_font_data(const PoolVector<uint8_t> &p_font); DynamicFontData(); ~DynamicFontData(); }; - class DynamicFontAtSize : public Reference { - GDCLASS(DynamicFontAtSize,Reference); - + GDCLASS(DynamicFontAtSize, Reference); int rect_margin; @@ -115,34 +109,31 @@ class DynamicFontAtSize : public Reference { float h_align; float advance; - Character() { texture_idx=0; v_align=0; } + Character() { + texture_idx = 0; + v_align = 0; + } }; - - - HashMap< CharType, Character > char_map; + HashMap<CharType, Character> char_map; _FORCE_INLINE_ void _update_char(CharType p_char); -friend class DynamicFontData; + friend class DynamicFontData; Ref<DynamicFontData> font; float scale; int size; protected: - public: - float get_height() const; float get_ascent() const; float get_descent() const; - Size2 get_char_size(CharType p_char,CharType p_next=0) const; - - float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const; - + Size2 get_char_size(CharType p_char, CharType p_next = 0) const; + float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const; DynamicFontAtSize(); ~DynamicFontAtSize(); @@ -152,20 +143,17 @@ public: class DynamicFont : public Font { - GDCLASS( DynamicFont, Font ); + GDCLASS(DynamicFont, Font); Ref<DynamicFontData> data; Ref<DynamicFontAtSize> data_at_size; int size; - protected: - static void _bind_methods(); public: - - void set_font_data(const Ref<DynamicFontData>& p_data); + void set_font_data(const Ref<DynamicFontData> &p_data); Ref<DynamicFontData> get_font_data() const; void set_size(int p_size); @@ -176,31 +164,25 @@ public: virtual float get_ascent() const; virtual float get_descent() const; - virtual Size2 get_char_size(CharType p_char,CharType p_next=0) const; + virtual Size2 get_char_size(CharType p_char, CharType p_next = 0) const; virtual bool is_distance_field_hint() const; - virtual float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const; + virtual float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const; DynamicFont(); ~DynamicFont(); - }; - - ///////////// class ResourceFormatLoaderDynamicFont : public ResourceFormatLoader { public: - - virtual RES load(const String &p_path,const String& p_original_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; - 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; - }; - #endif #endif // DYNAMICFONT_H diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp index f44b37f6f5..b134d8052b 100644 --- a/scene/resources/environment.cpp +++ b/scene/resources/environment.cpp @@ -27,76 +27,75 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "environment.h" -#include "texture.h" #include "global_config.h" #include "servers/visual_server.h" +#include "texture.h" RID Environment::get_rid() const { return environment; } - void Environment::set_background(BGMode p_bg) { - bg_mode=p_bg; - VS::get_singleton()->environment_set_background(environment,VS::EnvironmentBG(p_bg)); + bg_mode = p_bg; + VS::get_singleton()->environment_set_background(environment, VS::EnvironmentBG(p_bg)); _change_notify(); } -void Environment::set_skybox(const Ref<SkyBox> &p_skybox){ +void Environment::set_skybox(const Ref<SkyBox> &p_skybox) { - bg_skybox=p_skybox; + bg_skybox = p_skybox; RID sb_rid; if (bg_skybox.is_valid()) - sb_rid=bg_skybox->get_rid(); + sb_rid = bg_skybox->get_rid(); - VS::get_singleton()->environment_set_skybox(environment,sb_rid); + VS::get_singleton()->environment_set_skybox(environment, sb_rid); } void Environment::set_skybox_scale(float p_scale) { - bg_skybox_scale=p_scale; - VS::get_singleton()->environment_set_skybox_scale(environment,p_scale); + bg_skybox_scale = p_scale; + VS::get_singleton()->environment_set_skybox_scale(environment, p_scale); } -void Environment::set_bg_color(const Color& p_color){ +void Environment::set_bg_color(const Color &p_color) { - bg_color=p_color; - VS::get_singleton()->environment_set_bg_color(environment,p_color); + bg_color = p_color; + VS::get_singleton()->environment_set_bg_color(environment, p_color); } -void Environment::set_bg_energy(float p_energy){ +void Environment::set_bg_energy(float p_energy) { - bg_energy=p_energy; - VS::get_singleton()->environment_set_bg_energy(environment,p_energy); + bg_energy = p_energy; + VS::get_singleton()->environment_set_bg_energy(environment, p_energy); } -void Environment::set_canvas_max_layer(int p_max_layer){ +void Environment::set_canvas_max_layer(int p_max_layer) { - bg_canvas_max_layer=p_max_layer; - VS::get_singleton()->environment_set_canvas_max_layer(environment,p_max_layer); + bg_canvas_max_layer = p_max_layer; + VS::get_singleton()->environment_set_canvas_max_layer(environment, p_max_layer); } -void Environment::set_ambient_light_color(const Color& p_color){ +void Environment::set_ambient_light_color(const Color &p_color) { - ambient_color=p_color; - VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution); + ambient_color = p_color; + VS::get_singleton()->environment_set_ambient_light(environment, ambient_color, ambient_energy, ambient_skybox_contribution); } -void Environment::set_ambient_light_energy(float p_energy){ +void Environment::set_ambient_light_energy(float p_energy) { - ambient_energy=p_energy; - VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution); + ambient_energy = p_energy; + VS::get_singleton()->environment_set_ambient_light(environment, ambient_color, ambient_energy, ambient_skybox_contribution); } -void Environment::set_ambient_light_skybox_contribution(float p_energy){ +void Environment::set_ambient_light_skybox_contribution(float p_energy) { - ambient_skybox_contribution=p_energy; - VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution); + ambient_skybox_contribution = p_energy; + VS::get_singleton()->environment_set_ambient_light(environment, ambient_color, ambient_energy, ambient_skybox_contribution); } -Environment::BGMode Environment::get_background() const{ +Environment::BGMode Environment::get_background() const { return bg_mode; } -Ref<SkyBox> Environment::get_skybox() const{ +Ref<SkyBox> Environment::get_skybox() const { return bg_skybox; } @@ -106,60 +105,57 @@ float Environment::get_skybox_scale() const { return bg_skybox_scale; } -Color Environment::get_bg_color() const{ +Color Environment::get_bg_color() const { return bg_color; } -float Environment::get_bg_energy() const{ +float Environment::get_bg_energy() const { return bg_energy; } -int Environment::get_canvas_max_layer() const{ +int Environment::get_canvas_max_layer() const { return bg_canvas_max_layer; } -Color Environment::get_ambient_light_color() const{ +Color Environment::get_ambient_light_color() const { return ambient_color; } -float Environment::get_ambient_light_energy() const{ +float Environment::get_ambient_light_energy() const { return ambient_energy; } -float Environment::get_ambient_light_skybox_contribution() const{ +float Environment::get_ambient_light_skybox_contribution() const { return ambient_skybox_contribution; } - - void Environment::set_tonemapper(ToneMapper p_tone_mapper) { - tone_mapper=p_tone_mapper; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); + tone_mapper = p_tone_mapper; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } -Environment::ToneMapper Environment::get_tonemapper() const{ +Environment::ToneMapper Environment::get_tonemapper() const { return tone_mapper; } -void Environment::set_tonemap_exposure(float p_exposure){ +void Environment::set_tonemap_exposure(float p_exposure) { - tonemap_exposure=p_exposure; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); + tonemap_exposure = p_exposure; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } -float Environment::get_tonemap_exposure() const{ +float Environment::get_tonemap_exposure() const { return tonemap_exposure; } -void Environment::set_tonemap_white(float p_white){ - - tonemap_white=p_white; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); +void Environment::set_tonemap_white(float p_white) { + tonemap_white = p_white; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } float Environment::get_tonemap_white() const { @@ -168,9 +164,8 @@ float Environment::get_tonemap_white() const { void Environment::set_tonemap_auto_exposure(bool p_enabled) { - tonemap_auto_exposure=p_enabled; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); - + tonemap_auto_exposure = p_enabled; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } bool Environment::get_tonemap_auto_exposure() const { @@ -179,9 +174,8 @@ bool Environment::get_tonemap_auto_exposure() const { void Environment::set_tonemap_auto_exposure_max(float p_auto_exposure_max) { - tonemap_auto_exposure_max=p_auto_exposure_max; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); - + tonemap_auto_exposure_max = p_auto_exposure_max; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_max() const { @@ -190,9 +184,8 @@ float Environment::get_tonemap_auto_exposure_max() const { void Environment::set_tonemap_auto_exposure_min(float p_auto_exposure_min) { - tonemap_auto_exposure_min=p_auto_exposure_min; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); - + tonemap_auto_exposure_min = p_auto_exposure_min; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_min() const { @@ -201,9 +194,8 @@ float Environment::get_tonemap_auto_exposure_min() const { void Environment::set_tonemap_auto_exposure_speed(float p_auto_exposure_speed) { - tonemap_auto_exposure_speed=p_auto_exposure_speed; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); - + tonemap_auto_exposure_speed = p_auto_exposure_speed; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_speed() const { @@ -212,9 +204,8 @@ float Environment::get_tonemap_auto_exposure_speed() const { void Environment::set_tonemap_auto_exposure_grey(float p_auto_exposure_grey) { - tonemap_auto_exposure_grey=p_auto_exposure_grey; - VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); - + tonemap_auto_exposure_grey = p_auto_exposure_grey; + VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_grey() const { @@ -223,8 +214,8 @@ float Environment::get_tonemap_auto_exposure_grey() const { void Environment::set_adjustment_enable(bool p_enable) { - adjustment_enabled=p_enable; - VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); + adjustment_enabled = p_enable; + VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID()); } bool Environment::is_adjustment_enabled() const { @@ -232,12 +223,10 @@ bool Environment::is_adjustment_enabled() const { return adjustment_enabled; } - void Environment::set_adjustment_brightness(float p_brightness) { - adjustment_brightness=p_brightness; - VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); - + adjustment_brightness = p_brightness; + VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID()); } float Environment::get_adjustment_brightness() const { @@ -246,9 +235,8 @@ float Environment::get_adjustment_brightness() const { void Environment::set_adjustment_contrast(float p_contrast) { - adjustment_contrast=p_contrast; - VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); - + adjustment_contrast = p_contrast; + VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID()); } float Environment::get_adjustment_contrast() const { @@ -257,65 +245,60 @@ float Environment::get_adjustment_contrast() const { void Environment::set_adjustment_saturation(float p_saturation) { - adjustment_saturation=p_saturation; - VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); - + adjustment_saturation = p_saturation; + VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID()); } float Environment::get_adjustment_saturation() const { return adjustment_saturation; } -void Environment::set_adjustment_color_correction(const Ref<Texture>& p_ramp) { - - adjustment_color_correction=p_ramp; - VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); +void Environment::set_adjustment_color_correction(const Ref<Texture> &p_ramp) { + adjustment_color_correction = p_ramp; + VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID()); } Ref<Texture> Environment::get_adjustment_color_correction() const { return adjustment_color_correction; } +void Environment::_validate_property(PropertyInfo &property) const { -void Environment::_validate_property(PropertyInfo& property) const { - - if (property.name=="background/skybox" || property.name=="background/skybox_scale" || property.name=="ambient_light/skybox_contribution") { - if (bg_mode!=BG_SKYBOX) { - property.usage=PROPERTY_USAGE_NOEDITOR; + if (property.name == "background/skybox" || property.name == "background/skybox_scale" || property.name == "ambient_light/skybox_contribution") { + if (bg_mode != BG_SKYBOX) { + property.usage = PROPERTY_USAGE_NOEDITOR; } } - if (property.name=="background/color") { - if (bg_mode!=BG_COLOR) { - property.usage=PROPERTY_USAGE_NOEDITOR; + if (property.name == "background/color") { + if (bg_mode != BG_COLOR) { + property.usage = PROPERTY_USAGE_NOEDITOR; } } - if (property.name=="background/canvas_max_layer") { - if (bg_mode!=BG_CANVAS) { - property.usage=PROPERTY_USAGE_NOEDITOR; + if (property.name == "background/canvas_max_layer") { + if (bg_mode != BG_CANVAS) { + property.usage = PROPERTY_USAGE_NOEDITOR; } } - } void Environment::set_ssr_enabled(bool p_enable) { - ssr_enabled=p_enable; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); + ssr_enabled = p_enable; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } -bool Environment::is_ssr_enabled() const{ +bool Environment::is_ssr_enabled() const { return ssr_enabled; } -void Environment::set_ssr_max_steps(int p_steps){ - - ssr_max_steps=p_steps; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); +void Environment::set_ssr_max_steps(int p_steps) { + ssr_max_steps = p_steps; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } int Environment::get_ssr_max_steps() const { @@ -324,9 +307,8 @@ int Environment::get_ssr_max_steps() const { void Environment::set_ssr_accel(float p_accel) { - ssr_accel=p_accel; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); - + ssr_accel = p_accel; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } float Environment::get_ssr_accel() const { @@ -335,9 +317,8 @@ float Environment::get_ssr_accel() const { void Environment::set_ssr_fade(float p_fade) { - ssr_fade=p_fade; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); - + ssr_fade = p_fade; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } float Environment::get_ssr_fade() const { @@ -346,9 +327,8 @@ float Environment::get_ssr_fade() const { void Environment::set_ssr_depth_tolerance(float p_depth_tolerance) { - ssr_depth_tolerance=p_depth_tolerance; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); - + ssr_depth_tolerance = p_depth_tolerance; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } float Environment::get_ssr_depth_tolerance() const { @@ -357,9 +337,8 @@ float Environment::get_ssr_depth_tolerance() const { void Environment::set_ssr_smooth(bool p_enable) { - ssr_smooth=p_enable; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); - + ssr_smooth = p_enable; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } bool Environment::is_ssr_smooth() const { @@ -368,9 +347,8 @@ bool Environment::is_ssr_smooth() const { void Environment::set_ssr_rough(bool p_enable) { - ssr_roughness=p_enable; - VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); - + ssr_roughness = p_enable; + VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness); } bool Environment::is_ssr_rough() const { @@ -379,84 +357,80 @@ bool Environment::is_ssr_rough() const { void Environment::set_ssao_enabled(bool p_enable) { - ssao_enabled=p_enable; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); - + ssao_enabled = p_enable; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -bool Environment::is_ssao_enabled() const{ +bool Environment::is_ssao_enabled() const { return ssao_enabled; } -void Environment::set_ssao_radius(float p_radius){ +void Environment::set_ssao_radius(float p_radius) { - ssao_radius=p_radius; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_radius = p_radius; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -float Environment::get_ssao_radius() const{ +float Environment::get_ssao_radius() const { return ssao_radius; } +void Environment::set_ssao_intensity(float p_intensity) { -void Environment::set_ssao_intensity(float p_intensity){ - - ssao_intensity=p_intensity; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_intensity = p_intensity; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -float Environment::get_ssao_intensity() const{ +float Environment::get_ssao_intensity() const { return ssao_intensity; } -void Environment::set_ssao_radius2(float p_radius){ +void Environment::set_ssao_radius2(float p_radius) { - ssao_radius2=p_radius; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_radius2 = p_radius; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -float Environment::get_ssao_radius2() const{ +float Environment::get_ssao_radius2() const { return ssao_radius2; } +void Environment::set_ssao_intensity2(float p_intensity) { -void Environment::set_ssao_intensity2(float p_intensity){ - - ssao_intensity2=p_intensity; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_intensity2 = p_intensity; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -float Environment::get_ssao_intensity2() const{ +float Environment::get_ssao_intensity2() const { return ssao_intensity2; } -void Environment::set_ssao_bias(float p_bias){ +void Environment::set_ssao_bias(float p_bias) { - ssao_bias=p_bias; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_bias = p_bias; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -float Environment::get_ssao_bias() const{ +float Environment::get_ssao_bias() const { return ssao_bias; } -void Environment::set_ssao_direct_light_affect(float p_direct_light_affect){ +void Environment::set_ssao_direct_light_affect(float p_direct_light_affect) { - ssao_direct_light_affect=p_direct_light_affect; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_direct_light_affect = p_direct_light_affect; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } -float Environment::get_ssao_direct_light_affect() const{ +float Environment::get_ssao_direct_light_affect() const { return ssao_direct_light_affect; } +void Environment::set_ssao_color(const Color &p_color) { -void Environment::set_ssao_color(const Color& p_color) { - - ssao_color=p_color; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_color = p_color; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } Color Environment::get_ssao_color() const { @@ -466,8 +440,8 @@ Color Environment::get_ssao_color() const { void Environment::set_ssao_blur(bool p_enable) { - ssao_blur=p_enable; - VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); + ssao_blur = p_enable; + VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur); } bool Environment::is_ssao_blur_enabled() const { @@ -476,110 +450,102 @@ bool Environment::is_ssao_blur_enabled() const { void Environment::set_glow_enabled(bool p_enabled) { - glow_enabled=p_enabled; - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_enabled = p_enabled; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -bool Environment::is_glow_enabled() const{ +bool Environment::is_glow_enabled() const { return glow_enabled; } -void Environment::set_glow_level(int p_level,bool p_enabled){ +void Environment::set_glow_level(int p_level, bool p_enabled) { - ERR_FAIL_INDEX(p_level,VS::MAX_GLOW_LEVELS); + ERR_FAIL_INDEX(p_level, VS::MAX_GLOW_LEVELS); if (p_enabled) - glow_levels|=(1<<p_level); + glow_levels |= (1 << p_level); else - glow_levels&=~(1<<p_level); - - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_levels &= ~(1 << p_level); + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -bool Environment::is_glow_level_enabled(int p_level) const{ +bool Environment::is_glow_level_enabled(int p_level) const { - ERR_FAIL_INDEX_V(p_level,VS::MAX_GLOW_LEVELS,false); + ERR_FAIL_INDEX_V(p_level, VS::MAX_GLOW_LEVELS, false); - return glow_levels&(1<<p_level); + return glow_levels & (1 << p_level); } -void Environment::set_glow_intensity(float p_intensity){ +void Environment::set_glow_intensity(float p_intensity) { - glow_intensity=p_intensity; - - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_intensity = p_intensity; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -float Environment::get_glow_intensity() const{ +float Environment::get_glow_intensity() const { return glow_intensity; } -void Environment::set_glow_strength(float p_strength){ - - glow_strength=p_strength; - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); +void Environment::set_glow_strength(float p_strength) { + glow_strength = p_strength; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -float Environment::get_glow_strength() const{ +float Environment::get_glow_strength() const { return glow_strength; } -void Environment::set_glow_bloom(float p_treshold){ +void Environment::set_glow_bloom(float p_treshold) { - glow_bloom=p_treshold; - - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_bloom = p_treshold; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -float Environment::get_glow_bloom() const{ +float Environment::get_glow_bloom() const { return glow_bloom; } -void Environment::set_glow_blend_mode(GlowBlendMode p_mode){ - - glow_blend_mode=p_mode; +void Environment::set_glow_blend_mode(GlowBlendMode p_mode) { - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_blend_mode = p_mode; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -Environment::GlowBlendMode Environment::get_glow_blend_mode() const{ +Environment::GlowBlendMode Environment::get_glow_blend_mode() const { return glow_blend_mode; } -void Environment::set_glow_hdr_bleed_treshold(float p_treshold){ +void Environment::set_glow_hdr_bleed_treshold(float p_treshold) { - glow_hdr_bleed_treshold=p_treshold; - - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_hdr_bleed_treshold = p_treshold; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -float Environment::get_glow_hdr_bleed_treshold() const{ +float Environment::get_glow_hdr_bleed_treshold() const { return glow_hdr_bleed_treshold; } -void Environment::set_glow_hdr_bleed_scale(float p_scale){ - - glow_hdr_bleed_scale=p_scale; +void Environment::set_glow_hdr_bleed_scale(float p_scale) { - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); + glow_hdr_bleed_scale = p_scale; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } -float Environment::get_glow_hdr_bleed_scale() const{ +float Environment::get_glow_hdr_bleed_scale() const { return glow_hdr_bleed_scale; } void Environment::set_glow_bicubic_upscale(bool p_enable) { - glow_bicubic_upscale=p_enable; - VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); - + glow_bicubic_upscale = p_enable; + VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale); } bool Environment::is_glow_bicubic_upscale_enabled() const { @@ -587,54 +553,51 @@ bool Environment::is_glow_bicubic_upscale_enabled() const { return glow_bicubic_upscale; } - void Environment::set_dof_blur_far_enabled(bool p_enable) { - dof_blur_far_enabled=p_enable; - VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); + dof_blur_far_enabled = p_enable; + VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } -bool Environment::is_dof_blur_far_enabled() const{ +bool Environment::is_dof_blur_far_enabled() const { return dof_blur_far_enabled; } -void Environment::set_dof_blur_far_distance(float p_distance){ - - dof_blur_far_distance=p_distance; - VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); +void Environment::set_dof_blur_far_distance(float p_distance) { + dof_blur_far_distance = p_distance; + VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } -float Environment::get_dof_blur_far_distance() const{ +float Environment::get_dof_blur_far_distance() const { return dof_blur_far_distance; } -void Environment::set_dof_blur_far_transition(float p_distance){ +void Environment::set_dof_blur_far_transition(float p_distance) { - dof_blur_far_transition=p_distance; - VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); + dof_blur_far_transition = p_distance; + VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } -float Environment::get_dof_blur_far_transition() const{ +float Environment::get_dof_blur_far_transition() const { return dof_blur_far_transition; } -void Environment::set_dof_blur_far_amount(float p_amount){ - - dof_blur_far_amount=p_amount; - VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); +void Environment::set_dof_blur_far_amount(float p_amount) { + dof_blur_far_amount = p_amount; + VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } -float Environment::get_dof_blur_far_amount() const{ +float Environment::get_dof_blur_far_amount() const { return dof_blur_far_amount; } void Environment::set_dof_blur_far_quality(DOFBlurQuality p_quality) { - dof_blur_far_quality=p_quality; - VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); + dof_blur_far_quality = p_quality; + VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } Environment::DOFBlurQuality Environment::get_dof_blur_far_quality() const { @@ -642,55 +605,54 @@ Environment::DOFBlurQuality Environment::get_dof_blur_far_quality() const { return dof_blur_far_quality; } - void Environment::set_dof_blur_near_enabled(bool p_enable) { - dof_blur_near_enabled=p_enable; - VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); + dof_blur_near_enabled = p_enable; + VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } -bool Environment::is_dof_blur_near_enabled() const{ +bool Environment::is_dof_blur_near_enabled() const { return dof_blur_near_enabled; } -void Environment::set_dof_blur_near_distance(float p_distance){ +void Environment::set_dof_blur_near_distance(float p_distance) { - dof_blur_near_distance=p_distance; - VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); + dof_blur_near_distance = p_distance; + VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } -float Environment::get_dof_blur_near_distance() const{ +float Environment::get_dof_blur_near_distance() const { return dof_blur_near_distance; } -void Environment::set_dof_blur_near_transition(float p_distance){ +void Environment::set_dof_blur_near_transition(float p_distance) { - dof_blur_near_transition=p_distance; - VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); + dof_blur_near_transition = p_distance; + VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } -float Environment::get_dof_blur_near_transition() const{ +float Environment::get_dof_blur_near_transition() const { return dof_blur_near_transition; } -void Environment::set_dof_blur_near_amount(float p_amount){ +void Environment::set_dof_blur_near_amount(float p_amount) { - dof_blur_near_amount=p_amount; - VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); + dof_blur_near_amount = p_amount; + VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } -float Environment::get_dof_blur_near_amount() const{ +float Environment::get_dof_blur_near_amount() const { return dof_blur_near_amount; } void Environment::set_dof_blur_near_quality(DOFBlurQuality p_quality) { - dof_blur_near_quality=p_quality; - VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); + dof_blur_near_quality = p_quality; + VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } Environment::DOFBlurQuality Environment::get_dof_blur_near_quality() const { @@ -698,263 +660,255 @@ Environment::DOFBlurQuality Environment::get_dof_blur_near_quality() const { return dof_blur_near_quality; } - void Environment::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_background","mode"),&Environment::set_background); - ClassDB::bind_method(D_METHOD("set_skybox","skybox:CubeMap"),&Environment::set_skybox); - ClassDB::bind_method(D_METHOD("set_skybox_scale","scale"),&Environment::set_skybox_scale); - ClassDB::bind_method(D_METHOD("set_bg_color","color"),&Environment::set_bg_color); - ClassDB::bind_method(D_METHOD("set_bg_energy","energy"),&Environment::set_bg_energy); - ClassDB::bind_method(D_METHOD("set_canvas_max_layer","layer"),&Environment::set_canvas_max_layer); - ClassDB::bind_method(D_METHOD("set_ambient_light_color","color"),&Environment::set_ambient_light_color); - ClassDB::bind_method(D_METHOD("set_ambient_light_energy","energy"),&Environment::set_ambient_light_energy); - ClassDB::bind_method(D_METHOD("set_ambient_light_skybox_contribution","energy"),&Environment::set_ambient_light_skybox_contribution); - - - ClassDB::bind_method(D_METHOD("get_background"),&Environment::get_background); - ClassDB::bind_method(D_METHOD("get_skybox:CubeMap"),&Environment::get_skybox); - ClassDB::bind_method(D_METHOD("get_skybox_scale"),&Environment::get_skybox_scale); - ClassDB::bind_method(D_METHOD("get_bg_color"),&Environment::get_bg_color); - ClassDB::bind_method(D_METHOD("get_bg_energy"),&Environment::get_bg_energy); - ClassDB::bind_method(D_METHOD("get_canvas_max_layer"),&Environment::get_canvas_max_layer); - ClassDB::bind_method(D_METHOD("get_ambient_light_color"),&Environment::get_ambient_light_color); - ClassDB::bind_method(D_METHOD("get_ambient_light_energy"),&Environment::get_ambient_light_energy); - ClassDB::bind_method(D_METHOD("get_ambient_light_skybox_contribution"),&Environment::get_ambient_light_skybox_contribution); - - - ADD_GROUP("Background","background_"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"background_mode",PROPERTY_HINT_ENUM,"Clear Color,Custom Color,Skybox,Canvas,Keep"),"set_background","get_background") ; - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"background_skybox",PROPERTY_HINT_RESOURCE_TYPE,"SkyBox"),"set_skybox","get_skybox") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"background_skybox_scale",PROPERTY_HINT_RANGE,"0,32,0.01"),"set_skybox_scale","get_skybox_scale") ; - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"background_color"),"set_bg_color","get_bg_color") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"background_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_bg_energy","get_bg_energy") ; - ADD_PROPERTY(PropertyInfo(Variant::INT,"background_canvas_max_layer",PROPERTY_HINT_RANGE,"-1000,1000,1"),"set_canvas_max_layer","get_canvas_max_layer") ; - ADD_GROUP("Ambient Light","ambient_light_"); - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"ambient_light_color"),"set_ambient_light_color","get_ambient_light_color") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ambient_light_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_ambient_light_energy","get_ambient_light_energy") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ambient_light_skybox_contribution",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_ambient_light_skybox_contribution","get_ambient_light_skybox_contribution") ; - - - ClassDB::bind_method(D_METHOD("set_ssr_enabled","enabled"),&Environment::set_ssr_enabled); - ClassDB::bind_method(D_METHOD("is_ssr_enabled"),&Environment::is_ssr_enabled); - - ClassDB::bind_method(D_METHOD("set_ssr_max_steps","max_steps"),&Environment::set_ssr_max_steps); - ClassDB::bind_method(D_METHOD("get_ssr_max_steps"),&Environment::get_ssr_max_steps); - - ClassDB::bind_method(D_METHOD("set_ssr_accel","accel"),&Environment::set_ssr_accel); - ClassDB::bind_method(D_METHOD("get_ssr_accel"),&Environment::get_ssr_accel); - - ClassDB::bind_method(D_METHOD("set_ssr_fade","fade"),&Environment::set_ssr_fade); - ClassDB::bind_method(D_METHOD("get_ssr_fade"),&Environment::get_ssr_fade); - - ClassDB::bind_method(D_METHOD("set_ssr_depth_tolerance","depth_tolerance"),&Environment::set_ssr_depth_tolerance); - ClassDB::bind_method(D_METHOD("get_ssr_depth_tolerance"),&Environment::get_ssr_depth_tolerance); - - ClassDB::bind_method(D_METHOD("set_ssr_smooth","smooth"),&Environment::set_ssr_smooth); - ClassDB::bind_method(D_METHOD("is_ssr_smooth"),&Environment::is_ssr_smooth); - - ClassDB::bind_method(D_METHOD("set_ssr_rough","rough"),&Environment::set_ssr_rough); - ClassDB::bind_method(D_METHOD("is_ssr_rough"),&Environment::is_ssr_rough); - - ADD_GROUP("SS Reflections","ss_reflections_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_enabled"),"set_ssr_enabled","is_ssr_enabled") ; - ADD_PROPERTY(PropertyInfo(Variant::INT,"ss_reflections_max_steps",PROPERTY_HINT_RANGE,"1,512,1"),"set_ssr_max_steps","get_ssr_max_steps") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_accel",PROPERTY_HINT_RANGE,"0,4,0.01"),"set_ssr_accel","get_ssr_accel") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_fade",PROPERTY_HINT_EXP_EASING),"set_ssr_fade","get_ssr_fade") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_depth_tolerance",PROPERTY_HINT_RANGE,"0.1,128,0.1"),"set_ssr_depth_tolerance","get_ssr_depth_tolerance") ; - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_accel_smooth"),"set_ssr_smooth","is_ssr_smooth") ; - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_roughness"),"set_ssr_rough","is_ssr_rough") ; + ClassDB::bind_method(D_METHOD("set_background", "mode"), &Environment::set_background); + ClassDB::bind_method(D_METHOD("set_skybox", "skybox:CubeMap"), &Environment::set_skybox); + ClassDB::bind_method(D_METHOD("set_skybox_scale", "scale"), &Environment::set_skybox_scale); + ClassDB::bind_method(D_METHOD("set_bg_color", "color"), &Environment::set_bg_color); + ClassDB::bind_method(D_METHOD("set_bg_energy", "energy"), &Environment::set_bg_energy); + ClassDB::bind_method(D_METHOD("set_canvas_max_layer", "layer"), &Environment::set_canvas_max_layer); + ClassDB::bind_method(D_METHOD("set_ambient_light_color", "color"), &Environment::set_ambient_light_color); + ClassDB::bind_method(D_METHOD("set_ambient_light_energy", "energy"), &Environment::set_ambient_light_energy); + ClassDB::bind_method(D_METHOD("set_ambient_light_skybox_contribution", "energy"), &Environment::set_ambient_light_skybox_contribution); + + ClassDB::bind_method(D_METHOD("get_background"), &Environment::get_background); + ClassDB::bind_method(D_METHOD("get_skybox:CubeMap"), &Environment::get_skybox); + ClassDB::bind_method(D_METHOD("get_skybox_scale"), &Environment::get_skybox_scale); + ClassDB::bind_method(D_METHOD("get_bg_color"), &Environment::get_bg_color); + ClassDB::bind_method(D_METHOD("get_bg_energy"), &Environment::get_bg_energy); + ClassDB::bind_method(D_METHOD("get_canvas_max_layer"), &Environment::get_canvas_max_layer); + ClassDB::bind_method(D_METHOD("get_ambient_light_color"), &Environment::get_ambient_light_color); + ClassDB::bind_method(D_METHOD("get_ambient_light_energy"), &Environment::get_ambient_light_energy); + ClassDB::bind_method(D_METHOD("get_ambient_light_skybox_contribution"), &Environment::get_ambient_light_skybox_contribution); + + ADD_GROUP("Background", "background_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "background_mode", PROPERTY_HINT_ENUM, "Clear Color,Custom Color,Skybox,Canvas,Keep"), "set_background", "get_background"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "background_skybox", PROPERTY_HINT_RESOURCE_TYPE, "SkyBox"), "set_skybox", "get_skybox"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "background_skybox_scale", PROPERTY_HINT_RANGE, "0,32,0.01"), "set_skybox_scale", "get_skybox_scale"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "background_color"), "set_bg_color", "get_bg_color"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "background_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_bg_energy", "get_bg_energy"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "background_canvas_max_layer", PROPERTY_HINT_RANGE, "-1000,1000,1"), "set_canvas_max_layer", "get_canvas_max_layer"); + ADD_GROUP("Ambient Light", "ambient_light_"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "ambient_light_color"), "set_ambient_light_color", "get_ambient_light_color"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ambient_light_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_ambient_light_energy", "get_ambient_light_energy"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ambient_light_skybox_contribution", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_ambient_light_skybox_contribution", "get_ambient_light_skybox_contribution"); + + ClassDB::bind_method(D_METHOD("set_ssr_enabled", "enabled"), &Environment::set_ssr_enabled); + ClassDB::bind_method(D_METHOD("is_ssr_enabled"), &Environment::is_ssr_enabled); + + ClassDB::bind_method(D_METHOD("set_ssr_max_steps", "max_steps"), &Environment::set_ssr_max_steps); + ClassDB::bind_method(D_METHOD("get_ssr_max_steps"), &Environment::get_ssr_max_steps); + + ClassDB::bind_method(D_METHOD("set_ssr_accel", "accel"), &Environment::set_ssr_accel); + ClassDB::bind_method(D_METHOD("get_ssr_accel"), &Environment::get_ssr_accel); + + ClassDB::bind_method(D_METHOD("set_ssr_fade", "fade"), &Environment::set_ssr_fade); + ClassDB::bind_method(D_METHOD("get_ssr_fade"), &Environment::get_ssr_fade); + + ClassDB::bind_method(D_METHOD("set_ssr_depth_tolerance", "depth_tolerance"), &Environment::set_ssr_depth_tolerance); + ClassDB::bind_method(D_METHOD("get_ssr_depth_tolerance"), &Environment::get_ssr_depth_tolerance); + + ClassDB::bind_method(D_METHOD("set_ssr_smooth", "smooth"), &Environment::set_ssr_smooth); + ClassDB::bind_method(D_METHOD("is_ssr_smooth"), &Environment::is_ssr_smooth); + + ClassDB::bind_method(D_METHOD("set_ssr_rough", "rough"), &Environment::set_ssr_rough); + ClassDB::bind_method(D_METHOD("is_ssr_rough"), &Environment::is_ssr_rough); + + ADD_GROUP("SS Reflections", "ss_reflections_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ss_reflections_enabled"), "set_ssr_enabled", "is_ssr_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "ss_reflections_max_steps", PROPERTY_HINT_RANGE, "1,512,1"), "set_ssr_max_steps", "get_ssr_max_steps"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ss_reflections_accel", PROPERTY_HINT_RANGE, "0,4,0.01"), "set_ssr_accel", "get_ssr_accel"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ss_reflections_fade", PROPERTY_HINT_EXP_EASING), "set_ssr_fade", "get_ssr_fade"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ss_reflections_depth_tolerance", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_ssr_depth_tolerance", "get_ssr_depth_tolerance"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ss_reflections_accel_smooth"), "set_ssr_smooth", "is_ssr_smooth"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ss_reflections_roughness"), "set_ssr_rough", "is_ssr_rough"); - ClassDB::bind_method(D_METHOD("set_ssao_enabled","enabled"),&Environment::set_ssao_enabled); - ClassDB::bind_method(D_METHOD("is_ssao_enabled"),&Environment::is_ssao_enabled); + ClassDB::bind_method(D_METHOD("set_ssao_enabled", "enabled"), &Environment::set_ssao_enabled); + ClassDB::bind_method(D_METHOD("is_ssao_enabled"), &Environment::is_ssao_enabled); - ClassDB::bind_method(D_METHOD("set_ssao_radius","radius"),&Environment::set_ssao_radius); - ClassDB::bind_method(D_METHOD("get_ssao_radius"),&Environment::get_ssao_radius); + ClassDB::bind_method(D_METHOD("set_ssao_radius", "radius"), &Environment::set_ssao_radius); + ClassDB::bind_method(D_METHOD("get_ssao_radius"), &Environment::get_ssao_radius); - ClassDB::bind_method(D_METHOD("set_ssao_intensity","intensity"),&Environment::set_ssao_intensity); - ClassDB::bind_method(D_METHOD("get_ssao_intensity"),&Environment::get_ssao_intensity); + ClassDB::bind_method(D_METHOD("set_ssao_intensity", "intensity"), &Environment::set_ssao_intensity); + ClassDB::bind_method(D_METHOD("get_ssao_intensity"), &Environment::get_ssao_intensity); - ClassDB::bind_method(D_METHOD("set_ssao_radius2","radius"),&Environment::set_ssao_radius2); - ClassDB::bind_method(D_METHOD("get_ssao_radius2"),&Environment::get_ssao_radius2); + ClassDB::bind_method(D_METHOD("set_ssao_radius2", "radius"), &Environment::set_ssao_radius2); + ClassDB::bind_method(D_METHOD("get_ssao_radius2"), &Environment::get_ssao_radius2); - ClassDB::bind_method(D_METHOD("set_ssao_intensity2","intensity"),&Environment::set_ssao_intensity2); - ClassDB::bind_method(D_METHOD("get_ssao_intensity2"),&Environment::get_ssao_intensity2); + ClassDB::bind_method(D_METHOD("set_ssao_intensity2", "intensity"), &Environment::set_ssao_intensity2); + ClassDB::bind_method(D_METHOD("get_ssao_intensity2"), &Environment::get_ssao_intensity2); + + ClassDB::bind_method(D_METHOD("set_ssao_bias", "bias"), &Environment::set_ssao_bias); + ClassDB::bind_method(D_METHOD("get_ssao_bias"), &Environment::get_ssao_bias); + + ClassDB::bind_method(D_METHOD("set_ssao_direct_light_affect", "amount"), &Environment::set_ssao_direct_light_affect); + ClassDB::bind_method(D_METHOD("get_ssao_direct_light_affect"), &Environment::get_ssao_direct_light_affect); + + ClassDB::bind_method(D_METHOD("set_ssao_color", "color"), &Environment::set_ssao_color); + ClassDB::bind_method(D_METHOD("get_ssao_color"), &Environment::get_ssao_color); + + ClassDB::bind_method(D_METHOD("set_ssao_blur", "enabled"), &Environment::set_ssao_blur); + ClassDB::bind_method(D_METHOD("is_ssao_blur_enabled"), &Environment::is_ssao_blur_enabled); + + ADD_GROUP("SSAO", "ssao_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ssao_enabled"), "set_ssao_enabled", "is_ssao_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_radius", PROPERTY_HINT_RANGE, "0.1,16,0.1"), "set_ssao_radius", "get_ssao_radius"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_intensity", PROPERTY_HINT_RANGE, "0.0,9,0.1"), "set_ssao_intensity", "get_ssao_intensity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_radius2", PROPERTY_HINT_RANGE, "0.0,16,0.1"), "set_ssao_radius2", "get_ssao_radius2"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_intensity2", PROPERTY_HINT_RANGE, "0.0,9,0.1"), "set_ssao_intensity2", "get_ssao_intensity2"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_bias", PROPERTY_HINT_RANGE, "0.001,8,0.001"), "set_ssao_bias", "get_ssao_bias"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_light_affect", PROPERTY_HINT_RANGE, "0.00,1,0.01"), "set_ssao_direct_light_affect", "get_ssao_direct_light_affect"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "ssao_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_ssao_color", "get_ssao_color"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ssao_blur"), "set_ssao_blur", "is_ssao_blur_enabled"); + + ClassDB::bind_method(D_METHOD("set_dof_blur_far_enabled", "enabled"), &Environment::set_dof_blur_far_enabled); + ClassDB::bind_method(D_METHOD("is_dof_blur_far_enabled"), &Environment::is_dof_blur_far_enabled); + + ClassDB::bind_method(D_METHOD("set_dof_blur_far_distance", "intensity"), &Environment::set_dof_blur_far_distance); + ClassDB::bind_method(D_METHOD("get_dof_blur_far_distance"), &Environment::get_dof_blur_far_distance); + + ClassDB::bind_method(D_METHOD("set_dof_blur_far_transition", "intensity"), &Environment::set_dof_blur_far_transition); + ClassDB::bind_method(D_METHOD("get_dof_blur_far_transition"), &Environment::get_dof_blur_far_transition); - ClassDB::bind_method(D_METHOD("set_ssao_bias","bias"),&Environment::set_ssao_bias); - ClassDB::bind_method(D_METHOD("get_ssao_bias"),&Environment::get_ssao_bias); + ClassDB::bind_method(D_METHOD("set_dof_blur_far_amount", "intensity"), &Environment::set_dof_blur_far_amount); + ClassDB::bind_method(D_METHOD("get_dof_blur_far_amount"), &Environment::get_dof_blur_far_amount); - ClassDB::bind_method(D_METHOD("set_ssao_direct_light_affect","amount"),&Environment::set_ssao_direct_light_affect); - ClassDB::bind_method(D_METHOD("get_ssao_direct_light_affect"),&Environment::get_ssao_direct_light_affect); + ClassDB::bind_method(D_METHOD("set_dof_blur_far_quality", "intensity"), &Environment::set_dof_blur_far_quality); + ClassDB::bind_method(D_METHOD("get_dof_blur_far_quality"), &Environment::get_dof_blur_far_quality); - ClassDB::bind_method(D_METHOD("set_ssao_color","color"),&Environment::set_ssao_color); - ClassDB::bind_method(D_METHOD("get_ssao_color"),&Environment::get_ssao_color); + ClassDB::bind_method(D_METHOD("set_dof_blur_near_enabled", "enabled"), &Environment::set_dof_blur_near_enabled); + ClassDB::bind_method(D_METHOD("is_dof_blur_near_enabled"), &Environment::is_dof_blur_near_enabled); - ClassDB::bind_method(D_METHOD("set_ssao_blur","enabled"),&Environment::set_ssao_blur); - ClassDB::bind_method(D_METHOD("is_ssao_blur_enabled"),&Environment::is_ssao_blur_enabled); + ClassDB::bind_method(D_METHOD("set_dof_blur_near_distance", "intensity"), &Environment::set_dof_blur_near_distance); + ClassDB::bind_method(D_METHOD("get_dof_blur_near_distance"), &Environment::get_dof_blur_near_distance); - ADD_GROUP("SSAO","ssao_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ssao_enabled"),"set_ssao_enabled","is_ssao_enabled") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_radius",PROPERTY_HINT_RANGE,"0.1,16,0.1"),"set_ssao_radius","get_ssao_radius") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_intensity",PROPERTY_HINT_RANGE,"0.0,9,0.1"),"set_ssao_intensity","get_ssao_intensity") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_radius2",PROPERTY_HINT_RANGE,"0.0,16,0.1"),"set_ssao_radius2","get_ssao_radius2") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_intensity2",PROPERTY_HINT_RANGE,"0.0,9,0.1"),"set_ssao_intensity2","get_ssao_intensity2") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_bias",PROPERTY_HINT_RANGE,"0.001,8,0.001"),"set_ssao_bias","get_ssao_bias") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_light_affect",PROPERTY_HINT_RANGE,"0.00,1,0.01"),"set_ssao_direct_light_affect","get_ssao_direct_light_affect") ; - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"ssao_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_ssao_color","get_ssao_color") ; - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ssao_blur"),"set_ssao_blur","is_ssao_blur_enabled") ; + ClassDB::bind_method(D_METHOD("set_dof_blur_near_transition", "intensity"), &Environment::set_dof_blur_near_transition); + ClassDB::bind_method(D_METHOD("get_dof_blur_near_transition"), &Environment::get_dof_blur_near_transition); - ClassDB::bind_method(D_METHOD("set_dof_blur_far_enabled","enabled"),&Environment::set_dof_blur_far_enabled); - ClassDB::bind_method(D_METHOD("is_dof_blur_far_enabled"),&Environment::is_dof_blur_far_enabled); + ClassDB::bind_method(D_METHOD("set_dof_blur_near_amount", "intensity"), &Environment::set_dof_blur_near_amount); + ClassDB::bind_method(D_METHOD("get_dof_blur_near_amount"), &Environment::get_dof_blur_near_amount); - ClassDB::bind_method(D_METHOD("set_dof_blur_far_distance","intensity"),&Environment::set_dof_blur_far_distance); - ClassDB::bind_method(D_METHOD("get_dof_blur_far_distance"),&Environment::get_dof_blur_far_distance); + ClassDB::bind_method(D_METHOD("set_dof_blur_near_quality", "level"), &Environment::set_dof_blur_near_quality); + ClassDB::bind_method(D_METHOD("get_dof_blur_near_quality"), &Environment::get_dof_blur_near_quality); - ClassDB::bind_method(D_METHOD("set_dof_blur_far_transition","intensity"),&Environment::set_dof_blur_far_transition); - ClassDB::bind_method(D_METHOD("get_dof_blur_far_transition"),&Environment::get_dof_blur_far_transition); + ADD_GROUP("DOF Far Blur", "dof_blur_far_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_far_enabled"), "set_dof_blur_far_enabled", "is_dof_blur_far_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_far_distance", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_far_distance", "get_dof_blur_far_distance"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_far_transition", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_far_transition", "get_dof_blur_far_transition"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_far_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dof_blur_far_amount", "get_dof_blur_far_amount"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "dof_blur_far_quality", PROPERTY_HINT_ENUM, "Low,Medium,High"), "set_dof_blur_far_quality", "get_dof_blur_far_quality"); - ClassDB::bind_method(D_METHOD("set_dof_blur_far_amount","intensity"),&Environment::set_dof_blur_far_amount); - ClassDB::bind_method(D_METHOD("get_dof_blur_far_amount"),&Environment::get_dof_blur_far_amount); + ADD_GROUP("DOF Far Near", "dof_blur_near_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_near_enabled"), "set_dof_blur_near_enabled", "is_dof_blur_near_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_near_distance", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_near_distance", "get_dof_blur_near_distance"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_near_transition", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_near_transition", "get_dof_blur_near_transition"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_near_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dof_blur_near_amount", "get_dof_blur_near_amount"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "dof_blur_near_quality", PROPERTY_HINT_ENUM, "Low,Medium,High"), "set_dof_blur_near_quality", "get_dof_blur_near_quality"); - ClassDB::bind_method(D_METHOD("set_dof_blur_far_quality","intensity"),&Environment::set_dof_blur_far_quality); - ClassDB::bind_method(D_METHOD("get_dof_blur_far_quality"),&Environment::get_dof_blur_far_quality); + ClassDB::bind_method(D_METHOD("set_glow_enabled", "enabled"), &Environment::set_glow_enabled); + ClassDB::bind_method(D_METHOD("is_glow_enabled"), &Environment::is_glow_enabled); - ClassDB::bind_method(D_METHOD("set_dof_blur_near_enabled","enabled"),&Environment::set_dof_blur_near_enabled); - ClassDB::bind_method(D_METHOD("is_dof_blur_near_enabled"),&Environment::is_dof_blur_near_enabled); + ClassDB::bind_method(D_METHOD("set_glow_level", "idx", "enabled"), &Environment::set_glow_level); + ClassDB::bind_method(D_METHOD("is_glow_level_enabled", "idx"), &Environment::is_glow_level_enabled); - ClassDB::bind_method(D_METHOD("set_dof_blur_near_distance","intensity"),&Environment::set_dof_blur_near_distance); - ClassDB::bind_method(D_METHOD("get_dof_blur_near_distance"),&Environment::get_dof_blur_near_distance); + ClassDB::bind_method(D_METHOD("set_glow_intensity", "intensity"), &Environment::set_glow_intensity); + ClassDB::bind_method(D_METHOD("get_glow_intensity"), &Environment::get_glow_intensity); - ClassDB::bind_method(D_METHOD("set_dof_blur_near_transition","intensity"),&Environment::set_dof_blur_near_transition); - ClassDB::bind_method(D_METHOD("get_dof_blur_near_transition"),&Environment::get_dof_blur_near_transition); + ClassDB::bind_method(D_METHOD("set_glow_strength", "strength"), &Environment::set_glow_strength); + ClassDB::bind_method(D_METHOD("get_glow_strength"), &Environment::get_glow_strength); - ClassDB::bind_method(D_METHOD("set_dof_blur_near_amount","intensity"),&Environment::set_dof_blur_near_amount); - ClassDB::bind_method(D_METHOD("get_dof_blur_near_amount"),&Environment::get_dof_blur_near_amount); + ClassDB::bind_method(D_METHOD("set_glow_bloom", "amount"), &Environment::set_glow_bloom); + ClassDB::bind_method(D_METHOD("get_glow_bloom"), &Environment::get_glow_bloom); - ClassDB::bind_method(D_METHOD("set_dof_blur_near_quality","level"),&Environment::set_dof_blur_near_quality); - ClassDB::bind_method(D_METHOD("get_dof_blur_near_quality"),&Environment::get_dof_blur_near_quality); + ClassDB::bind_method(D_METHOD("set_glow_blend_mode", "mode"), &Environment::set_glow_blend_mode); + ClassDB::bind_method(D_METHOD("get_glow_blend_mode"), &Environment::get_glow_blend_mode); - ADD_GROUP("DOF Far Blur","dof_blur_far_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"dof_blur_far_enabled"),"set_dof_blur_far_enabled","is_dof_blur_far_enabled") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_distance",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_far_distance","get_dof_blur_far_distance") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_transition",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_far_transition","get_dof_blur_far_transition") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dof_blur_far_amount","get_dof_blur_far_amount") ; - ADD_PROPERTY(PropertyInfo(Variant::INT,"dof_blur_far_quality",PROPERTY_HINT_ENUM,"Low,Medium,High"),"set_dof_blur_far_quality","get_dof_blur_far_quality") ; + ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_treshold", "treshold"), &Environment::set_glow_hdr_bleed_treshold); + ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_treshold"), &Environment::get_glow_hdr_bleed_treshold); - ADD_GROUP("DOF Far Near","dof_blur_near_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"dof_blur_near_enabled"),"set_dof_blur_near_enabled","is_dof_blur_near_enabled") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_distance",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_near_distance","get_dof_blur_near_distance") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_transition",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_near_transition","get_dof_blur_near_transition") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dof_blur_near_amount","get_dof_blur_near_amount") ; - ADD_PROPERTY(PropertyInfo(Variant::INT,"dof_blur_near_quality",PROPERTY_HINT_ENUM,"Low,Medium,High"),"set_dof_blur_near_quality","get_dof_blur_near_quality") ; + ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_scale", "scale"), &Environment::set_glow_hdr_bleed_scale); + ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_scale"), &Environment::get_glow_hdr_bleed_scale); + ClassDB::bind_method(D_METHOD("set_glow_bicubic_upscale", "enabled"), &Environment::set_glow_bicubic_upscale); + ClassDB::bind_method(D_METHOD("is_glow_bicubic_upscale_enabled"), &Environment::is_glow_bicubic_upscale_enabled); - ClassDB::bind_method(D_METHOD("set_glow_enabled","enabled"),&Environment::set_glow_enabled); - ClassDB::bind_method(D_METHOD("is_glow_enabled"),&Environment::is_glow_enabled); + ADD_GROUP("Glow", "glow_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "glow_enabled"), "set_glow_enabled", "is_glow_enabled"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/1"), "set_glow_level", "is_glow_level_enabled", 0); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/2"), "set_glow_level", "is_glow_level_enabled", 1); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/3"), "set_glow_level", "is_glow_level_enabled", 2); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/4"), "set_glow_level", "is_glow_level_enabled", 3); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/5"), "set_glow_level", "is_glow_level_enabled", 4); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/6"), "set_glow_level", "is_glow_level_enabled", 5); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/7"), "set_glow_level", "is_glow_level_enabled", 6); - ClassDB::bind_method(D_METHOD("set_glow_level","idx","enabled"),&Environment::set_glow_level); - ClassDB::bind_method(D_METHOD("is_glow_level_enabled","idx"),&Environment::is_glow_level_enabled); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_intensity", PROPERTY_HINT_RANGE, "0.0,8.0,0.01"), "set_glow_intensity", "get_glow_intensity"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_strength", PROPERTY_HINT_RANGE, "0.0,2.0,0.01"), "set_glow_strength", "get_glow_strength"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_bloom", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_glow_bloom", "get_glow_bloom"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "glow_blend_mode", PROPERTY_HINT_ENUM, "Additive,Screen,Softlight,Replace"), "set_glow_blend_mode", "get_glow_blend_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_hdr_treshold", PROPERTY_HINT_RANGE, "0.0,4.0,0.01"), "set_glow_hdr_bleed_treshold", "get_glow_hdr_bleed_treshold"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_hdr_scale", PROPERTY_HINT_RANGE, "0.0,4.0,0.01"), "set_glow_hdr_bleed_scale", "get_glow_hdr_bleed_scale"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "glow_bicubic_upscale"), "set_glow_bicubic_upscale", "is_glow_bicubic_upscale_enabled"); - ClassDB::bind_method(D_METHOD("set_glow_intensity","intensity"),&Environment::set_glow_intensity); - ClassDB::bind_method(D_METHOD("get_glow_intensity"),&Environment::get_glow_intensity); + ClassDB::bind_method(D_METHOD("set_tonemapper", "mode"), &Environment::set_tonemapper); + ClassDB::bind_method(D_METHOD("get_tonemapper"), &Environment::get_tonemapper); - ClassDB::bind_method(D_METHOD("set_glow_strength","strength"),&Environment::set_glow_strength); - ClassDB::bind_method(D_METHOD("get_glow_strength"),&Environment::get_glow_strength); + ClassDB::bind_method(D_METHOD("set_tonemap_exposure", "exposure"), &Environment::set_tonemap_exposure); + ClassDB::bind_method(D_METHOD("get_tonemap_exposure"), &Environment::get_tonemap_exposure); - ClassDB::bind_method(D_METHOD("set_glow_bloom","amount"),&Environment::set_glow_bloom); - ClassDB::bind_method(D_METHOD("get_glow_bloom"),&Environment::get_glow_bloom); + ClassDB::bind_method(D_METHOD("set_tonemap_white", "white"), &Environment::set_tonemap_white); + ClassDB::bind_method(D_METHOD("get_tonemap_white"), &Environment::get_tonemap_white); - ClassDB::bind_method(D_METHOD("set_glow_blend_mode","mode"),&Environment::set_glow_blend_mode); - ClassDB::bind_method(D_METHOD("get_glow_blend_mode"),&Environment::get_glow_blend_mode); + ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure", "auto_exposure"), &Environment::set_tonemap_auto_exposure); + ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure"), &Environment::get_tonemap_auto_exposure); - ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_treshold","treshold"),&Environment::set_glow_hdr_bleed_treshold); - ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_treshold"),&Environment::get_glow_hdr_bleed_treshold); + ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_max", "exposure_max"), &Environment::set_tonemap_auto_exposure_max); + ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_max"), &Environment::get_tonemap_auto_exposure_max); - ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_scale","scale"),&Environment::set_glow_hdr_bleed_scale); - ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_scale"),&Environment::get_glow_hdr_bleed_scale); + ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_min", "exposure_min"), &Environment::set_tonemap_auto_exposure_min); + ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_min"), &Environment::get_tonemap_auto_exposure_min); - ClassDB::bind_method(D_METHOD("set_glow_bicubic_upscale","enabled"),&Environment::set_glow_bicubic_upscale); - ClassDB::bind_method(D_METHOD("is_glow_bicubic_upscale_enabled"),&Environment::is_glow_bicubic_upscale_enabled); + ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_speed", "exposure_speed"), &Environment::set_tonemap_auto_exposure_speed); + ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_speed"), &Environment::get_tonemap_auto_exposure_speed); - ADD_GROUP("Glow","glow_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"glow_enabled"),"set_glow_enabled","is_glow_enabled") ; - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/1"),"set_glow_level","is_glow_level_enabled",0 ); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/2"),"set_glow_level","is_glow_level_enabled",1 ); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/3"),"set_glow_level","is_glow_level_enabled",2 ); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/4"),"set_glow_level","is_glow_level_enabled",3 ); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/5"),"set_glow_level","is_glow_level_enabled",4 ); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/6"),"set_glow_level","is_glow_level_enabled",5 ); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/7"),"set_glow_level","is_glow_level_enabled",6 ); + ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_grey", "exposure_grey"), &Environment::set_tonemap_auto_exposure_grey); + ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_grey"), &Environment::get_tonemap_auto_exposure_grey); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_intensity",PROPERTY_HINT_RANGE,"0.0,8.0,0.01"),"set_glow_intensity","get_glow_intensity") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_strength",PROPERTY_HINT_RANGE,"0.0,2.0,0.01"),"set_glow_strength","get_glow_strength") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_bloom",PROPERTY_HINT_RANGE,"0.0,1.0,0.01"),"set_glow_bloom","get_glow_bloom") ; - ADD_PROPERTY(PropertyInfo(Variant::INT,"glow_blend_mode",PROPERTY_HINT_ENUM,"Additive,Screen,Softlight,Replace"),"set_glow_blend_mode","get_glow_blend_mode") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_hdr_treshold",PROPERTY_HINT_RANGE,"0.0,4.0,0.01"),"set_glow_hdr_bleed_treshold","get_glow_hdr_bleed_treshold") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_hdr_scale",PROPERTY_HINT_RANGE,"0.0,4.0,0.01"),"set_glow_hdr_bleed_scale","get_glow_hdr_bleed_scale") ; - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"glow_bicubic_upscale"),"set_glow_bicubic_upscale","is_glow_bicubic_upscale_enabled") ; + ADD_GROUP("Tonemap", "tonemap_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "tonemap_mode", PROPERTY_HINT_ENUM, "Linear,Reindhart,Filmic,Aces"), "set_tonemapper", "get_tonemapper"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tonemap_exposure", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_exposure", "get_tonemap_exposure"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "tonemap_white", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_white", "get_tonemap_white"); + ADD_GROUP("Auto Exposure", "auto_exposure_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_expoure_enabled"), "set_tonemap_auto_exposure", "get_tonemap_auto_exposure"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_scale", PROPERTY_HINT_RANGE, "0.01,64,0.01"), "set_tonemap_auto_exposure_grey", "get_tonemap_auto_exposure_grey"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_min_luma", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_auto_exposure_min", "get_tonemap_auto_exposure_min"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_max_luma", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_auto_exposure_max", "get_tonemap_auto_exposure_max"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_speed", PROPERTY_HINT_RANGE, "0.01,64,0.01"), "set_tonemap_auto_exposure_speed", "get_tonemap_auto_exposure_speed"); + ClassDB::bind_method(D_METHOD("set_adjustment_enable", "enabled"), &Environment::set_adjustment_enable); + ClassDB::bind_method(D_METHOD("is_adjustment_enabled"), &Environment::is_adjustment_enabled); - ClassDB::bind_method(D_METHOD("set_tonemapper","mode"),&Environment::set_tonemapper); - ClassDB::bind_method(D_METHOD("get_tonemapper"),&Environment::get_tonemapper); + ClassDB::bind_method(D_METHOD("set_adjustment_brightness", "brightness"), &Environment::set_adjustment_brightness); + ClassDB::bind_method(D_METHOD("get_adjustment_brightness"), &Environment::get_adjustment_brightness); - ClassDB::bind_method(D_METHOD("set_tonemap_exposure","exposure"),&Environment::set_tonemap_exposure); - ClassDB::bind_method(D_METHOD("get_tonemap_exposure"),&Environment::get_tonemap_exposure); + ClassDB::bind_method(D_METHOD("set_adjustment_contrast", "contrast"), &Environment::set_adjustment_contrast); + ClassDB::bind_method(D_METHOD("get_adjustment_contrast"), &Environment::get_adjustment_contrast); - ClassDB::bind_method(D_METHOD("set_tonemap_white","white"),&Environment::set_tonemap_white); - ClassDB::bind_method(D_METHOD("get_tonemap_white"),&Environment::get_tonemap_white); + ClassDB::bind_method(D_METHOD("set_adjustment_saturation", "saturation"), &Environment::set_adjustment_saturation); + ClassDB::bind_method(D_METHOD("get_adjustment_saturation"), &Environment::get_adjustment_saturation); - ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure","auto_exposure"),&Environment::set_tonemap_auto_exposure); - ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure"),&Environment::get_tonemap_auto_exposure); + ClassDB::bind_method(D_METHOD("set_adjustment_color_correction", "color_correction"), &Environment::set_adjustment_color_correction); + ClassDB::bind_method(D_METHOD("get_adjustment_color_correction"), &Environment::get_adjustment_color_correction); - ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_max","exposure_max"),&Environment::set_tonemap_auto_exposure_max); - ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_max"),&Environment::get_tonemap_auto_exposure_max); + ADD_GROUP("Adjustments", "adjustment_"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "adjustment_enabled"), "set_adjustment_enable", "is_adjustment_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "adjustment_brightness", PROPERTY_HINT_RANGE, "0.01,8,0.01"), "set_adjustment_brightness", "get_adjustment_brightness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "adjustment_contrast", PROPERTY_HINT_RANGE, "0.01,8,0.01"), "set_adjustment_contrast", "get_adjustment_contrast"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "adjustment_saturation", PROPERTY_HINT_RANGE, "0.01,8,0.01"), "set_adjustment_saturation", "get_adjustment_saturation"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "adjustment_color_correction", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_adjustment_color_correction", "get_adjustment_color_correction"); - ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_min","exposure_min"),&Environment::set_tonemap_auto_exposure_min); - ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_min"),&Environment::get_tonemap_auto_exposure_min); - - ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_speed","exposure_speed"),&Environment::set_tonemap_auto_exposure_speed); - ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_speed"),&Environment::get_tonemap_auto_exposure_speed); - - ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_grey","exposure_grey"),&Environment::set_tonemap_auto_exposure_grey); - ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_grey"),&Environment::get_tonemap_auto_exposure_grey); - - - ADD_GROUP("Tonemap","tonemap_"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"tonemap_mode",PROPERTY_HINT_ENUM,"Linear,Reindhart,Filmic,Aces"),"set_tonemapper","get_tonemapper") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tonemap_exposure",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_exposure","get_tonemap_exposure") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"tonemap_white",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_white","get_tonemap_white") ; - ADD_GROUP("Auto Exposure","auto_exposure_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"auto_expoure_enabled"),"set_tonemap_auto_exposure","get_tonemap_auto_exposure") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_scale",PROPERTY_HINT_RANGE,"0.01,64,0.01"),"set_tonemap_auto_exposure_grey","get_tonemap_auto_exposure_grey") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_min_luma",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_auto_exposure_min","get_tonemap_auto_exposure_min") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_max_luma",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_auto_exposure_max","get_tonemap_auto_exposure_max") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_speed",PROPERTY_HINT_RANGE,"0.01,64,0.01"),"set_tonemap_auto_exposure_speed","get_tonemap_auto_exposure_speed") ; - - ClassDB::bind_method(D_METHOD("set_adjustment_enable","enabled"),&Environment::set_adjustment_enable); - ClassDB::bind_method(D_METHOD("is_adjustment_enabled"),&Environment::is_adjustment_enabled); - - ClassDB::bind_method(D_METHOD("set_adjustment_brightness","brightness"),&Environment::set_adjustment_brightness); - ClassDB::bind_method(D_METHOD("get_adjustment_brightness"),&Environment::get_adjustment_brightness); - - ClassDB::bind_method(D_METHOD("set_adjustment_contrast","contrast"),&Environment::set_adjustment_contrast); - ClassDB::bind_method(D_METHOD("get_adjustment_contrast"),&Environment::get_adjustment_contrast); - - ClassDB::bind_method(D_METHOD("set_adjustment_saturation","saturation"),&Environment::set_adjustment_saturation); - ClassDB::bind_method(D_METHOD("get_adjustment_saturation"),&Environment::get_adjustment_saturation); - - ClassDB::bind_method(D_METHOD("set_adjustment_color_correction","color_correction"),&Environment::set_adjustment_color_correction); - ClassDB::bind_method(D_METHOD("get_adjustment_color_correction"),&Environment::get_adjustment_color_correction); - - ADD_GROUP("Adjustments","adjustment_"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL,"adjustment_enabled"),"set_adjustment_enable","is_adjustment_enabled") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_brightness",PROPERTY_HINT_RANGE,"0.01,8,0.01"),"set_adjustment_brightness","get_adjustment_brightness") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_contrast",PROPERTY_HINT_RANGE,"0.01,8,0.01"),"set_adjustment_contrast","get_adjustment_contrast") ; - ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_saturation",PROPERTY_HINT_RANGE,"0.01,8,0.01"),"set_adjustment_saturation","get_adjustment_saturation") ; - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"adjustment_color_correction",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_adjustment_color_correction","get_adjustment_color_correction") ; - - - GLOBAL_DEF("rendering/skybox/irradiance_cube_resolution",256); + GLOBAL_DEF("rendering/skybox/irradiance_cube_resolution", 256); BIND_CONSTANT(BG_KEEP); BIND_CONSTANT(BG_CLEAR_COLOR); @@ -973,79 +927,75 @@ void Environment::_bind_methods() { BIND_CONSTANT(DOF_BLUR_QUALITY_LOW); BIND_CONSTANT(DOF_BLUR_QUALITY_MEDIUM); BIND_CONSTANT(DOF_BLUR_QUALITY_HIGH); - - } Environment::Environment() { - bg_mode=BG_CLEAR_COLOR; - bg_skybox_scale=1.0; - bg_energy=1.0; - bg_canvas_max_layer=0; - ambient_energy=1.0; - ambient_skybox_contribution=0; - - - tone_mapper=TONE_MAPPER_LINEAR; - tonemap_exposure=1.0; - tonemap_white=1.0; - tonemap_auto_exposure=false; - tonemap_auto_exposure_max=8; - tonemap_auto_exposure_min=0.05; - tonemap_auto_exposure_speed=0.5; - tonemap_auto_exposure_grey=0.4; + bg_mode = BG_CLEAR_COLOR; + bg_skybox_scale = 1.0; + bg_energy = 1.0; + bg_canvas_max_layer = 0; + ambient_energy = 1.0; + ambient_skybox_contribution = 0; + + tone_mapper = TONE_MAPPER_LINEAR; + tonemap_exposure = 1.0; + tonemap_white = 1.0; + tonemap_auto_exposure = false; + tonemap_auto_exposure_max = 8; + tonemap_auto_exposure_min = 0.05; + tonemap_auto_exposure_speed = 0.5; + tonemap_auto_exposure_grey = 0.4; set_tonemapper(tone_mapper); //update - adjustment_enabled=false; - adjustment_contrast=1.0; - adjustment_saturation=1.0; - adjustment_brightness=1.0; + adjustment_enabled = false; + adjustment_contrast = 1.0; + adjustment_saturation = 1.0; + adjustment_brightness = 1.0; set_adjustment_enable(adjustment_enabled); //update environment = VS::get_singleton()->environment_create(); - ssr_enabled=false; - ssr_max_steps=64; - ssr_accel=0.04; - ssr_fade=2.0; - ssr_depth_tolerance=0.2; - ssr_smooth=true; - ssr_roughness=true; - - ssao_enabled=false; - ssao_radius=1; - ssao_intensity=1; - ssao_radius2=0; - ssao_intensity2=1; - ssao_bias=0.01; - ssao_direct_light_affect=false; - ssao_blur=true; - - glow_enabled=false; - glow_levels=(1<<2)|(1<<4); - glow_intensity=0.8; - glow_strength=1.0; - glow_bloom=0.0; - glow_blend_mode=GLOW_BLEND_MODE_SOFTLIGHT; - glow_hdr_bleed_treshold=1.0; - glow_hdr_bleed_scale=2.0; - glow_bicubic_upscale=false; - - dof_blur_far_enabled=false; - dof_blur_far_distance=10; - dof_blur_far_transition=5; - dof_blur_far_amount=0.1; - dof_blur_far_quality=DOF_BLUR_QUALITY_MEDIUM; - - dof_blur_near_enabled=false; - dof_blur_near_distance=2; - dof_blur_near_transition=1; - dof_blur_near_amount=0.1; - dof_blur_near_quality=DOF_BLUR_QUALITY_MEDIUM; - + ssr_enabled = false; + ssr_max_steps = 64; + ssr_accel = 0.04; + ssr_fade = 2.0; + ssr_depth_tolerance = 0.2; + ssr_smooth = true; + ssr_roughness = true; + + ssao_enabled = false; + ssao_radius = 1; + ssao_intensity = 1; + ssao_radius2 = 0; + ssao_intensity2 = 1; + ssao_bias = 0.01; + ssao_direct_light_affect = false; + ssao_blur = true; + + glow_enabled = false; + glow_levels = (1 << 2) | (1 << 4); + glow_intensity = 0.8; + glow_strength = 1.0; + glow_bloom = 0.0; + glow_blend_mode = GLOW_BLEND_MODE_SOFTLIGHT; + glow_hdr_bleed_treshold = 1.0; + glow_hdr_bleed_scale = 2.0; + glow_bicubic_upscale = false; + + dof_blur_far_enabled = false; + dof_blur_far_distance = 10; + dof_blur_far_transition = 5; + dof_blur_far_amount = 0.1; + dof_blur_far_quality = DOF_BLUR_QUALITY_MEDIUM; + + dof_blur_near_enabled = false; + dof_blur_near_distance = 2; + dof_blur_near_transition = 1; + dof_blur_near_amount = 0.1; + dof_blur_near_quality = DOF_BLUR_QUALITY_MEDIUM; } Environment::~Environment() { diff --git a/scene/resources/environment.h b/scene/resources/environment.h index b8c243b588..3ac311f4a3 100644 --- a/scene/resources/environment.h +++ b/scene/resources/environment.h @@ -30,15 +30,15 @@ #define ENVIRONMENT_H #include "resource.h" -#include "servers/visual_server.h" -#include "scene/resources/texture.h" #include "scene/resources/sky_box.h" +#include "scene/resources/texture.h" +#include "servers/visual_server.h" class Environment : public Resource { - GDCLASS(Environment,Resource); -public: + GDCLASS(Environment, Resource); +public: enum BGMode { BG_CLEAR_COLOR, @@ -49,8 +49,6 @@ public: BG_MAX }; - - enum ToneMapper { TONE_MAPPER_LINEAR, TONE_MAPPER_REINHARDT, @@ -140,20 +138,17 @@ private: DOFBlurQuality dof_blur_near_quality; protected: - static void _bind_methods(); - virtual void _validate_property(PropertyInfo& property) const; + virtual void _validate_property(PropertyInfo &property) const; public: - - void set_background(BGMode p_bg); - void set_skybox(const Ref<SkyBox>& p_skybox); + void set_skybox(const Ref<SkyBox> &p_skybox); void set_skybox_scale(float p_scale); - void set_bg_color(const Color& p_color); + void set_bg_color(const Color &p_color); void set_bg_energy(float p_energy); void set_canvas_max_layer(int p_max_layer); - void set_ambient_light_color(const Color& p_color); + void set_ambient_light_color(const Color &p_color); void set_ambient_light_energy(float p_energy); void set_ambient_light_skybox_contribution(float p_energy); @@ -167,7 +162,6 @@ public: float get_ambient_light_energy() const; float get_ambient_light_skybox_contribution() const; - void set_tonemapper(ToneMapper p_tone_mapper); ToneMapper get_tonemapper() const; @@ -204,7 +198,7 @@ public: void set_adjustment_saturation(float p_saturation); float get_adjustment_saturation() const; - void set_adjustment_color_correction(const Ref<Texture>& p_ramp); + void set_adjustment_color_correction(const Ref<Texture> &p_ramp); Ref<Texture> get_adjustment_color_correction() const; void set_ssr_enabled(bool p_enable); @@ -249,17 +243,16 @@ public: void set_ssao_direct_light_affect(float p_direct_light_affect); float get_ssao_direct_light_affect() const; - void set_ssao_color(const Color& p_color); + void set_ssao_color(const Color &p_color); Color get_ssao_color() const; void set_ssao_blur(bool p_enable); bool is_ssao_blur_enabled() const; - void set_glow_enabled(bool p_enabled); bool is_glow_enabled() const; - void set_glow_level(int p_level,bool p_enabled); + void set_glow_level(int p_level, bool p_enabled); bool is_glow_level_enabled(int p_level) const; void set_glow_intensity(float p_intensity); @@ -313,16 +306,12 @@ public: void set_dof_blur_near_quality(DOFBlurQuality p_quality); DOFBlurQuality get_dof_blur_near_quality() const; - virtual RID get_rid() const; Environment(); ~Environment(); }; - - - VARIANT_ENUM_CAST(Environment::BGMode) VARIANT_ENUM_CAST(Environment::ToneMapper) VARIANT_ENUM_CAST(Environment::GlowBlendMode) diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp index d94e046b98..9f30474a26 100644 --- a/scene/resources/font.cpp +++ b/scene/resources/font.cpp @@ -28,46 +28,44 @@ /*************************************************************************/ #include "font.h" -#include "core/os/file_access.h" #include "core/io/resource_loader.h" +#include "core/os/file_access.h" +void Font::draw_halign(RID p_canvas_item, const Point2 &p_pos, HAlign p_align, float p_width, const String &p_text, const Color &p_modulate) const { - -void Font::draw_halign(RID p_canvas_item, const Point2& p_pos, HAlign p_align,float p_width,const String& p_text,const Color& p_modulate) const { - - float length=get_string_size(p_text).width; - if (length>=p_width) { - draw(p_canvas_item,p_pos,p_text,p_modulate,p_width); + float length = get_string_size(p_text).width; + if (length >= p_width) { + draw(p_canvas_item, p_pos, p_text, p_modulate, p_width); return; } float ofs; - switch(p_align) { + switch (p_align) { case HALIGN_LEFT: { - ofs=0; + ofs = 0; } break; case HALIGN_CENTER: { - ofs = Math::floor( (p_width-length) / 2.0 ); + ofs = Math::floor((p_width - length) / 2.0); } break; case HALIGN_RIGHT: { - ofs=p_width-length; + ofs = p_width - length; } break; } - draw(p_canvas_item,p_pos+Point2(ofs,0),p_text,p_modulate,p_width); + draw(p_canvas_item, p_pos + Point2(ofs, 0), p_text, p_modulate, p_width); } -void Font::draw(RID p_canvas_item, const Point2& p_pos, const String& p_text, const Color& p_modulate,int p_clip_w) const { +void Font::draw(RID p_canvas_item, const Point2 &p_pos, const String &p_text, const Color &p_modulate, int p_clip_w) const { Vector2 ofs; - for (int i=0;i<p_text.length();i++) { + for (int i = 0; i < p_text.length(); i++) { int width = get_char_size(p_text[i]).width; - if (p_clip_w>=0 && (ofs.x+width)>p_clip_w) + if (p_clip_w >= 0 && (ofs.x + width) > p_clip_w) break; //clip - ofs.x+=draw_char(p_canvas_item,p_pos+ofs,p_text[i],p_text[i+1],p_modulate); + ofs.x += draw_char(p_canvas_item, p_pos + ofs, p_text[i], p_text[i + 1], p_modulate); } } @@ -78,53 +76,47 @@ void Font::update_changes() { void Font::_bind_methods() { - ClassDB::bind_method(D_METHOD("draw","canvas_item","pos","string","modulate","clip_w"),&Font::draw,DEFVAL(Color(1,1,1)),DEFVAL(-1)); - ClassDB::bind_method(D_METHOD("get_ascent"),&Font::get_ascent); - ClassDB::bind_method(D_METHOD("get_descent"),&Font::get_descent); - ClassDB::bind_method(D_METHOD("get_height"),&Font::get_height); - ClassDB::bind_method(D_METHOD("is_distance_field_hint"),&Font::is_distance_field_hint); - ClassDB::bind_method(D_METHOD("get_string_size","string"),&Font::get_string_size); - ClassDB::bind_method(D_METHOD("draw_char","canvas_item","pos","char","next","modulate"),&Font::draw_char,DEFVAL(-1),DEFVAL(Color(1,1,1))); - ClassDB::bind_method(D_METHOD("update_changes"),&Font::update_changes); - + ClassDB::bind_method(D_METHOD("draw", "canvas_item", "pos", "string", "modulate", "clip_w"), &Font::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("get_ascent"), &Font::get_ascent); + ClassDB::bind_method(D_METHOD("get_descent"), &Font::get_descent); + ClassDB::bind_method(D_METHOD("get_height"), &Font::get_height); + ClassDB::bind_method(D_METHOD("is_distance_field_hint"), &Font::is_distance_field_hint); + ClassDB::bind_method(D_METHOD("get_string_size", "string"), &Font::get_string_size); + ClassDB::bind_method(D_METHOD("draw_char", "canvas_item", "pos", "char", "next", "modulate"), &Font::draw_char, DEFVAL(-1), DEFVAL(Color(1, 1, 1))); + ClassDB::bind_method(D_METHOD("update_changes"), &Font::update_changes); } - Font::Font() { - - } ///////////////////////////////////////////////////////////////// -void BitmapFont::_set_chars(const PoolVector<int>& p_chars) { +void BitmapFont::_set_chars(const PoolVector<int> &p_chars) { int len = p_chars.size(); //char 1 charsize 1 texture, 4 rect, 2 align, advance 1 - ERR_FAIL_COND(len%9); + ERR_FAIL_COND(len % 9); if (!len) return; //none to do - int chars = len/9; + int chars = len / 9; + PoolVector<int>::Read r = p_chars.read(); + for (int i = 0; i < chars; i++) { - PoolVector<int>::Read r=p_chars.read(); - for(int i=0;i<chars;i++) { - - const int* data = &r[i*9]; - add_char(data[0],data[1],Rect2(data[2],data[3],data[4],data[5]), Size2(data[6],data[7]),data[8]); + const int *data = &r[i * 9]; + add_char(data[0], data[1], Rect2(data[2], data[3], data[4], data[5]), Size2(data[6], data[7]), data[8]); } - } PoolVector<int> BitmapFont::_get_chars() const { PoolVector<int> chars; - const CharType* key=NULL; + const CharType *key = NULL; - while((key=char_map.next(key))) { + while ((key = char_map.next(key))) { - const Character *c=char_map.getptr(*key); + const Character *c = char_map.getptr(*key); chars.push_back(*key); chars.push_back(c->texture_idx); chars.push_back(c->rect.pos.x); @@ -140,18 +132,18 @@ PoolVector<int> BitmapFont::_get_chars() const { return chars; } -void BitmapFont::_set_kernings(const PoolVector<int>& p_kernings) { +void BitmapFont::_set_kernings(const PoolVector<int> &p_kernings) { - int len=p_kernings.size(); - ERR_FAIL_COND(len%3); + int len = p_kernings.size(); + ERR_FAIL_COND(len % 3); if (!len) return; - PoolVector<int>::Read r=p_kernings.read(); + PoolVector<int>::Read r = p_kernings.read(); - for(int i=0;i<len/3;i++) { + for (int i = 0; i < len / 3; i++) { - const int* data = &r[i*3]; - add_kerning_pair(data[0],data[1],data[2]); + const int *data = &r[i * 3]; + add_kerning_pair(data[0], data[1], data[2]); } } @@ -159,7 +151,7 @@ PoolVector<int> BitmapFont::_get_kernings() const { PoolVector<int> kernings; - for(Map<KerningPairKey,int>::Element *E=kerning_map.front();E;E=E->next()) { + for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) { kernings.push_back(E->key().A); kernings.push_back(E->key().B); @@ -169,86 +161,79 @@ PoolVector<int> BitmapFont::_get_kernings() const { return kernings; } +void BitmapFont::_set_textures(const Vector<Variant> &p_textures) { -void BitmapFont::_set_textures(const Vector<Variant> & p_textures) { - - for(int i=0;i<p_textures.size();i++) { + for (int i = 0; i < p_textures.size(); i++) { Ref<Texture> tex = p_textures[i]; ERR_CONTINUE(!tex.is_valid()); add_texture(tex); } - } Vector<Variant> BitmapFont::_get_textures() const { Vector<Variant> rtextures; - for(int i=0;i<textures.size();i++) + for (int i = 0; i < textures.size(); i++) rtextures.push_back(textures[i].get_ref_ptr()); return rtextures; } -Error BitmapFont::create_from_fnt(const String& p_string) { +Error BitmapFont::create_from_fnt(const String &p_string) { //fnt format used by angelcode bmfont //http://www.angelcode.com/products/bmfont/ - FileAccess *f = FileAccess::open(p_string,FileAccess::READ); + FileAccess *f = FileAccess::open(p_string, FileAccess::READ); if (!f) { - ERR_EXPLAIN("Can't open font: "+p_string); + ERR_EXPLAIN("Can't open font: " + p_string); ERR_FAIL_V(ERR_FILE_NOT_FOUND); } clear(); - while(true) { + while (true) { - String line=f->get_line(); + String line = f->get_line(); - int delimiter=line.find(" "); - String type=line.substr(0,delimiter); - int pos = delimiter+1; - Map<String,String> keys; + int delimiter = line.find(" "); + String type = line.substr(0, delimiter); + int pos = delimiter + 1; + Map<String, String> keys; - while (pos < line.size() && line[pos]==' ') + while (pos < line.size() && line[pos] == ' ') pos++; + while (pos < line.size()) { - while(pos<line.size()) { - - int eq = line.find("=",pos); - if (eq==-1) + int eq = line.find("=", pos); + if (eq == -1) break; - String key=line.substr(pos,eq-pos); - int end=-1; + String key = line.substr(pos, eq - pos); + int end = -1; String value; - if (line[eq+1]=='"') { - end=line.find("\"",eq+2); - if (end==-1) + if (line[eq + 1] == '"') { + end = line.find("\"", eq + 2); + if (end == -1) break; - value=line.substr(eq+2,end-1-eq-1); - pos=end+1; + value = line.substr(eq + 2, end - 1 - eq - 1); + pos = end + 1; } else { - end=line.find(" ",eq+1); - if (end==-1) - end=line.size(); + end = line.find(" ", eq + 1); + if (end == -1) + end = line.size(); - value=line.substr(eq+1,end-eq); - - pos=end; + value = line.substr(eq + 1, end - eq); + pos = end; } - while (pos<line.size() && line[pos]==' ') + while (pos < line.size() && line[pos] == ' ') pos++; - - keys[key]=value; - + keys[key] = value; } - - if (type=="info") { + if (type == "info") { if (keys.has("face")) set_name(keys["face"]); @@ -257,19 +242,19 @@ Error BitmapFont::create_from_fnt(const String& p_string) { font->set_height(keys["size"].to_int()); */ - } else if (type=="common") { + } else if (type == "common") { if (keys.has("lineHeight")) set_height(keys["lineHeight"].to_int()); if (keys.has("base")) set_ascent(keys["base"].to_int()); - } else if (type=="page") { + } else if (type == "page") { if (keys.has("file")) { String file = keys["file"]; - file=p_string.get_base_dir()+"/"+file; + file = p_string.get_base_dir() + "/" + file; Ref<Texture> tex = ResourceLoader::load(file); if (tex.is_null()) { ERR_PRINT("Can't load font texture!"); @@ -277,80 +262,75 @@ Error BitmapFont::create_from_fnt(const String& p_string) { add_texture(tex); } } - } else if (type=="char") { + } else if (type == "char") { - CharType idx=0; + CharType idx = 0; if (keys.has("id")) - idx=keys["id"].to_int(); + idx = keys["id"].to_int(); Rect2 rect; if (keys.has("x")) - rect.pos.x=keys["x"].to_int(); + rect.pos.x = keys["x"].to_int(); if (keys.has("y")) - rect.pos.y=keys["y"].to_int(); + rect.pos.y = keys["y"].to_int(); if (keys.has("width")) - rect.size.width=keys["width"].to_int(); + rect.size.width = keys["width"].to_int(); if (keys.has("height")) - rect.size.height=keys["height"].to_int(); + rect.size.height = keys["height"].to_int(); Point2 ofs; if (keys.has("xoffset")) - ofs.x=keys["xoffset"].to_int(); + ofs.x = keys["xoffset"].to_int(); if (keys.has("yoffset")) - ofs.y=keys["yoffset"].to_int(); + ofs.y = keys["yoffset"].to_int(); - int texture=0; + int texture = 0; if (keys.has("page")) - texture=keys["page"].to_int(); - int advance=-1; + texture = keys["page"].to_int(); + int advance = -1; if (keys.has("xadvance")) - advance=keys["xadvance"].to_int(); + advance = keys["xadvance"].to_int(); - add_char(idx,texture,rect,ofs,advance); + add_char(idx, texture, rect, ofs, advance); - } else if (type=="kerning") { + } else if (type == "kerning") { - CharType first=0,second=0; - int k=0; + CharType first = 0, second = 0; + int k = 0; if (keys.has("first")) - first=keys["first"].to_int(); + first = keys["first"].to_int(); if (keys.has("second")) - second=keys["second"].to_int(); + second = keys["second"].to_int(); if (keys.has("amount")) - k=keys["amount"].to_int(); - - add_kerning_pair(first,second,-k); + k = keys["amount"].to_int(); + add_kerning_pair(first, second, -k); } if (f->eof_reached()) break; } - - memdelete(f); return OK; } - - void BitmapFont::set_height(float p_height) { - height=p_height; + height = p_height; } -float BitmapFont::get_height() const{ +float BitmapFont::get_height() const { return height; } -void BitmapFont::set_ascent(float p_ascent){ +void BitmapFont::set_ascent(float p_ascent) { - ascent=p_ascent; + ascent = p_ascent; } float BitmapFont::get_ascent() const { @@ -358,13 +338,13 @@ float BitmapFont::get_ascent() const { } float BitmapFont::get_descent() const { - return height-ascent; + return height - ascent; } -void BitmapFont::add_texture(const Ref<Texture>& p_texture) { +void BitmapFont::add_texture(const Ref<Texture> &p_texture) { - ERR_FAIL_COND( p_texture.is_null()); - textures.push_back( p_texture ); + ERR_FAIL_COND(p_texture.is_null()); + textures.push_back(p_texture); } int BitmapFont::get_texture_count() const { @@ -387,9 +367,9 @@ Vector<CharType> BitmapFont::get_char_keys() const { Vector<CharType> chars; chars.resize(char_map.size()); - const CharType* ct = NULL; + const CharType *ct = NULL; int count = 0; - while ( (ct = char_map.next(ct)) ) { + while ((ct = char_map.next(ct))) { chars[count++] = *ct; }; @@ -406,60 +386,56 @@ BitmapFont::Character BitmapFont::get_character(CharType p_char) const { return char_map[p_char]; }; -void BitmapFont::add_char(CharType p_char, int p_texture_idx, const Rect2& p_rect, const Size2& p_align, float p_advance) { +void BitmapFont::add_char(CharType p_char, int p_texture_idx, const Rect2 &p_rect, const Size2 &p_align, float p_advance) { - if (p_advance<0) - p_advance=p_rect.size.width; + if (p_advance < 0) + p_advance = p_rect.size.width; Character c; - c.rect=p_rect; - c.texture_idx=p_texture_idx; - c.v_align=p_align.y; - c.advance=p_advance; - c.h_align=p_align.x; + c.rect = p_rect; + c.texture_idx = p_texture_idx; + c.v_align = p_align.y; + c.advance = p_advance; + c.h_align = p_align.x; - char_map[p_char]=c; + char_map[p_char] = c; } -void BitmapFont::add_kerning_pair(CharType p_A,CharType p_B,int p_kerning) { - +void BitmapFont::add_kerning_pair(CharType p_A, CharType p_B, int p_kerning) { KerningPairKey kpk; - kpk.A=p_A; - kpk.B=p_B; + kpk.A = p_A; + kpk.B = p_B; - if (p_kerning==0 && kerning_map.has(kpk)) { + if (p_kerning == 0 && kerning_map.has(kpk)) { kerning_map.erase(kpk); } else { - kerning_map[kpk]=p_kerning; + kerning_map[kpk] = p_kerning; } } Vector<BitmapFont::KerningPairKey> BitmapFont::get_kerning_pair_keys() const { - Vector<BitmapFont::KerningPairKey> ret; ret.resize(kerning_map.size()); - int i=0; - - for (Map<KerningPairKey,int>::Element *E=kerning_map.front();E;E=E->next()) { - ret[i++]=E->key(); + int i = 0; + for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) { + ret[i++] = E->key(); } return ret; - } -int BitmapFont::get_kerning_pair(CharType p_A,CharType p_B) const { +int BitmapFont::get_kerning_pair(CharType p_A, CharType p_B) const { KerningPairKey kpk; - kpk.A=p_A; - kpk.B=p_B; + kpk.A = p_A; + kpk.B = p_B; - const Map<KerningPairKey,int>::Element *E=kerning_map.find(kpk); + const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk); if (E) return E->get(); @@ -468,96 +444,94 @@ int BitmapFont::get_kerning_pair(CharType p_A,CharType p_B) const { void BitmapFont::set_distance_field_hint(bool p_distance_field) { - distance_field_hint=p_distance_field; + distance_field_hint = p_distance_field; emit_changed(); } -bool BitmapFont::is_distance_field_hint() const{ +bool BitmapFont::is_distance_field_hint() const { return distance_field_hint; } - void BitmapFont::clear() { - height=1; - ascent=0; + height = 1; + ascent = 0; char_map.clear(); textures.clear(); kerning_map.clear(); - distance_field_hint=false; + distance_field_hint = false; } -Size2 Font::get_string_size(const String& p_string) const { +Size2 Font::get_string_size(const String &p_string) const { - float w=0; + float w = 0; int l = p_string.length(); - if (l==0) - return Size2(0,get_height()); + if (l == 0) + return Size2(0, get_height()); const CharType *sptr = &p_string[0]; - for (int i=0;i<l;i++) { + for (int i = 0; i < l; i++) { - w+=get_char_size(sptr[i],sptr[i+1]).width; + w += get_char_size(sptr[i], sptr[i + 1]).width; } - return Size2(w,get_height()); + return Size2(w, get_height()); } void BitmapFont::set_fallback(const Ref<BitmapFont> &p_fallback) { - fallback=p_fallback; + fallback = p_fallback; } -Ref<BitmapFont> BitmapFont::get_fallback() const{ +Ref<BitmapFont> BitmapFont::get_fallback() const { return fallback; } -float BitmapFont::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char, CharType p_next, const Color& p_modulate) const { +float BitmapFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const { - const Character * c = char_map.getptr(p_char); + const Character *c = char_map.getptr(p_char); if (!c) { if (fallback.is_valid()) - return fallback->draw_char(p_canvas_item,p_pos,p_char,p_next,p_modulate); + return fallback->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate); return 0; } - Point2 cpos=p_pos; - cpos.x+=c->h_align; - cpos.y-=ascent; - cpos.y+=c->v_align; - ERR_FAIL_COND_V( c->texture_idx<-1 || c->texture_idx>=textures.size(),0); - if (c->texture_idx!=-1) - VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, c->rect.size ), textures[c->texture_idx]->get_rid(),c->rect, p_modulate ); + Point2 cpos = p_pos; + cpos.x += c->h_align; + cpos.y -= ascent; + cpos.y += c->v_align; + ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0); + if (c->texture_idx != -1) + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx]->get_rid(), c->rect, p_modulate); - return get_char_size(p_char,p_next).width; + return get_char_size(p_char, p_next).width; } +Size2 BitmapFont::get_char_size(CharType p_char, CharType p_next) const { -Size2 BitmapFont::get_char_size(CharType p_char,CharType p_next) const { - - const Character * c = char_map.getptr(p_char); + const Character *c = char_map.getptr(p_char); if (!c) { if (fallback.is_valid()) - return fallback->get_char_size(p_char,p_next); + return fallback->get_char_size(p_char, p_next); return Size2(); } - Size2 ret(c->advance,c->rect.size.y); + Size2 ret(c->advance, c->rect.size.y); if (p_next) { KerningPairKey kpk; - kpk.A=p_char; - kpk.B=p_next; + kpk.A = p_char; + kpk.B = p_next; - const Map<KerningPairKey,int>::Element *E=kerning_map.find(kpk); + const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk); if (E) { - ret.width-=E->get(); + ret.width -= E->get(); } } @@ -566,63 +540,54 @@ Size2 BitmapFont::get_char_size(CharType p_char,CharType p_next) const { void BitmapFont::_bind_methods() { - ClassDB::bind_method(D_METHOD("create_from_fnt","path"),&BitmapFont::create_from_fnt); - ClassDB::bind_method(D_METHOD("set_height","px"),&BitmapFont::set_height); + ClassDB::bind_method(D_METHOD("create_from_fnt", "path"), &BitmapFont::create_from_fnt); + ClassDB::bind_method(D_METHOD("set_height", "px"), &BitmapFont::set_height); - ClassDB::bind_method(D_METHOD("set_ascent","px"),&BitmapFont::set_ascent); + ClassDB::bind_method(D_METHOD("set_ascent", "px"), &BitmapFont::set_ascent); - ClassDB::bind_method(D_METHOD("add_kerning_pair","char_a","char_b","kerning"),&BitmapFont::add_kerning_pair); - ClassDB::bind_method(D_METHOD("get_kerning_pair","char_a","char_b"),&BitmapFont::get_kerning_pair); + ClassDB::bind_method(D_METHOD("add_kerning_pair", "char_a", "char_b", "kerning"), &BitmapFont::add_kerning_pair); + ClassDB::bind_method(D_METHOD("get_kerning_pair", "char_a", "char_b"), &BitmapFont::get_kerning_pair); - ClassDB::bind_method(D_METHOD("add_texture","texture:Texture"),&BitmapFont::add_texture); - ClassDB::bind_method(D_METHOD("add_char","character","texture","rect","align","advance"),&BitmapFont::add_char,DEFVAL(Point2()),DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("add_texture", "texture:Texture"), &BitmapFont::add_texture); + ClassDB::bind_method(D_METHOD("add_char", "character", "texture", "rect", "align", "advance"), &BitmapFont::add_char, DEFVAL(Point2()), DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("get_texture_count"), &BitmapFont::get_texture_count); + ClassDB::bind_method(D_METHOD("get_texture:Texture", "idx"), &BitmapFont::get_texture); - ClassDB::bind_method(D_METHOD("get_texture_count"),&BitmapFont::get_texture_count); - ClassDB::bind_method(D_METHOD("get_texture:Texture","idx"),&BitmapFont::get_texture); + ClassDB::bind_method(D_METHOD("get_char_size", "char", "next"), &BitmapFont::get_char_size, DEFVAL(0)); - ClassDB::bind_method(D_METHOD("get_char_size","char","next"),&BitmapFont::get_char_size,DEFVAL(0)); + ClassDB::bind_method(D_METHOD("set_distance_field_hint", "enable"), &BitmapFont::set_distance_field_hint); - ClassDB::bind_method(D_METHOD("set_distance_field_hint","enable"),&BitmapFont::set_distance_field_hint); + ClassDB::bind_method(D_METHOD("clear"), &BitmapFont::clear); - ClassDB::bind_method(D_METHOD("clear"),&BitmapFont::clear); + ClassDB::bind_method(D_METHOD("_set_chars"), &BitmapFont::_set_chars); + ClassDB::bind_method(D_METHOD("_get_chars"), &BitmapFont::_get_chars); + ClassDB::bind_method(D_METHOD("_set_kernings"), &BitmapFont::_set_kernings); + ClassDB::bind_method(D_METHOD("_get_kernings"), &BitmapFont::_get_kernings); - ClassDB::bind_method(D_METHOD("_set_chars"),&BitmapFont::_set_chars); - ClassDB::bind_method(D_METHOD("_get_chars"),&BitmapFont::_get_chars); + ClassDB::bind_method(D_METHOD("_set_textures"), &BitmapFont::_set_textures); + ClassDB::bind_method(D_METHOD("_get_textures"), &BitmapFont::_get_textures); - ClassDB::bind_method(D_METHOD("_set_kernings"),&BitmapFont::_set_kernings); - ClassDB::bind_method(D_METHOD("_get_kernings"),&BitmapFont::_get_kernings); + ClassDB::bind_method(D_METHOD("set_fallback", "fallback"), &BitmapFont::set_fallback); + ClassDB::bind_method(D_METHOD("get_fallback"), &BitmapFont::get_fallback); - ClassDB::bind_method(D_METHOD("_set_textures"),&BitmapFont::_set_textures); - ClassDB::bind_method(D_METHOD("_get_textures"),&BitmapFont::_get_textures); - - ClassDB::bind_method(D_METHOD("set_fallback","fallback"),&BitmapFont::set_fallback); - ClassDB::bind_method(D_METHOD("get_fallback"),&BitmapFont::get_fallback); - - ADD_PROPERTY( PropertyInfo( Variant::ARRAY, "textures", PROPERTY_HINT_NONE,"", PROPERTY_USAGE_NOEDITOR ), "_set_textures", "_get_textures") ; - ADD_PROPERTY( PropertyInfo( Variant::POOL_INT_ARRAY, "chars", PROPERTY_HINT_NONE,"", PROPERTY_USAGE_NOEDITOR ), "_set_chars", "_get_chars") ; - ADD_PROPERTY( PropertyInfo( Variant::POOL_INT_ARRAY, "kernings", PROPERTY_HINT_NONE,"", PROPERTY_USAGE_NOEDITOR ), "_set_kernings", "_get_kernings") ; - - ADD_PROPERTY( PropertyInfo( Variant::REAL, "height", PROPERTY_HINT_RANGE,"-1024,1024,1" ), "set_height", "get_height") ; - ADD_PROPERTY( PropertyInfo( Variant::REAL, "ascent", PROPERTY_HINT_RANGE,"-1024,1024,1" ), "set_ascent", "get_ascent") ; - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "distance_field" ), "set_distance_field_hint", "is_distance_field_hint") ; - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "fallback", PROPERTY_HINT_RESOURCE_TYPE,"BitmapFont" ), "set_fallback", "get_fallback") ; + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_textures", "_get_textures"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "chars", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_chars", "_get_chars"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "kernings", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_kernings", "_get_kernings"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "-1024,1024,1"), "set_height", "get_height"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "ascent", PROPERTY_HINT_RANGE, "-1024,1024,1"), "set_ascent", "get_ascent"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "distance_field"), "set_distance_field_hint", "is_distance_field_hint"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "fallback", PROPERTY_HINT_RESOURCE_TYPE, "BitmapFont"), "set_fallback", "get_fallback"); } BitmapFont::BitmapFont() { clear(); - - - } - BitmapFont::~BitmapFont() { clear(); } - - diff --git a/scene/resources/font.h b/scene/resources/font.h index ad0f0176db..332017684d 100644 --- a/scene/resources/font.h +++ b/scene/resources/font.h @@ -29,50 +29,45 @@ #ifndef FONT_H #define FONT_H +#include "map.h" #include "resource.h" #include "scene/resources/texture.h" -#include "map.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - class Font : public Resource { - GDCLASS( Font, Resource ); + GDCLASS(Font, Resource); protected: - static void _bind_methods(); public: + virtual float get_height() const = 0; - virtual float get_height() const=0; + virtual float get_ascent() const = 0; + virtual float get_descent() const = 0; - virtual float get_ascent() const=0; - virtual float get_descent() const=0; + virtual Size2 get_char_size(CharType p_char, CharType p_next = 0) const = 0; + Size2 get_string_size(const String &p_string) const; - virtual Size2 get_char_size(CharType p_char,CharType p_next=0) const=0; - Size2 get_string_size(const String& p_string) const; + virtual bool is_distance_field_hint() const = 0; - virtual bool is_distance_field_hint() const=0; - - void draw(RID p_canvas_item, const Point2& p_pos, const String& p_text,const Color& p_modulate=Color(1,1,1),int p_clip_w=-1) const; - void draw_halign(RID p_canvas_item, const Point2& p_pos, HAlign p_align,float p_width,const String& p_text,const Color& p_modulate=Color(1,1,1)) const; - virtual float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char, CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const=0; + void draw(RID p_canvas_item, const Point2 &p_pos, const String &p_text, const Color &p_modulate = Color(1, 1, 1), int p_clip_w = -1) const; + void draw_halign(RID p_canvas_item, const Point2 &p_pos, HAlign p_align, float p_width, const String &p_text, const Color &p_modulate = Color(1, 1, 1)) const; + virtual float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const = 0; void update_changes(); Font(); - }; - class BitmapFont : public Font { - GDCLASS( BitmapFont, Font ); + GDCLASS(BitmapFont, Font); RES_BASE_EXTENSION("fnt"); - Vector< Ref<Texture> > textures; + Vector<Ref<Texture> > textures; public: struct Character { @@ -83,47 +78,47 @@ public: float h_align; float advance; - Character() { texture_idx=0; v_align=0; } + Character() { + texture_idx = 0; + v_align = 0; + } }; struct KerningPairKey { union { struct { - uint32_t A,B; + uint32_t A, B; }; uint64_t pair; }; - _FORCE_INLINE_ bool operator<(const KerningPairKey& p_r) const { return pair<p_r.pair; } + _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; } }; private: - - - HashMap< CharType, Character > char_map; - Map<KerningPairKey,int> kerning_map; + HashMap<CharType, Character> char_map; + Map<KerningPairKey, int> kerning_map; float height; float ascent; bool distance_field_hint; - void _set_chars(const PoolVector<int>& p_chars); + void _set_chars(const PoolVector<int> &p_chars); PoolVector<int> _get_chars() const; - void _set_kernings(const PoolVector<int>& p_kernings); + void _set_kernings(const PoolVector<int> &p_kernings); PoolVector<int> _get_kernings() const; - void _set_textures(const Vector<Variant> & p_textures); + void _set_textures(const Vector<Variant> &p_textures); Vector<Variant> _get_textures() const; Ref<BitmapFont> fallback; -protected: +protected: static void _bind_methods(); public: - - Error create_from_fnt(const String& p_file); + Error create_from_fnt(const String &p_file); void set_height(float p_height); float get_height() const; @@ -132,8 +127,8 @@ public: float get_ascent() const; float get_descent() const; - void add_texture(const Ref<Texture>& p_texture); - void add_char(CharType p_char, int p_texture_idx, const Rect2& p_rect, const Size2& p_align, float p_advance=-1); + void add_texture(const Ref<Texture> &p_texture); + void add_char(CharType p_char, int p_texture_idx, const Rect2 &p_rect, const Size2 &p_align, float p_advance = -1); int get_character_count() const; Vector<CharType> get_char_keys() const; @@ -142,11 +137,11 @@ public: int get_texture_count() const; Ref<Texture> get_texture(int p_idx) const; - void add_kerning_pair(CharType p_A,CharType p_B,int p_kerning); - int get_kerning_pair(CharType p_A,CharType p_B) const; + void add_kerning_pair(CharType p_A, CharType p_B, int p_kerning); + int get_kerning_pair(CharType p_A, CharType p_B) const; Vector<KerningPairKey> get_kerning_pair_keys() const; - Size2 get_char_size(CharType p_char,CharType p_next=0) const; + Size2 get_char_size(CharType p_char, CharType p_next = 0) const; void set_fallback(const Ref<BitmapFont> &p_fallback); Ref<BitmapFont> get_fallback() const; @@ -156,14 +151,10 @@ public: void set_distance_field_hint(bool p_distance_field); bool is_distance_field_hint() const; - float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const; + float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const; BitmapFont(); ~BitmapFont(); }; - - - - #endif diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp index 3780c466a5..410f4962fa 100644 --- a/scene/resources/material.cpp +++ b/scene/resources/material.cpp @@ -36,7 +36,7 @@ RID Material::get_rid() const { Material::Material() { - material=VisualServer::get_singleton()->material_create(); + material = VisualServer::get_singleton()->material_create(); } Material::~Material() { @@ -44,13 +44,12 @@ Material::~Material() { VisualServer::get_singleton()->free(material); } - ///////////////////////////////// -Mutex *FixedSpatialMaterial::material_mutex=NULL; +Mutex *FixedSpatialMaterial::material_mutex = NULL; SelfList<FixedSpatialMaterial>::List FixedSpatialMaterial::dirty_materials; -Map<FixedSpatialMaterial::MaterialKey,FixedSpatialMaterial::ShaderData> FixedSpatialMaterial::shader_map; -FixedSpatialMaterial::ShaderNames* FixedSpatialMaterial::shader_names=NULL; +Map<FixedSpatialMaterial::MaterialKey, FixedSpatialMaterial::ShaderData> FixedSpatialMaterial::shader_map; +FixedSpatialMaterial::ShaderNames *FixedSpatialMaterial::shader_names = NULL; void FixedSpatialMaterial::init_shaders() { @@ -58,303 +57,293 @@ void FixedSpatialMaterial::init_shaders() { material_mutex = Mutex::create(); #endif - shader_names = memnew( ShaderNames ); - - shader_names->albedo="albedo"; - shader_names->specular="specular"; - shader_names->roughness="roughness"; - shader_names->metalness="metalness"; - shader_names->emission="emission"; - shader_names->emission_energy="emission_energy"; - shader_names->normal_scale="normal_scale"; - shader_names->rim="rim"; - shader_names->rim_tint="rim_tint"; - shader_names->clearcoat="clearcoat"; - shader_names->clearcoat_gloss="clearcoat_gloss"; - shader_names->anisotropy="anisotropy_ratio"; - shader_names->height_scale="height_scale"; - shader_names->subsurface_scattering_strength="subsurface_scattering_strength"; - shader_names->refraction="refraction"; - shader_names->refraction_roughness="refraction_roughness"; - shader_names->point_size="point_size"; - shader_names->uv1_scale="uv1_scale"; - shader_names->uv1_offset="uv1_offset"; - shader_names->uv2_scale="uv2_scale"; - shader_names->uv2_offset="uv2_offset"; - - shader_names->texture_names[TEXTURE_ALBEDO]="texture_albedo"; - shader_names->texture_names[TEXTURE_SPECULAR]="texture_specular"; - shader_names->texture_names[TEXTURE_EMISSION]="texture_emission"; - shader_names->texture_names[TEXTURE_NORMAL]="texture_normal"; - shader_names->texture_names[TEXTURE_RIM]="texture_rim"; - shader_names->texture_names[TEXTURE_CLEARCOAT]="texture_clearcoat"; - shader_names->texture_names[TEXTURE_FLOWMAP]="texture_flowmap"; - shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION]="texture_ambient_occlusion"; - shader_names->texture_names[TEXTURE_HEIGHT]="texture_height"; - shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING]="texture_subsurface_scattering"; - shader_names->texture_names[TEXTURE_REFRACTION]="texture_refraction"; - shader_names->texture_names[TEXTURE_REFRACTION_ROUGHNESS]="texture_refraction_roughness"; - shader_names->texture_names[TEXTURE_DETAIL_MASK]="texture_detail_mask"; - shader_names->texture_names[TEXTURE_DETAIL_ALBEDO]="texture_detail_albedo"; - shader_names->texture_names[TEXTURE_DETAIL_NORMAL]="texture_detail_normal"; - -} - -void FixedSpatialMaterial::finish_shaders(){ + shader_names = memnew(ShaderNames); + + shader_names->albedo = "albedo"; + shader_names->specular = "specular"; + shader_names->roughness = "roughness"; + shader_names->metalness = "metalness"; + shader_names->emission = "emission"; + shader_names->emission_energy = "emission_energy"; + shader_names->normal_scale = "normal_scale"; + shader_names->rim = "rim"; + shader_names->rim_tint = "rim_tint"; + shader_names->clearcoat = "clearcoat"; + shader_names->clearcoat_gloss = "clearcoat_gloss"; + shader_names->anisotropy = "anisotropy_ratio"; + shader_names->height_scale = "height_scale"; + shader_names->subsurface_scattering_strength = "subsurface_scattering_strength"; + shader_names->refraction = "refraction"; + shader_names->refraction_roughness = "refraction_roughness"; + shader_names->point_size = "point_size"; + shader_names->uv1_scale = "uv1_scale"; + shader_names->uv1_offset = "uv1_offset"; + shader_names->uv2_scale = "uv2_scale"; + shader_names->uv2_offset = "uv2_offset"; + + shader_names->texture_names[TEXTURE_ALBEDO] = "texture_albedo"; + shader_names->texture_names[TEXTURE_SPECULAR] = "texture_specular"; + shader_names->texture_names[TEXTURE_EMISSION] = "texture_emission"; + shader_names->texture_names[TEXTURE_NORMAL] = "texture_normal"; + shader_names->texture_names[TEXTURE_RIM] = "texture_rim"; + shader_names->texture_names[TEXTURE_CLEARCOAT] = "texture_clearcoat"; + shader_names->texture_names[TEXTURE_FLOWMAP] = "texture_flowmap"; + shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION] = "texture_ambient_occlusion"; + shader_names->texture_names[TEXTURE_HEIGHT] = "texture_height"; + shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING] = "texture_subsurface_scattering"; + shader_names->texture_names[TEXTURE_REFRACTION] = "texture_refraction"; + shader_names->texture_names[TEXTURE_REFRACTION_ROUGHNESS] = "texture_refraction_roughness"; + shader_names->texture_names[TEXTURE_DETAIL_MASK] = "texture_detail_mask"; + shader_names->texture_names[TEXTURE_DETAIL_ALBEDO] = "texture_detail_albedo"; + shader_names->texture_names[TEXTURE_DETAIL_NORMAL] = "texture_detail_normal"; +} + +void FixedSpatialMaterial::finish_shaders() { #ifndef NO_THREADS - memdelete( material_mutex ); + memdelete(material_mutex); #endif - memdelete( shader_names ); - + memdelete(shader_names); } - - void FixedSpatialMaterial::_update_shader() { - dirty_materials.remove( &element ); + dirty_materials.remove(&element); MaterialKey mk = _compute_key(); - if (mk.key==current_key.key) + if (mk.key == current_key.key) return; //no update required in the end if (shader_map.has(current_key)) { shader_map[current_key].users--; - if (shader_map[current_key].users==0) { + if (shader_map[current_key].users == 0) { //deallocate shader, as it's no longer in use VS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } } - current_key=mk; + current_key = mk; if (shader_map.has(mk)) { - VS::get_singleton()->material_set_shader(_get_material(),shader_map[mk].shader); + VS::get_singleton()->material_set_shader(_get_material(), shader_map[mk].shader); shader_map[mk].users++; return; } //must create a shader! - String code="render_mode "; - switch(blend_mode) { - case BLEND_MODE_MIX: code+="blend_mix"; break; - case BLEND_MODE_ADD: code+="blend_add"; break; - case BLEND_MODE_SUB: code+="blend_sub"; break; - case BLEND_MODE_MUL: code+="blend_mul"; break; + String code = "render_mode "; + switch (blend_mode) { + case BLEND_MODE_MIX: code += "blend_mix"; break; + case BLEND_MODE_ADD: code += "blend_add"; break; + case BLEND_MODE_SUB: code += "blend_sub"; break; + case BLEND_MODE_MUL: code += "blend_mul"; break; } - switch(depth_draw_mode) { - case DEPTH_DRAW_OPAQUE_ONLY: code+=",depth_draw_opaque"; break; - case DEPTH_DRAW_ALWAYS: code+=",depth_draw_always"; break; - case DEPTH_DRAW_DISABLED: code+=",depth_draw_never"; break; - case DEPTH_DRAW_ALPHA_OPAQUE_PREPASS: code+=",depth_draw_alpha_prepass"; break; + switch (depth_draw_mode) { + case DEPTH_DRAW_OPAQUE_ONLY: code += ",depth_draw_opaque"; break; + case DEPTH_DRAW_ALWAYS: code += ",depth_draw_always"; break; + case DEPTH_DRAW_DISABLED: code += ",depth_draw_never"; break; + case DEPTH_DRAW_ALPHA_OPAQUE_PREPASS: code += ",depth_draw_alpha_prepass"; break; } - switch(cull_mode) { - case CULL_BACK: code+=",cull_back"; break; - case CULL_FRONT: code+=",cull_front"; break; - case CULL_DISABLED: code+=",cull_disabled"; break; - + switch (cull_mode) { + case CULL_BACK: code += ",cull_back"; break; + case CULL_FRONT: code += ",cull_front"; break; + case CULL_DISABLED: code += ",cull_disabled"; break; } if (flags[FLAG_UNSHADED]) { - code+=",unshaded"; + code += ",unshaded"; } if (flags[FLAG_ONTOP]) { - code+=",ontop"; + code += ",ontop"; } - code+=";\n"; - + code += ";\n"; - code+="uniform vec4 albedo : hint_color;\n"; - code+="uniform sampler2D texture_albedo : hint_albedo;\n"; - if (specular_mode==SPECULAR_MODE_SPECULAR) { - code+="uniform vec4 specular : hint_color;\n"; + code += "uniform vec4 albedo : hint_color;\n"; + code += "uniform sampler2D texture_albedo : hint_albedo;\n"; + if (specular_mode == SPECULAR_MODE_SPECULAR) { + code += "uniform vec4 specular : hint_color;\n"; } else { - code+="uniform float metalness;\n"; + code += "uniform float metalness;\n"; } - code+="uniform float roughness : hint_range(0,1);\n"; - code+="uniform float point_size : hint_range(0,128);\n"; - code+="uniform sampler2D texture_specular : hint_white;\n"; - code+="uniform vec2 uv1_scale;\n"; - code+="uniform vec2 uv1_offset;\n"; - code+="uniform vec2 uv2_scale;\n"; - code+="uniform vec2 uv2_offset;\n"; + code += "uniform float roughness : hint_range(0,1);\n"; + code += "uniform float point_size : hint_range(0,128);\n"; + code += "uniform sampler2D texture_specular : hint_white;\n"; + code += "uniform vec2 uv1_scale;\n"; + code += "uniform vec2 uv1_offset;\n"; + code += "uniform vec2 uv2_scale;\n"; + code += "uniform vec2 uv2_offset;\n"; if (features[FEATURE_EMISSION]) { - code+="uniform sampler2D texture_emission : hint_black_albedo;\n"; - code+="uniform vec4 emission : hint_color;\n"; - code+="uniform float emission_energy;\n"; + code += "uniform sampler2D texture_emission : hint_black_albedo;\n"; + code += "uniform vec4 emission : hint_color;\n"; + code += "uniform float emission_energy;\n"; } if (features[FEATURE_NORMAL_MAPPING]) { - code+="uniform sampler2D texture_normal : hint_normal;\n"; - code+="uniform float normal_scale : hint_range(-16,16);\n"; + code += "uniform sampler2D texture_normal : hint_normal;\n"; + code += "uniform float normal_scale : hint_range(-16,16);\n"; } if (features[FEATURE_RIM]) { - code+="uniform float rim : hint_range(0,1);\n"; - code+="uniform float rim_tint : hint_range(0,1);\n"; - code+="uniform sampler2D texture_rim : hint_white;\n"; + code += "uniform float rim : hint_range(0,1);\n"; + code += "uniform float rim_tint : hint_range(0,1);\n"; + code += "uniform sampler2D texture_rim : hint_white;\n"; } if (features[FEATURE_CLEARCOAT]) { - code+="uniform float clearcoat : hint_range(0,1);\n"; - code+="uniform float clearcoat_gloss : hint_range(0,1);\n"; - code+="uniform sampler2D texture_clearcoat : hint_white;\n"; + code += "uniform float clearcoat : hint_range(0,1);\n"; + code += "uniform float clearcoat_gloss : hint_range(0,1);\n"; + code += "uniform sampler2D texture_clearcoat : hint_white;\n"; } if (features[FEATURE_ANISOTROPY]) { - code+="uniform float anisotropy_ratio : hint_range(0,256);\n"; - code+="uniform sampler2D texture_flowmap : hint_aniso;\n"; + code += "uniform float anisotropy_ratio : hint_range(0,256);\n"; + code += "uniform sampler2D texture_flowmap : hint_aniso;\n"; } if (features[FEATURE_AMBIENT_OCCLUSION]) { - code+="uniform sampler2D texture_ambient_occlusion : hint_white;\n"; + code += "uniform sampler2D texture_ambient_occlusion : hint_white;\n"; } if (features[FEATURE_DETAIL]) { - code+="uniform sampler2D texture_detail_albedo : hint_albedo;\n"; - code+="uniform sampler2D texture_detail_normal : hint_normal;\n"; - code+="uniform sampler2D texture_detail_mask : hint_white;\n"; + code += "uniform sampler2D texture_detail_albedo : hint_albedo;\n"; + code += "uniform sampler2D texture_detail_normal : hint_normal;\n"; + code += "uniform sampler2D texture_detail_mask : hint_white;\n"; } if (features[FEATURE_SUBSURACE_SCATTERING]) { - code+="uniform float subsurface_scattering_strength : hint_range(0,1);\n"; - code+="uniform sampler2D texture_subsurface_scattering : hint_white;\n"; - + code += "uniform float subsurface_scattering_strength : hint_range(0,1);\n"; + code += "uniform sampler2D texture_subsurface_scattering : hint_white;\n"; } + code += "\n\n"; - code+="\n\n"; - - code+="void vertex() {\n"; + code += "void vertex() {\n"; if (flags[FLAG_SRGB_VERTEX_COLOR]) { - code+="\tCOLOR.rgb = mix( pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb* (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)) );\n"; + code += "\tCOLOR.rgb = mix( pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb* (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)) );\n"; } if (flags[FLAG_USE_POINT_SIZE]) { - code+="\tPOINT_SIZE=point_size;\n"; + code += "\tPOINT_SIZE=point_size;\n"; } - code+="\tUV=UV*uv1_scale+uv1_offset;\n"; - if (detail_uv==DETAIL_UV_2) { - code+="\tUV2=UV2*uv2_scale+uv2_offset;\n"; + code += "\tUV=UV*uv1_scale+uv1_offset;\n"; + if (detail_uv == DETAIL_UV_2) { + code += "\tUV2=UV2*uv2_scale+uv2_offset;\n"; } - code+="}\n"; - code+="\n\n"; - code+="void fragment() {\n"; + code += "}\n"; + code += "\n\n"; + code += "void fragment() {\n"; if (flags[FLAG_USE_POINT_SIZE]) { - code+="\tvec4 albedo_tex = texture(texture_albedo,POINT_COORD);\n"; + code += "\tvec4 albedo_tex = texture(texture_albedo,POINT_COORD);\n"; } else { - code+="\tvec4 albedo_tex = texture(texture_albedo,UV);\n"; + code += "\tvec4 albedo_tex = texture(texture_albedo,UV);\n"; } if (flags[FLAG_ALBEDO_FROM_VERTEX_COLOR]) { - code+="\talbedo_tex *= COLOR;\n"; + code += "\talbedo_tex *= COLOR;\n"; } - code+="\tALBEDO = albedo.rgb * albedo_tex.rgb;\n"; + code += "\tALBEDO = albedo.rgb * albedo_tex.rgb;\n"; if (features[FEATURE_TRANSPARENT]) { - code+="\tALPHA = albedo.a * albedo_tex.a;\n"; + code += "\tALPHA = albedo.a * albedo_tex.a;\n"; } if (features[FEATURE_EMISSION]) { - code+="\tEMISSION = (emission.rgb+texture(texture_emission,UV).rgb)*emission_energy;\n"; + code += "\tEMISSION = (emission.rgb+texture(texture_emission,UV).rgb)*emission_energy;\n"; } if (features[FEATURE_NORMAL_MAPPING]) { - code+="\tNORMALMAP = texture(texture_normal,UV).rgb;\n"; - code+="\tNORMALMAP_DEPTH = normal_scale;\n"; + code += "\tNORMALMAP = texture(texture_normal,UV).rgb;\n"; + code += "\tNORMALMAP_DEPTH = normal_scale;\n"; } if (features[FEATURE_RIM]) { - code+="\tvec2 rim_tex = texture(texture_rim,UV).xw;\n"; - code+="\tRIM = rim*rim_tex.x;"; - code+="\tRIM_TINT = rim_tint*rim_tex.y;\n"; + code += "\tvec2 rim_tex = texture(texture_rim,UV).xw;\n"; + code += "\tRIM = rim*rim_tex.x;"; + code += "\tRIM_TINT = rim_tint*rim_tex.y;\n"; } if (features[FEATURE_CLEARCOAT]) { - code+="\tvec2 clearcoat_tex = texture(texture_clearcoat,UV).xw;\n"; - code+="\tCLEARCOAT = clearcoat*clearcoat_tex.x;"; - code+="\tCLEARCOAT_GLOSS = clearcoat_gloss*clearcoat_tex.y;\n"; + code += "\tvec2 clearcoat_tex = texture(texture_clearcoat,UV).xw;\n"; + code += "\tCLEARCOAT = clearcoat*clearcoat_tex.x;"; + code += "\tCLEARCOAT_GLOSS = clearcoat_gloss*clearcoat_tex.y;\n"; } if (features[FEATURE_ANISOTROPY]) { - code+="\tvec4 anisotropy_tex = texture(texture_flowmap,UV);\n"; - code+="\tANISOTROPY = anisotropy_ratio*anisotropy_tex.a;\n"; - code+="\tANISOTROPY_FLOW = anisotropy_tex.rg*2.0-1.0;\n"; + code += "\tvec4 anisotropy_tex = texture(texture_flowmap,UV);\n"; + code += "\tANISOTROPY = anisotropy_ratio*anisotropy_tex.a;\n"; + code += "\tANISOTROPY_FLOW = anisotropy_tex.rg*2.0-1.0;\n"; } if (features[FEATURE_AMBIENT_OCCLUSION]) { - code+="\tAO = texture(texture_ambient_occlusion,UV).r;\n"; + code += "\tAO = texture(texture_ambient_occlusion,UV).r;\n"; } if (features[FEATURE_SUBSURACE_SCATTERING]) { - code+="\tfloat sss_tex = texture(texture_subsurface_scattering,UV).r;\n"; - code+="\tSSS_STRENGTH=subsurface_scattering_strength*sss_tex;\n"; + code += "\tfloat sss_tex = texture(texture_subsurface_scattering,UV).r;\n"; + code += "\tSSS_STRENGTH=subsurface_scattering_strength*sss_tex;\n"; } if (features[FEATURE_DETAIL]) { - String det_uv=detail_uv==DETAIL_UV_1?"UV":"UV2"; - code+="\tvec4 detail_tex = texture(texture_detail_albedo,"+det_uv+");\n"; - code+="\tvec4 detail_norm_tex = texture(texture_detail_normal,"+det_uv+");\n"; - code+="\tvec4 detail_mask_tex = texture(texture_detail_mask,UV);\n"; + String det_uv = detail_uv == DETAIL_UV_1 ? "UV" : "UV2"; + code += "\tvec4 detail_tex = texture(texture_detail_albedo," + det_uv + ");\n"; + code += "\tvec4 detail_norm_tex = texture(texture_detail_normal," + det_uv + ");\n"; + code += "\tvec4 detail_mask_tex = texture(texture_detail_mask,UV);\n"; - switch(detail_blend_mode) { + switch (detail_blend_mode) { case BLEND_MODE_MIX: { - code+="\tvec3 detail = mix(ALBEDO.rgb,detail_tex.rgb,detail_tex.a);\n"; + code += "\tvec3 detail = mix(ALBEDO.rgb,detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_ADD: { - code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb+detail_tex.rgb,detail_tex.a);\n"; + code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb+detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_SUB: { - code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb-detail_tex.rgb,detail_tex.a);\n"; + code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb-detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_MUL: { - code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb*detail_tex.rgb,detail_tex.a);\n"; + code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb*detail_tex.rgb,detail_tex.a);\n"; } break; - } - code+="\tvec3 detail_norm = mix(NORMALMAP,detail_norm_tex.rgb,detail_tex.a);\n"; + code += "\tvec3 detail_norm = mix(NORMALMAP,detail_norm_tex.rgb,detail_tex.a);\n"; - code+="\tNORMALMAP = mix(NORMALMAP,detail_norm,detail_mask_tex.r);\n"; - code+="\tALBEDO.rgb = mix(ALBEDO.rgb,detail,detail_mask_tex.r);\n"; + code += "\tNORMALMAP = mix(NORMALMAP,detail_norm,detail_mask_tex.r);\n"; + code += "\tALBEDO.rgb = mix(ALBEDO.rgb,detail,detail_mask_tex.r);\n"; } - if (specular_mode==SPECULAR_MODE_SPECULAR) { + if (specular_mode == SPECULAR_MODE_SPECULAR) { - code+="\tvec4 specular_tex = texture(texture_specular,UV);\n"; - code+="\tSPECULAR = specular.rgb * specular_tex.rgb;\n"; - code+="\tROUGHNESS = specular_tex.a * roughness;\n"; + code += "\tvec4 specular_tex = texture(texture_specular,UV);\n"; + code += "\tSPECULAR = specular.rgb * specular_tex.rgb;\n"; + code += "\tROUGHNESS = specular_tex.a * roughness;\n"; } else { - code+="\tvec4 specular_tex = texture(texture_specular,UV);\n"; - code+="\tSPECULAR = vec3(ALBEDO.rgb * metalness * specular_tex.r);\n"; - code+="\tROUGHNESS = specular_tex.a * roughness;\n"; + code += "\tvec4 specular_tex = texture(texture_specular,UV);\n"; + code += "\tSPECULAR = vec3(ALBEDO.rgb * metalness * specular_tex.r);\n"; + code += "\tROUGHNESS = specular_tex.a * roughness;\n"; } - code+="}\n"; + code += "}\n"; ShaderData shader_data; shader_data.shader = VS::get_singleton()->shader_create(VS::SHADER_SPATIAL); - shader_data.users=1; - - VS::get_singleton()->shader_set_code( shader_data.shader, code ); + shader_data.users = 1; - shader_map[mk]=shader_data; + VS::get_singleton()->shader_set_code(shader_data.shader, code); - VS::get_singleton()->material_set_shader(_get_material(),shader_data.shader); + shader_map[mk] = shader_data; + VS::get_singleton()->material_set_shader(_get_material(), shader_data.shader); } void FixedSpatialMaterial::flush_changes() { @@ -382,38 +371,36 @@ void FixedSpatialMaterial::_queue_shader_change() { if (material_mutex) material_mutex->unlock(); - - } bool FixedSpatialMaterial::_is_shader_dirty() const { - bool dirty=false; + bool dirty = false; if (material_mutex) material_mutex->lock(); - dirty=element.in_list(); + dirty = element.in_list(); if (material_mutex) material_mutex->unlock(); return dirty; } -void FixedSpatialMaterial::set_albedo(const Color& p_albedo) { +void FixedSpatialMaterial::set_albedo(const Color &p_albedo) { - albedo=p_albedo; + albedo = p_albedo; - VS::get_singleton()->material_set_param(_get_material(),shader_names->albedo,p_albedo); + VS::get_singleton()->material_set_param(_get_material(), shader_names->albedo, p_albedo); } -Color FixedSpatialMaterial::get_albedo() const{ +Color FixedSpatialMaterial::get_albedo() const { return albedo; } void FixedSpatialMaterial::set_specular_mode(SpecularMode p_mode) { - specular_mode=p_mode; + specular_mode = p_mode; _change_notify(); _queue_shader_change(); } @@ -423,167 +410,146 @@ FixedSpatialMaterial::SpecularMode FixedSpatialMaterial::get_specular_mode() con return specular_mode; } -void FixedSpatialMaterial::set_specular(const Color& p_specular){ - - specular=p_specular; - VS::get_singleton()->material_set_param(_get_material(),shader_names->specular,p_specular); +void FixedSpatialMaterial::set_specular(const Color &p_specular) { + specular = p_specular; + VS::get_singleton()->material_set_param(_get_material(), shader_names->specular, p_specular); } -Color FixedSpatialMaterial::get_specular() const{ +Color FixedSpatialMaterial::get_specular() const { return specular; } -void FixedSpatialMaterial::set_roughness(float p_roughness){ - - roughness=p_roughness; - VS::get_singleton()->material_set_param(_get_material(),shader_names->roughness,p_roughness); +void FixedSpatialMaterial::set_roughness(float p_roughness) { + roughness = p_roughness; + VS::get_singleton()->material_set_param(_get_material(), shader_names->roughness, p_roughness); } - -float FixedSpatialMaterial::get_roughness() const{ +float FixedSpatialMaterial::get_roughness() const { return roughness; } -void FixedSpatialMaterial::set_metalness(float p_metalness){ +void FixedSpatialMaterial::set_metalness(float p_metalness) { - metalness=p_metalness; - VS::get_singleton()->material_set_param(_get_material(),shader_names->metalness,p_metalness); + metalness = p_metalness; + VS::get_singleton()->material_set_param(_get_material(), shader_names->metalness, p_metalness); } - -float FixedSpatialMaterial::get_metalness() const{ +float FixedSpatialMaterial::get_metalness() const { return metalness; } -void FixedSpatialMaterial::set_emission(const Color& p_emission){ - - emission=p_emission; - VS::get_singleton()->material_set_param(_get_material(),shader_names->emission,p_emission); +void FixedSpatialMaterial::set_emission(const Color &p_emission) { + emission = p_emission; + VS::get_singleton()->material_set_param(_get_material(), shader_names->emission, p_emission); } -Color FixedSpatialMaterial::get_emission() const{ +Color FixedSpatialMaterial::get_emission() const { return emission; } +void FixedSpatialMaterial::set_emission_energy(float p_emission_energy) { -void FixedSpatialMaterial::set_emission_energy(float p_emission_energy){ - - emission_energy=p_emission_energy; - VS::get_singleton()->material_set_param(_get_material(),shader_names->emission_energy,p_emission_energy); - + emission_energy = p_emission_energy; + VS::get_singleton()->material_set_param(_get_material(), shader_names->emission_energy, p_emission_energy); } -float FixedSpatialMaterial::get_emission_energy() const{ +float FixedSpatialMaterial::get_emission_energy() const { return emission_energy; } -void FixedSpatialMaterial::set_normal_scale(float p_normal_scale){ - - normal_scale=p_normal_scale; - VS::get_singleton()->material_set_param(_get_material(),shader_names->normal_scale,p_normal_scale); +void FixedSpatialMaterial::set_normal_scale(float p_normal_scale) { + normal_scale = p_normal_scale; + VS::get_singleton()->material_set_param(_get_material(), shader_names->normal_scale, p_normal_scale); } -float FixedSpatialMaterial::get_normal_scale() const{ +float FixedSpatialMaterial::get_normal_scale() const { return normal_scale; } -void FixedSpatialMaterial::set_rim(float p_rim){ - - rim=p_rim; - VS::get_singleton()->material_set_param(_get_material(),shader_names->rim,p_rim); - +void FixedSpatialMaterial::set_rim(float p_rim) { + rim = p_rim; + VS::get_singleton()->material_set_param(_get_material(), shader_names->rim, p_rim); } -float FixedSpatialMaterial::get_rim() const{ +float FixedSpatialMaterial::get_rim() const { return rim; } -void FixedSpatialMaterial::set_rim_tint(float p_rim_tint){ - - rim_tint=p_rim_tint; - VS::get_singleton()->material_set_param(_get_material(),shader_names->rim_tint,p_rim_tint); +void FixedSpatialMaterial::set_rim_tint(float p_rim_tint) { + rim_tint = p_rim_tint; + VS::get_singleton()->material_set_param(_get_material(), shader_names->rim_tint, p_rim_tint); } -float FixedSpatialMaterial::get_rim_tint() const{ +float FixedSpatialMaterial::get_rim_tint() const { return rim_tint; } -void FixedSpatialMaterial::set_clearcoat(float p_clearcoat){ - - clearcoat=p_clearcoat; - VS::get_singleton()->material_set_param(_get_material(),shader_names->clearcoat,p_clearcoat); +void FixedSpatialMaterial::set_clearcoat(float p_clearcoat) { + clearcoat = p_clearcoat; + VS::get_singleton()->material_set_param(_get_material(), shader_names->clearcoat, p_clearcoat); } -float FixedSpatialMaterial::get_clearcoat() const{ +float FixedSpatialMaterial::get_clearcoat() const { return clearcoat; } -void FixedSpatialMaterial::set_clearcoat_gloss(float p_clearcoat_gloss){ - - clearcoat_gloss=p_clearcoat_gloss; - VS::get_singleton()->material_set_param(_get_material(),shader_names->clearcoat_gloss,p_clearcoat_gloss); - +void FixedSpatialMaterial::set_clearcoat_gloss(float p_clearcoat_gloss) { + clearcoat_gloss = p_clearcoat_gloss; + VS::get_singleton()->material_set_param(_get_material(), shader_names->clearcoat_gloss, p_clearcoat_gloss); } -float FixedSpatialMaterial::get_clearcoat_gloss() const{ +float FixedSpatialMaterial::get_clearcoat_gloss() const { return clearcoat_gloss; } -void FixedSpatialMaterial::set_anisotropy(float p_anisotropy){ - - anisotropy=p_anisotropy; - VS::get_singleton()->material_set_param(_get_material(),shader_names->anisotropy,p_anisotropy); +void FixedSpatialMaterial::set_anisotropy(float p_anisotropy) { + anisotropy = p_anisotropy; + VS::get_singleton()->material_set_param(_get_material(), shader_names->anisotropy, p_anisotropy); } -float FixedSpatialMaterial::get_anisotropy() const{ +float FixedSpatialMaterial::get_anisotropy() const { return anisotropy; } -void FixedSpatialMaterial::set_height_scale(float p_height_scale){ - - height_scale=p_height_scale; - VS::get_singleton()->material_set_param(_get_material(),shader_names->height_scale,p_height_scale); - +void FixedSpatialMaterial::set_height_scale(float p_height_scale) { + height_scale = p_height_scale; + VS::get_singleton()->material_set_param(_get_material(), shader_names->height_scale, p_height_scale); } -float FixedSpatialMaterial::get_height_scale() const{ +float FixedSpatialMaterial::get_height_scale() const { return height_scale; } +void FixedSpatialMaterial::set_subsurface_scattering_strength(float p_subsurface_scattering_strength) { -void FixedSpatialMaterial::set_subsurface_scattering_strength(float p_subsurface_scattering_strength){ - - subsurface_scattering_strength=p_subsurface_scattering_strength; - VS::get_singleton()->material_set_param(_get_material(),shader_names->subsurface_scattering_strength,subsurface_scattering_strength); - - + subsurface_scattering_strength = p_subsurface_scattering_strength; + VS::get_singleton()->material_set_param(_get_material(), shader_names->subsurface_scattering_strength, subsurface_scattering_strength); } -float FixedSpatialMaterial::get_subsurface_scattering_strength() const{ +float FixedSpatialMaterial::get_subsurface_scattering_strength() const { return subsurface_scattering_strength; } -void FixedSpatialMaterial::set_refraction(float p_refraction){ - - refraction=p_refraction; - VS::get_singleton()->material_set_param(_get_material(),shader_names->refraction,refraction); +void FixedSpatialMaterial::set_refraction(float p_refraction) { + refraction = p_refraction; + VS::get_singleton()->material_set_param(_get_material(), shader_names->refraction, refraction); } float FixedSpatialMaterial::get_refraction() const { @@ -593,10 +559,8 @@ float FixedSpatialMaterial::get_refraction() const { void FixedSpatialMaterial::set_refraction_roughness(float p_refraction_roughness) { - refraction_roughness=p_refraction_roughness; - VS::get_singleton()->material_set_param(_get_material(),shader_names->refraction_roughness,refraction_roughness); - - + refraction_roughness = p_refraction_roughness; + VS::get_singleton()->material_set_param(_get_material(), shader_names->refraction_roughness, refraction_roughness); } float FixedSpatialMaterial::get_refraction_roughness() const { @@ -605,10 +569,10 @@ float FixedSpatialMaterial::get_refraction_roughness() const { void FixedSpatialMaterial::set_detail_uv(DetailUV p_detail_uv) { - if (detail_uv==p_detail_uv) + if (detail_uv == p_detail_uv) return; - detail_uv=p_detail_uv; + detail_uv = p_detail_uv; _queue_shader_change(); } FixedSpatialMaterial::DetailUV FixedSpatialMaterial::get_detail_uv() const { @@ -618,10 +582,10 @@ FixedSpatialMaterial::DetailUV FixedSpatialMaterial::get_detail_uv() const { void FixedSpatialMaterial::set_blend_mode(BlendMode p_mode) { - if (blend_mode==p_mode) + if (blend_mode == p_mode) return; - blend_mode=p_mode; + blend_mode = p_mode; _queue_shader_change(); } FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_blend_mode() const { @@ -631,7 +595,7 @@ FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_blend_mode() const { void FixedSpatialMaterial::set_detail_blend_mode(BlendMode p_mode) { - detail_blend_mode=p_mode; + detail_blend_mode = p_mode; _queue_shader_change(); } FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_detail_blend_mode() const { @@ -641,10 +605,10 @@ FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_detail_blend_mode() co void FixedSpatialMaterial::set_depth_draw_mode(DepthDrawMode p_mode) { - if (depth_draw_mode==p_mode) + if (depth_draw_mode == p_mode) return; - depth_draw_mode=p_mode; + depth_draw_mode = p_mode; _queue_shader_change(); } FixedSpatialMaterial::DepthDrawMode FixedSpatialMaterial::get_depth_draw_mode() const { @@ -654,10 +618,10 @@ FixedSpatialMaterial::DepthDrawMode FixedSpatialMaterial::get_depth_draw_mode() void FixedSpatialMaterial::set_cull_mode(CullMode p_mode) { - if (cull_mode==p_mode) + if (cull_mode == p_mode) return; - cull_mode=p_mode; + cull_mode = p_mode; _queue_shader_change(); } FixedSpatialMaterial::CullMode FixedSpatialMaterial::get_cull_mode() const { @@ -667,10 +631,10 @@ FixedSpatialMaterial::CullMode FixedSpatialMaterial::get_cull_mode() const { void FixedSpatialMaterial::set_diffuse_mode(DiffuseMode p_mode) { - if (diffuse_mode==p_mode) + if (diffuse_mode == p_mode) return; - diffuse_mode=p_mode; + diffuse_mode = p_mode; _queue_shader_change(); } FixedSpatialMaterial::DiffuseMode FixedSpatialMaterial::get_diffuse_mode() const { @@ -678,91 +642,84 @@ FixedSpatialMaterial::DiffuseMode FixedSpatialMaterial::get_diffuse_mode() const return diffuse_mode; } -void FixedSpatialMaterial::set_flag(Flags p_flag,bool p_enabled) { +void FixedSpatialMaterial::set_flag(Flags p_flag, bool p_enabled) { - ERR_FAIL_INDEX(p_flag,FLAG_MAX); + ERR_FAIL_INDEX(p_flag, FLAG_MAX); - if (flags[p_flag]==p_enabled) + if (flags[p_flag] == p_enabled) return; - flags[p_flag]=p_enabled; + flags[p_flag] = p_enabled; _queue_shader_change(); } bool FixedSpatialMaterial::get_flag(Flags p_flag) const { - ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); + ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags[p_flag]; } -void FixedSpatialMaterial::set_feature(Feature p_feature,bool p_enabled) { +void FixedSpatialMaterial::set_feature(Feature p_feature, bool p_enabled) { - ERR_FAIL_INDEX(p_feature,FEATURE_MAX); - if (features[p_feature]==p_enabled) + ERR_FAIL_INDEX(p_feature, FEATURE_MAX); + if (features[p_feature] == p_enabled) return; - features[p_feature]=p_enabled; + features[p_feature] = p_enabled; _change_notify(); _queue_shader_change(); - - } bool FixedSpatialMaterial::get_feature(Feature p_feature) const { - ERR_FAIL_INDEX_V(p_feature,FEATURE_MAX,false); + ERR_FAIL_INDEX_V(p_feature, FEATURE_MAX, false); return features[p_feature]; } - - void FixedSpatialMaterial::set_texture(TextureParam p_param, const Ref<Texture> &p_texture) { - ERR_FAIL_INDEX(p_param,TEXTURE_MAX); - textures[p_param]=p_texture; + ERR_FAIL_INDEX(p_param, TEXTURE_MAX); + textures[p_param] = p_texture; RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID(); - VS::get_singleton()->material_set_param(_get_material(),shader_names->texture_names[p_param],rid); + VS::get_singleton()->material_set_param(_get_material(), shader_names->texture_names[p_param], rid); } Ref<Texture> FixedSpatialMaterial::get_texture(TextureParam p_param) const { - ERR_FAIL_INDEX_V(p_param,TEXTURE_MAX,Ref<Texture>()); + ERR_FAIL_INDEX_V(p_param, TEXTURE_MAX, Ref<Texture>()); return textures[p_param]; } - -void FixedSpatialMaterial::_validate_feature(const String& text, Feature feature,PropertyInfo& property) const { - if (property.name.begins_with(text) && property.name!=text+"_enabled" && !features[feature]) { - property.usage=0; +void FixedSpatialMaterial::_validate_feature(const String &text, Feature feature, PropertyInfo &property) const { + if (property.name.begins_with(text) && property.name != text + "_enabled" && !features[feature]) { + property.usage = 0; } - } -void FixedSpatialMaterial::_validate_property(PropertyInfo& property) const { - _validate_feature("normal",FEATURE_NORMAL_MAPPING,property); - _validate_feature("emission",FEATURE_EMISSION,property); - _validate_feature("rim",FEATURE_RIM,property); - _validate_feature("clearcoat",FEATURE_CLEARCOAT,property); - _validate_feature("anisotropy",FEATURE_ANISOTROPY,property); - _validate_feature("ao",FEATURE_AMBIENT_OCCLUSION,property); - _validate_feature("height",FEATURE_HEIGHT_MAPPING,property); - _validate_feature("subsurf_scatter",FEATURE_SUBSURACE_SCATTERING,property); - _validate_feature("refraction",FEATURE_REFRACTION,property); - _validate_feature("detail",FEATURE_DETAIL,property); - - if (property.name=="specular/color" && specular_mode==SPECULAR_MODE_METALLIC) { - property.usage=0; +void FixedSpatialMaterial::_validate_property(PropertyInfo &property) const { + _validate_feature("normal", FEATURE_NORMAL_MAPPING, property); + _validate_feature("emission", FEATURE_EMISSION, property); + _validate_feature("rim", FEATURE_RIM, property); + _validate_feature("clearcoat", FEATURE_CLEARCOAT, property); + _validate_feature("anisotropy", FEATURE_ANISOTROPY, property); + _validate_feature("ao", FEATURE_AMBIENT_OCCLUSION, property); + _validate_feature("height", FEATURE_HEIGHT_MAPPING, property); + _validate_feature("subsurf_scatter", FEATURE_SUBSURACE_SCATTERING, property); + _validate_feature("refraction", FEATURE_REFRACTION, property); + _validate_feature("detail", FEATURE_DETAIL, property); + + if (property.name == "specular/color" && specular_mode == SPECULAR_MODE_METALLIC) { + property.usage = 0; } - if (property.name=="specular/metalness" && specular_mode==SPECULAR_MODE_SPECULAR) { - property.usage=0; + if (property.name == "specular/metalness" && specular_mode == SPECULAR_MODE_SPECULAR) { + property.usage = 0; } - } void FixedSpatialMaterial::set_line_width(float p_line_width) { - line_width=p_line_width; - VS::get_singleton()->material_set_line_width(_get_material(),line_width); + line_width = p_line_width; + VS::get_singleton()->material_set_line_width(_get_material(), line_width); } float FixedSpatialMaterial::get_line_width() const { @@ -772,8 +729,8 @@ float FixedSpatialMaterial::get_line_width() const { void FixedSpatialMaterial::set_point_size(float p_point_size) { - point_size=p_point_size; - VS::get_singleton()->material_set_param(_get_material(),shader_names->point_size,p_point_size); + point_size = p_point_size; + VS::get_singleton()->material_set_param(_get_material(), shader_names->point_size, p_point_size); } float FixedSpatialMaterial::get_point_size() const { @@ -781,321 +738,312 @@ float FixedSpatialMaterial::get_point_size() const { return point_size; } +void FixedSpatialMaterial::set_uv1_scale(const Vector2 &p_scale) { -void FixedSpatialMaterial::set_uv1_scale(const Vector2& p_scale) { - - uv1_scale=p_scale; - VS::get_singleton()->material_set_param(_get_material(),shader_names->uv1_scale,p_scale); + uv1_scale = p_scale; + VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_scale, p_scale); } -Vector2 FixedSpatialMaterial::get_uv1_scale() const{ +Vector2 FixedSpatialMaterial::get_uv1_scale() const { return uv1_scale; } -void FixedSpatialMaterial::set_uv1_offset(const Vector2& p_offset){ - - uv1_offset=p_offset; - VS::get_singleton()->material_set_param(_get_material(),shader_names->uv1_offset,p_offset); +void FixedSpatialMaterial::set_uv1_offset(const Vector2 &p_offset) { + uv1_offset = p_offset; + VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_offset, p_offset); } -Vector2 FixedSpatialMaterial::get_uv1_offset() const{ +Vector2 FixedSpatialMaterial::get_uv1_offset() const { return uv1_offset; } +void FixedSpatialMaterial::set_uv2_scale(const Vector2 &p_scale) { -void FixedSpatialMaterial::set_uv2_scale(const Vector2& p_scale) { - - uv2_scale=p_scale; - VS::get_singleton()->material_set_param(_get_material(),shader_names->uv2_scale,p_scale); + uv2_scale = p_scale; + VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_scale, p_scale); } -Vector2 FixedSpatialMaterial::get_uv2_scale() const{ +Vector2 FixedSpatialMaterial::get_uv2_scale() const { return uv2_scale; } -void FixedSpatialMaterial::set_uv2_offset(const Vector2& p_offset){ - - uv2_offset=p_offset; - VS::get_singleton()->material_set_param(_get_material(),shader_names->uv2_offset,p_offset); +void FixedSpatialMaterial::set_uv2_offset(const Vector2 &p_offset) { + uv2_offset = p_offset; + VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_offset, p_offset); } -Vector2 FixedSpatialMaterial::get_uv2_offset() const{ +Vector2 FixedSpatialMaterial::get_uv2_offset() const { return uv2_offset; } void FixedSpatialMaterial::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_albedo", "albedo"), &FixedSpatialMaterial::set_albedo); + ClassDB::bind_method(D_METHOD("get_albedo"), &FixedSpatialMaterial::get_albedo); - ClassDB::bind_method(D_METHOD("set_albedo","albedo"),&FixedSpatialMaterial::set_albedo); - ClassDB::bind_method(D_METHOD("get_albedo"),&FixedSpatialMaterial::get_albedo); + ClassDB::bind_method(D_METHOD("set_specular_mode", "specular_mode"), &FixedSpatialMaterial::set_specular_mode); + ClassDB::bind_method(D_METHOD("get_specular_mode"), &FixedSpatialMaterial::get_specular_mode); - ClassDB::bind_method(D_METHOD("set_specular_mode","specular_mode"),&FixedSpatialMaterial::set_specular_mode); - ClassDB::bind_method(D_METHOD("get_specular_mode"),&FixedSpatialMaterial::get_specular_mode); + ClassDB::bind_method(D_METHOD("set_specular", "specular"), &FixedSpatialMaterial::set_specular); + ClassDB::bind_method(D_METHOD("get_specular"), &FixedSpatialMaterial::get_specular); - ClassDB::bind_method(D_METHOD("set_specular","specular"),&FixedSpatialMaterial::set_specular); - ClassDB::bind_method(D_METHOD("get_specular"),&FixedSpatialMaterial::get_specular); + ClassDB::bind_method(D_METHOD("set_metalness", "metalness"), &FixedSpatialMaterial::set_metalness); + ClassDB::bind_method(D_METHOD("get_metalness"), &FixedSpatialMaterial::get_metalness); - ClassDB::bind_method(D_METHOD("set_metalness","metalness"),&FixedSpatialMaterial::set_metalness); - ClassDB::bind_method(D_METHOD("get_metalness"),&FixedSpatialMaterial::get_metalness); + ClassDB::bind_method(D_METHOD("set_roughness", "roughness"), &FixedSpatialMaterial::set_roughness); + ClassDB::bind_method(D_METHOD("get_roughness"), &FixedSpatialMaterial::get_roughness); - ClassDB::bind_method(D_METHOD("set_roughness","roughness"),&FixedSpatialMaterial::set_roughness); - ClassDB::bind_method(D_METHOD("get_roughness"),&FixedSpatialMaterial::get_roughness); + ClassDB::bind_method(D_METHOD("set_emission", "emission"), &FixedSpatialMaterial::set_emission); + ClassDB::bind_method(D_METHOD("get_emission"), &FixedSpatialMaterial::get_emission); - ClassDB::bind_method(D_METHOD("set_emission","emission"),&FixedSpatialMaterial::set_emission); - ClassDB::bind_method(D_METHOD("get_emission"),&FixedSpatialMaterial::get_emission); + ClassDB::bind_method(D_METHOD("set_emission_energy", "emission_energy"), &FixedSpatialMaterial::set_emission_energy); + ClassDB::bind_method(D_METHOD("get_emission_energy"), &FixedSpatialMaterial::get_emission_energy); - ClassDB::bind_method(D_METHOD("set_emission_energy","emission_energy"),&FixedSpatialMaterial::set_emission_energy); - ClassDB::bind_method(D_METHOD("get_emission_energy"),&FixedSpatialMaterial::get_emission_energy); + ClassDB::bind_method(D_METHOD("set_normal_scale", "normal_scale"), &FixedSpatialMaterial::set_normal_scale); + ClassDB::bind_method(D_METHOD("get_normal_scale"), &FixedSpatialMaterial::get_normal_scale); - ClassDB::bind_method(D_METHOD("set_normal_scale","normal_scale"),&FixedSpatialMaterial::set_normal_scale); - ClassDB::bind_method(D_METHOD("get_normal_scale"),&FixedSpatialMaterial::get_normal_scale); + ClassDB::bind_method(D_METHOD("set_rim", "rim"), &FixedSpatialMaterial::set_rim); + ClassDB::bind_method(D_METHOD("get_rim"), &FixedSpatialMaterial::get_rim); - ClassDB::bind_method(D_METHOD("set_rim","rim"),&FixedSpatialMaterial::set_rim); - ClassDB::bind_method(D_METHOD("get_rim"),&FixedSpatialMaterial::get_rim); + ClassDB::bind_method(D_METHOD("set_rim_tint", "rim_tint"), &FixedSpatialMaterial::set_rim_tint); + ClassDB::bind_method(D_METHOD("get_rim_tint"), &FixedSpatialMaterial::get_rim_tint); - ClassDB::bind_method(D_METHOD("set_rim_tint","rim_tint"),&FixedSpatialMaterial::set_rim_tint); - ClassDB::bind_method(D_METHOD("get_rim_tint"),&FixedSpatialMaterial::get_rim_tint); + ClassDB::bind_method(D_METHOD("set_clearcoat", "clearcoat"), &FixedSpatialMaterial::set_clearcoat); + ClassDB::bind_method(D_METHOD("get_clearcoat"), &FixedSpatialMaterial::get_clearcoat); - ClassDB::bind_method(D_METHOD("set_clearcoat","clearcoat"),&FixedSpatialMaterial::set_clearcoat); - ClassDB::bind_method(D_METHOD("get_clearcoat"),&FixedSpatialMaterial::get_clearcoat); + ClassDB::bind_method(D_METHOD("set_clearcoat_gloss", "clearcoat_gloss"), &FixedSpatialMaterial::set_clearcoat_gloss); + ClassDB::bind_method(D_METHOD("get_clearcoat_gloss"), &FixedSpatialMaterial::get_clearcoat_gloss); - ClassDB::bind_method(D_METHOD("set_clearcoat_gloss","clearcoat_gloss"),&FixedSpatialMaterial::set_clearcoat_gloss); - ClassDB::bind_method(D_METHOD("get_clearcoat_gloss"),&FixedSpatialMaterial::get_clearcoat_gloss); + ClassDB::bind_method(D_METHOD("set_anisotropy", "anisotropy"), &FixedSpatialMaterial::set_anisotropy); + ClassDB::bind_method(D_METHOD("get_anisotropy"), &FixedSpatialMaterial::get_anisotropy); - ClassDB::bind_method(D_METHOD("set_anisotropy","anisotropy"),&FixedSpatialMaterial::set_anisotropy); - ClassDB::bind_method(D_METHOD("get_anisotropy"),&FixedSpatialMaterial::get_anisotropy); + ClassDB::bind_method(D_METHOD("set_height_scale", "height_scale"), &FixedSpatialMaterial::set_height_scale); + ClassDB::bind_method(D_METHOD("get_height_scale"), &FixedSpatialMaterial::get_height_scale); - ClassDB::bind_method(D_METHOD("set_height_scale","height_scale"),&FixedSpatialMaterial::set_height_scale); - ClassDB::bind_method(D_METHOD("get_height_scale"),&FixedSpatialMaterial::get_height_scale); + ClassDB::bind_method(D_METHOD("set_subsurface_scattering_strength", "strength"), &FixedSpatialMaterial::set_subsurface_scattering_strength); + ClassDB::bind_method(D_METHOD("get_subsurface_scattering_strength"), &FixedSpatialMaterial::get_subsurface_scattering_strength); - ClassDB::bind_method(D_METHOD("set_subsurface_scattering_strength","strength"),&FixedSpatialMaterial::set_subsurface_scattering_strength); - ClassDB::bind_method(D_METHOD("get_subsurface_scattering_strength"),&FixedSpatialMaterial::get_subsurface_scattering_strength); + ClassDB::bind_method(D_METHOD("set_refraction", "refraction"), &FixedSpatialMaterial::set_refraction); + ClassDB::bind_method(D_METHOD("get_refraction"), &FixedSpatialMaterial::get_refraction); - ClassDB::bind_method(D_METHOD("set_refraction","refraction"),&FixedSpatialMaterial::set_refraction); - ClassDB::bind_method(D_METHOD("get_refraction"),&FixedSpatialMaterial::get_refraction); + ClassDB::bind_method(D_METHOD("set_refraction_roughness", "refraction_roughness"), &FixedSpatialMaterial::set_refraction_roughness); + ClassDB::bind_method(D_METHOD("get_refraction_roughness"), &FixedSpatialMaterial::get_refraction_roughness); - ClassDB::bind_method(D_METHOD("set_refraction_roughness","refraction_roughness"),&FixedSpatialMaterial::set_refraction_roughness); - ClassDB::bind_method(D_METHOD("get_refraction_roughness"),&FixedSpatialMaterial::get_refraction_roughness); + ClassDB::bind_method(D_METHOD("set_line_width", "line_width"), &FixedSpatialMaterial::set_line_width); + ClassDB::bind_method(D_METHOD("get_line_width"), &FixedSpatialMaterial::get_line_width); - ClassDB::bind_method(D_METHOD("set_line_width","line_width"),&FixedSpatialMaterial::set_line_width); - ClassDB::bind_method(D_METHOD("get_line_width"),&FixedSpatialMaterial::get_line_width); + ClassDB::bind_method(D_METHOD("set_point_size", "point_size"), &FixedSpatialMaterial::set_point_size); + ClassDB::bind_method(D_METHOD("get_point_size"), &FixedSpatialMaterial::get_point_size); - ClassDB::bind_method(D_METHOD("set_point_size","point_size"),&FixedSpatialMaterial::set_point_size); - ClassDB::bind_method(D_METHOD("get_point_size"),&FixedSpatialMaterial::get_point_size); + ClassDB::bind_method(D_METHOD("set_detail_uv", "detail_uv"), &FixedSpatialMaterial::set_detail_uv); + ClassDB::bind_method(D_METHOD("get_detail_uv"), &FixedSpatialMaterial::get_detail_uv); - ClassDB::bind_method(D_METHOD("set_detail_uv","detail_uv"),&FixedSpatialMaterial::set_detail_uv); - ClassDB::bind_method(D_METHOD("get_detail_uv"),&FixedSpatialMaterial::get_detail_uv); + ClassDB::bind_method(D_METHOD("set_blend_mode", "blend_mode"), &FixedSpatialMaterial::set_blend_mode); + ClassDB::bind_method(D_METHOD("get_blend_mode"), &FixedSpatialMaterial::get_blend_mode); - ClassDB::bind_method(D_METHOD("set_blend_mode","blend_mode"),&FixedSpatialMaterial::set_blend_mode); - ClassDB::bind_method(D_METHOD("get_blend_mode"),&FixedSpatialMaterial::get_blend_mode); + ClassDB::bind_method(D_METHOD("set_depth_draw_mode", "depth_draw_mode"), &FixedSpatialMaterial::set_depth_draw_mode); + ClassDB::bind_method(D_METHOD("get_depth_draw_mode"), &FixedSpatialMaterial::get_depth_draw_mode); - ClassDB::bind_method(D_METHOD("set_depth_draw_mode","depth_draw_mode"),&FixedSpatialMaterial::set_depth_draw_mode); - ClassDB::bind_method(D_METHOD("get_depth_draw_mode"),&FixedSpatialMaterial::get_depth_draw_mode); + ClassDB::bind_method(D_METHOD("set_cull_mode", "cull_mode"), &FixedSpatialMaterial::set_cull_mode); + ClassDB::bind_method(D_METHOD("get_cull_mode"), &FixedSpatialMaterial::get_cull_mode); - ClassDB::bind_method(D_METHOD("set_cull_mode","cull_mode"),&FixedSpatialMaterial::set_cull_mode); - ClassDB::bind_method(D_METHOD("get_cull_mode"),&FixedSpatialMaterial::get_cull_mode); + ClassDB::bind_method(D_METHOD("set_diffuse_mode", "diffuse_mode"), &FixedSpatialMaterial::set_diffuse_mode); + ClassDB::bind_method(D_METHOD("get_diffuse_mode"), &FixedSpatialMaterial::get_diffuse_mode); - ClassDB::bind_method(D_METHOD("set_diffuse_mode","diffuse_mode"),&FixedSpatialMaterial::set_diffuse_mode); - ClassDB::bind_method(D_METHOD("get_diffuse_mode"),&FixedSpatialMaterial::get_diffuse_mode); + ClassDB::bind_method(D_METHOD("set_flag", "flag", "enable"), &FixedSpatialMaterial::set_flag); + ClassDB::bind_method(D_METHOD("get_flag"), &FixedSpatialMaterial::get_flag); - ClassDB::bind_method(D_METHOD("set_flag","flag","enable"),&FixedSpatialMaterial::set_flag); - ClassDB::bind_method(D_METHOD("get_flag"),&FixedSpatialMaterial::get_flag); + ClassDB::bind_method(D_METHOD("set_feature", "feature", "enable"), &FixedSpatialMaterial::set_feature); + ClassDB::bind_method(D_METHOD("get_feature", "feature"), &FixedSpatialMaterial::get_feature); - ClassDB::bind_method(D_METHOD("set_feature","feature","enable"),&FixedSpatialMaterial::set_feature); - ClassDB::bind_method(D_METHOD("get_feature","feature"),&FixedSpatialMaterial::get_feature); + ClassDB::bind_method(D_METHOD("set_texture", "param:Texture", "texture"), &FixedSpatialMaterial::set_texture); + ClassDB::bind_method(D_METHOD("get_texture:Texture", "param:Texture"), &FixedSpatialMaterial::get_texture); - ClassDB::bind_method(D_METHOD("set_texture","param:Texture","texture"),&FixedSpatialMaterial::set_texture); - ClassDB::bind_method(D_METHOD("get_texture:Texture","param:Texture"),&FixedSpatialMaterial::get_texture); + ClassDB::bind_method(D_METHOD("set_detail_blend_mode", "detail_blend_mode"), &FixedSpatialMaterial::set_detail_blend_mode); + ClassDB::bind_method(D_METHOD("get_detail_blend_mode"), &FixedSpatialMaterial::get_detail_blend_mode); - ClassDB::bind_method(D_METHOD("set_detail_blend_mode","detail_blend_mode"),&FixedSpatialMaterial::set_detail_blend_mode); - ClassDB::bind_method(D_METHOD("get_detail_blend_mode"),&FixedSpatialMaterial::get_detail_blend_mode); + ClassDB::bind_method(D_METHOD("set_uv1_scale", "scale"), &FixedSpatialMaterial::set_uv1_scale); + ClassDB::bind_method(D_METHOD("get_uv1_scale"), &FixedSpatialMaterial::get_uv1_scale); - ClassDB::bind_method(D_METHOD("set_uv1_scale","scale"),&FixedSpatialMaterial::set_uv1_scale); - ClassDB::bind_method(D_METHOD("get_uv1_scale"),&FixedSpatialMaterial::get_uv1_scale); + ClassDB::bind_method(D_METHOD("set_uv1_offset", "offset"), &FixedSpatialMaterial::set_uv1_offset); + ClassDB::bind_method(D_METHOD("get_uv1_offset"), &FixedSpatialMaterial::get_uv1_offset); - ClassDB::bind_method(D_METHOD("set_uv1_offset","offset"),&FixedSpatialMaterial::set_uv1_offset); - ClassDB::bind_method(D_METHOD("get_uv1_offset"),&FixedSpatialMaterial::get_uv1_offset); + ClassDB::bind_method(D_METHOD("set_uv2_scale", "scale"), &FixedSpatialMaterial::set_uv2_scale); + ClassDB::bind_method(D_METHOD("get_uv2_scale"), &FixedSpatialMaterial::get_uv2_scale); - ClassDB::bind_method(D_METHOD("set_uv2_scale","scale"),&FixedSpatialMaterial::set_uv2_scale); - ClassDB::bind_method(D_METHOD("get_uv2_scale"),&FixedSpatialMaterial::get_uv2_scale); + ClassDB::bind_method(D_METHOD("set_uv2_offset", "offset"), &FixedSpatialMaterial::set_uv2_offset); + ClassDB::bind_method(D_METHOD("get_uv2_offset"), &FixedSpatialMaterial::get_uv2_offset); - ClassDB::bind_method(D_METHOD("set_uv2_offset","offset"),&FixedSpatialMaterial::set_uv2_offset); - ClassDB::bind_method(D_METHOD("get_uv2_offset"),&FixedSpatialMaterial::get_uv2_offset); - - ADD_GROUP("Flags","flags_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_transparent"),"set_feature","get_feature",FEATURE_TRANSPARENT); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_unshaded"),"set_flag","get_flag",FLAG_UNSHADED); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_on_top"),"set_flag","get_flag",FLAG_ONTOP); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_use_point_size"),"set_flag","get_flag",FLAG_USE_POINT_SIZE); - ADD_GROUP("Vertex Color","vertex_color"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"vertex_color_use_as_albedo"),"set_flag","get_flag",FLAG_ALBEDO_FROM_VERTEX_COLOR); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"vertex_color_is_srgb"),"set_flag","get_flag",FLAG_SRGB_VERTEX_COLOR); - - ADD_GROUP("Parameters","params_"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"params_diffuse_mode",PROPERTY_HINT_ENUM,"Labert,Lambert Wrap,Oren Nayar,Burley"),"set_diffuse_mode","get_diffuse_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"params_blend_mode",PROPERTY_HINT_ENUM,"Mix,Add,Sub,Mul"),"set_blend_mode","get_blend_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"params_cull_mode",PROPERTY_HINT_ENUM,"Back,Front,Disabled"),"set_cull_mode","get_cull_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"params_depth_draw_mode",PROPERTY_HINT_ENUM,"Opaque Only,Always,Never,Opaque Pre-Pass"),"set_depth_draw_mode","get_depth_draw_mode"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"params_line_width",PROPERTY_HINT_RANGE,"0.1,128,0.1"),"set_line_width","get_line_width"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"params_point_size",PROPERTY_HINT_RANGE,"0.1,128,0.1"),"set_point_size","get_point_size"); - - ADD_GROUP("Albedo","albedo_"); - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"albedo_color"),"set_albedo","get_albedo"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"albedo_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_ALBEDO); - - ADD_GROUP("Specular","specular_"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"specular_mode",PROPERTY_HINT_ENUM,"Metallic,Specular"),"set_specular_mode","get_specular_mode"); - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"specular_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_specular","get_specular"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"specular_metalness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_metalness","get_metalness"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"specular_roughness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_roughness","get_roughness"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"specular_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_SPECULAR); - - ADD_GROUP("Emission","emission_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"emission_enabled"),"set_feature","get_feature",FEATURE_EMISSION); - ADD_PROPERTY(PropertyInfo(Variant::COLOR,"emission_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_emission","get_emission"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"emission_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_emission_energy","get_emission_energy"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"emission_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_EMISSION); - - ADD_GROUP("NormapMap","normal_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"normal_enabled"),"set_feature","get_feature",FEATURE_NORMAL_MAPPING); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"normal_scale",PROPERTY_HINT_RANGE,"-16,16,0.01"),"set_normal_scale","get_normal_scale"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"normal_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_NORMAL); - - ADD_GROUP("Rim","rim_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"rim_enabled"),"set_feature","get_feature",FEATURE_RIM); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"rim_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_rim","get_rim"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"rim_tint",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_rim_tint","get_rim_tint"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"rim_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_RIM); - - ADD_GROUP("Clearcoat","clearcoat_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"clearcoat_enabled"),"set_feature","get_feature",FEATURE_CLEARCOAT); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"clearcoat_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_clearcoat","get_clearcoat"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"clearcoat_gloss",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_clearcoat_gloss","get_clearcoat_gloss"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"clearcoat_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_CLEARCOAT); - - ADD_GROUP("Anisotropy","anisotropy_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"anisotropy_enabled"),"set_feature","get_feature",FEATURE_ANISOTROPY); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"anisotropy_anisotropy",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_anisotropy","get_anisotropy"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"anisotropy_flowmap",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_FLOWMAP); - - ADD_GROUP("Ambient Occlusion","ao_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"ao_enabled"),"set_feature","get_feature",FEATURE_AMBIENT_OCCLUSION); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"ao_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_AMBIENT_OCCLUSION); - - ADD_GROUP("Height","height_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"height_enabled"),"set_feature","get_feature",FEATURE_HEIGHT_MAPPING); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"height_scale",PROPERTY_HINT_RANGE,"-16,16,0.01"),"set_height_scale","get_height_scale"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"height_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_HEIGHT); - - ADD_GROUP("Subsurf Scatter","subsurf_scatter_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"subsurf_scatter_enabled"),"set_feature","get_feature",FEATURE_SUBSURACE_SCATTERING); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"subsurf_scatter_strength",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_subsurface_scattering_strength","get_subsurface_scattering_strength"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"subsurf_scatter_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_SUBSURFACE_SCATTERING); - - ADD_GROUP("Refraction","refraction_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"refraction_enabled"),"set_feature","get_feature",FEATURE_REFRACTION); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"refraction_displacement",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_refraction","get_refraction"); - ADD_PROPERTY(PropertyInfo(Variant::REAL,"refraction_roughness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_refraction_roughness","get_refraction_roughness"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"refraction_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_REFRACTION); - - ADD_GROUP("Detail","detail_"); - ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"detail_enabled"),"set_feature","get_feature",FEATURE_DETAIL); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_mask",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_DETAIL_MASK); - ADD_PROPERTY(PropertyInfo(Variant::INT,"detail_blend_mode",PROPERTY_HINT_ENUM,"Mix,Add,Sub,Mul"),"set_detail_blend_mode","get_detail_blend_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"detail_uv_layer",PROPERTY_HINT_ENUM,"UV1,UV2"),"set_detail_uv","get_detail_uv"); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_albedo",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_DETAIL_ALBEDO); - ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_normal",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_DETAIL_NORMAL); - - ADD_GROUP("UV1","uv1_"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv1_scale"),"set_uv1_scale","get_uv1_scale"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv1_offset"),"set_uv1_offset","get_uv1_offset"); - - ADD_GROUP("UV2","uv2_"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv2_scale"),"set_uv2_scale","get_uv2_scale"); - ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv2_offset"),"set_uv2_offset","get_uv2_offset"); - - - BIND_CONSTANT( TEXTURE_ALBEDO ); - BIND_CONSTANT( TEXTURE_SPECULAR ); - BIND_CONSTANT( TEXTURE_EMISSION ); - BIND_CONSTANT( TEXTURE_NORMAL ); - BIND_CONSTANT( TEXTURE_RIM ); - BIND_CONSTANT( TEXTURE_CLEARCOAT ); - BIND_CONSTANT( TEXTURE_FLOWMAP ); - BIND_CONSTANT( TEXTURE_AMBIENT_OCCLUSION ); - BIND_CONSTANT( TEXTURE_HEIGHT ); - BIND_CONSTANT( TEXTURE_SUBSURFACE_SCATTERING ); - BIND_CONSTANT( TEXTURE_REFRACTION ); - BIND_CONSTANT( TEXTURE_REFRACTION_ROUGHNESS ); - BIND_CONSTANT( TEXTURE_DETAIL_MASK ); - BIND_CONSTANT( TEXTURE_DETAIL_ALBEDO ); - BIND_CONSTANT( TEXTURE_DETAIL_NORMAL ); - BIND_CONSTANT( TEXTURE_MAX ); - - - BIND_CONSTANT( DETAIL_UV_1 ); - BIND_CONSTANT( DETAIL_UV_2 ); - - BIND_CONSTANT( FEATURE_TRANSPARENT ); - BIND_CONSTANT( FEATURE_EMISSION ); - BIND_CONSTANT( FEATURE_NORMAL_MAPPING ); - BIND_CONSTANT( FEATURE_RIM ); - BIND_CONSTANT( FEATURE_CLEARCOAT ); - BIND_CONSTANT( FEATURE_ANISOTROPY ); - BIND_CONSTANT( FEATURE_AMBIENT_OCCLUSION ); - BIND_CONSTANT( FEATURE_HEIGHT_MAPPING ); - BIND_CONSTANT( FEATURE_SUBSURACE_SCATTERING ); - BIND_CONSTANT( FEATURE_REFRACTION ); - BIND_CONSTANT( FEATURE_DETAIL ); - BIND_CONSTANT( FEATURE_MAX ); - - BIND_CONSTANT( BLEND_MODE_MIX ); - BIND_CONSTANT( BLEND_MODE_ADD ); - BIND_CONSTANT( BLEND_MODE_SUB ); - BIND_CONSTANT( BLEND_MODE_MUL ); - - BIND_CONSTANT( DEPTH_DRAW_OPAQUE_ONLY ); - BIND_CONSTANT( DEPTH_DRAW_ALWAYS ); - BIND_CONSTANT( DEPTH_DRAW_DISABLED ); - BIND_CONSTANT( DEPTH_DRAW_ALPHA_OPAQUE_PREPASS ); - - - BIND_CONSTANT( CULL_BACK ); - BIND_CONSTANT( CULL_FRONT ); - BIND_CONSTANT( CULL_DISABLED ); - - BIND_CONSTANT( FLAG_UNSHADED ); - BIND_CONSTANT( FLAG_ONTOP ); - BIND_CONSTANT( FLAG_ALBEDO_FROM_VERTEX_COLOR ); - BIND_CONSTANT( FLAG_SRGB_VERTEX_COLOR ) - BIND_CONSTANT( FLAG_USE_POINT_SIZE ) - BIND_CONSTANT( FLAG_MAX ); - - BIND_CONSTANT( DIFFUSE_LAMBERT ); - BIND_CONSTANT( DIFFUSE_LAMBERT_WRAP ); - BIND_CONSTANT( DIFFUSE_OREN_NAYAR ); - BIND_CONSTANT( DIFFUSE_BURLEY ); - - BIND_CONSTANT( SPECULAR_MODE_METALLIC ); - BIND_CONSTANT( SPECULAR_MODE_SPECULAR ); - -} - - -FixedSpatialMaterial::FixedSpatialMaterial() : element(this) { + ADD_GROUP("Flags", "flags_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_transparent"), "set_feature", "get_feature", FEATURE_TRANSPARENT); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_unshaded"), "set_flag", "get_flag", FLAG_UNSHADED); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_on_top"), "set_flag", "get_flag", FLAG_ONTOP); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_use_point_size"), "set_flag", "get_flag", FLAG_USE_POINT_SIZE); + ADD_GROUP("Vertex Color", "vertex_color"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "vertex_color_use_as_albedo"), "set_flag", "get_flag", FLAG_ALBEDO_FROM_VERTEX_COLOR); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "vertex_color_is_srgb"), "set_flag", "get_flag", FLAG_SRGB_VERTEX_COLOR); + + ADD_GROUP("Parameters", "params_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "params_diffuse_mode", PROPERTY_HINT_ENUM, "Labert,Lambert Wrap,Oren Nayar,Burley"), "set_diffuse_mode", "get_diffuse_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "params_blend_mode", PROPERTY_HINT_ENUM, "Mix,Add,Sub,Mul"), "set_blend_mode", "get_blend_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "params_cull_mode", PROPERTY_HINT_ENUM, "Back,Front,Disabled"), "set_cull_mode", "get_cull_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "params_depth_draw_mode", PROPERTY_HINT_ENUM, "Opaque Only,Always,Never,Opaque Pre-Pass"), "set_depth_draw_mode", "get_depth_draw_mode"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_line_width", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_line_width", "get_line_width"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_point_size", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_point_size", "get_point_size"); + + ADD_GROUP("Albedo", "albedo_"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "albedo_color"), "set_albedo", "get_albedo"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "albedo_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_ALBEDO); + + ADD_GROUP("Specular", "specular_"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "specular_mode", PROPERTY_HINT_ENUM, "Metallic,Specular"), "set_specular_mode", "get_specular_mode"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "specular_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_specular", "get_specular"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "specular_metalness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_metalness", "get_metalness"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "specular_roughness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_roughness", "get_roughness"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "specular_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_SPECULAR); + + ADD_GROUP("Emission", "emission_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "emission_enabled"), "set_feature", "get_feature", FEATURE_EMISSION); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "emission_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_emission", "get_emission"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "emission_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_emission_energy", "get_emission_energy"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "emission_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_EMISSION); + + ADD_GROUP("NormapMap", "normal_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "normal_enabled"), "set_feature", "get_feature", FEATURE_NORMAL_MAPPING); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "normal_scale", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_normal_scale", "get_normal_scale"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "normal_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_NORMAL); + + ADD_GROUP("Rim", "rim_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "rim_enabled"), "set_feature", "get_feature", FEATURE_RIM); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "rim_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_rim", "get_rim"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "rim_tint", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_rim_tint", "get_rim_tint"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "rim_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_RIM); + + ADD_GROUP("Clearcoat", "clearcoat_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "clearcoat_enabled"), "set_feature", "get_feature", FEATURE_CLEARCOAT); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "clearcoat_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_clearcoat", "get_clearcoat"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "clearcoat_gloss", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_clearcoat_gloss", "get_clearcoat_gloss"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "clearcoat_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_CLEARCOAT); + + ADD_GROUP("Anisotropy", "anisotropy_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "anisotropy_enabled"), "set_feature", "get_feature", FEATURE_ANISOTROPY); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "anisotropy_anisotropy", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_anisotropy", "get_anisotropy"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anisotropy_flowmap", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_FLOWMAP); + + ADD_GROUP("Ambient Occlusion", "ao_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "ao_enabled"), "set_feature", "get_feature", FEATURE_AMBIENT_OCCLUSION); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "ao_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_AMBIENT_OCCLUSION); + + ADD_GROUP("Height", "height_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "height_enabled"), "set_feature", "get_feature", FEATURE_HEIGHT_MAPPING); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "height_scale", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_height_scale", "get_height_scale"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "height_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_HEIGHT); + + ADD_GROUP("Subsurf Scatter", "subsurf_scatter_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "subsurf_scatter_enabled"), "set_feature", "get_feature", FEATURE_SUBSURACE_SCATTERING); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "subsurf_scatter_strength", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_subsurface_scattering_strength", "get_subsurface_scattering_strength"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "subsurf_scatter_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_SUBSURFACE_SCATTERING); + + ADD_GROUP("Refraction", "refraction_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "refraction_enabled"), "set_feature", "get_feature", FEATURE_REFRACTION); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "refraction_displacement", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_refraction", "get_refraction"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "refraction_roughness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_refraction_roughness", "get_refraction_roughness"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "refraction_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_REFRACTION); + + ADD_GROUP("Detail", "detail_"); + ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "detail_enabled"), "set_feature", "get_feature", FEATURE_DETAIL); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_mask", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_MASK); + ADD_PROPERTY(PropertyInfo(Variant::INT, "detail_blend_mode", PROPERTY_HINT_ENUM, "Mix,Add,Sub,Mul"), "set_detail_blend_mode", "get_detail_blend_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "detail_uv_layer", PROPERTY_HINT_ENUM, "UV1,UV2"), "set_detail_uv", "get_detail_uv"); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_albedo", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_ALBEDO); + ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_NORMAL); + + ADD_GROUP("UV1", "uv1_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv1_scale"), "set_uv1_scale", "get_uv1_scale"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv1_offset"), "set_uv1_offset", "get_uv1_offset"); + + ADD_GROUP("UV2", "uv2_"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv2_scale"), "set_uv2_scale", "get_uv2_scale"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv2_offset"), "set_uv2_offset", "get_uv2_offset"); + + BIND_CONSTANT(TEXTURE_ALBEDO); + BIND_CONSTANT(TEXTURE_SPECULAR); + BIND_CONSTANT(TEXTURE_EMISSION); + BIND_CONSTANT(TEXTURE_NORMAL); + BIND_CONSTANT(TEXTURE_RIM); + BIND_CONSTANT(TEXTURE_CLEARCOAT); + BIND_CONSTANT(TEXTURE_FLOWMAP); + BIND_CONSTANT(TEXTURE_AMBIENT_OCCLUSION); + BIND_CONSTANT(TEXTURE_HEIGHT); + BIND_CONSTANT(TEXTURE_SUBSURFACE_SCATTERING); + BIND_CONSTANT(TEXTURE_REFRACTION); + BIND_CONSTANT(TEXTURE_REFRACTION_ROUGHNESS); + BIND_CONSTANT(TEXTURE_DETAIL_MASK); + BIND_CONSTANT(TEXTURE_DETAIL_ALBEDO); + BIND_CONSTANT(TEXTURE_DETAIL_NORMAL); + BIND_CONSTANT(TEXTURE_MAX); + + BIND_CONSTANT(DETAIL_UV_1); + BIND_CONSTANT(DETAIL_UV_2); + + BIND_CONSTANT(FEATURE_TRANSPARENT); + BIND_CONSTANT(FEATURE_EMISSION); + BIND_CONSTANT(FEATURE_NORMAL_MAPPING); + BIND_CONSTANT(FEATURE_RIM); + BIND_CONSTANT(FEATURE_CLEARCOAT); + BIND_CONSTANT(FEATURE_ANISOTROPY); + BIND_CONSTANT(FEATURE_AMBIENT_OCCLUSION); + BIND_CONSTANT(FEATURE_HEIGHT_MAPPING); + BIND_CONSTANT(FEATURE_SUBSURACE_SCATTERING); + BIND_CONSTANT(FEATURE_REFRACTION); + BIND_CONSTANT(FEATURE_DETAIL); + BIND_CONSTANT(FEATURE_MAX); + + BIND_CONSTANT(BLEND_MODE_MIX); + BIND_CONSTANT(BLEND_MODE_ADD); + BIND_CONSTANT(BLEND_MODE_SUB); + BIND_CONSTANT(BLEND_MODE_MUL); + + BIND_CONSTANT(DEPTH_DRAW_OPAQUE_ONLY); + BIND_CONSTANT(DEPTH_DRAW_ALWAYS); + BIND_CONSTANT(DEPTH_DRAW_DISABLED); + BIND_CONSTANT(DEPTH_DRAW_ALPHA_OPAQUE_PREPASS); + + BIND_CONSTANT(CULL_BACK); + BIND_CONSTANT(CULL_FRONT); + BIND_CONSTANT(CULL_DISABLED); + + BIND_CONSTANT(FLAG_UNSHADED); + BIND_CONSTANT(FLAG_ONTOP); + BIND_CONSTANT(FLAG_ALBEDO_FROM_VERTEX_COLOR); + BIND_CONSTANT(FLAG_SRGB_VERTEX_COLOR) + BIND_CONSTANT(FLAG_USE_POINT_SIZE) + BIND_CONSTANT(FLAG_MAX); + + BIND_CONSTANT(DIFFUSE_LAMBERT); + BIND_CONSTANT(DIFFUSE_LAMBERT_WRAP); + BIND_CONSTANT(DIFFUSE_OREN_NAYAR); + BIND_CONSTANT(DIFFUSE_BURLEY); + + BIND_CONSTANT(SPECULAR_MODE_METALLIC); + BIND_CONSTANT(SPECULAR_MODE_SPECULAR); +} + +FixedSpatialMaterial::FixedSpatialMaterial() + : element(this) { //initialize to right values - specular_mode=SPECULAR_MODE_METALLIC; - set_albedo(Color(0.7,0.7,0.7,1.0)); - set_specular(Color(0.1,0.1,0.1)); + specular_mode = SPECULAR_MODE_METALLIC; + set_albedo(Color(0.7, 0.7, 0.7, 1.0)); + set_specular(Color(0.1, 0.1, 0.1)); set_roughness(0.0); set_metalness(0.1); - set_emission(Color(0,0,0)); + set_emission(Color(0, 0, 0)); set_emission_energy(1.0); set_normal_scale(1); set_rim(1.0); @@ -1109,27 +1057,27 @@ FixedSpatialMaterial::FixedSpatialMaterial() : element(this) { set_refraction_roughness(0); set_line_width(1); set_point_size(1); - set_uv1_offset(Vector2(0,0)); - set_uv1_scale(Vector2(1,1)); - set_uv2_offset(Vector2(0,0)); - set_uv2_scale(Vector2(1,1)); - - detail_uv=DETAIL_UV_1; - blend_mode=BLEND_MODE_MIX; - detail_blend_mode=BLEND_MODE_MIX; - depth_draw_mode=DEPTH_DRAW_OPAQUE_ONLY; - cull_mode=CULL_BACK; - for(int i=0;i<FLAG_MAX;i++) { - flags[i]=0; + set_uv1_offset(Vector2(0, 0)); + set_uv1_scale(Vector2(1, 1)); + set_uv2_offset(Vector2(0, 0)); + set_uv2_scale(Vector2(1, 1)); + + detail_uv = DETAIL_UV_1; + blend_mode = BLEND_MODE_MIX; + detail_blend_mode = BLEND_MODE_MIX; + depth_draw_mode = DEPTH_DRAW_OPAQUE_ONLY; + cull_mode = CULL_BACK; + for (int i = 0; i < FLAG_MAX; i++) { + flags[i] = 0; } - diffuse_mode=DIFFUSE_LAMBERT; + diffuse_mode = DIFFUSE_LAMBERT; - for(int i=0;i<FEATURE_MAX;i++) { - features[i]=false; + for (int i = 0; i < FEATURE_MAX; i++) { + features[i] = false; } - current_key.key=0; - current_key.invalid_key=1; + current_key.key = 0; + current_key.invalid_key = 1; _queue_shader_change(); } @@ -1140,17 +1088,15 @@ FixedSpatialMaterial::~FixedSpatialMaterial() { if (shader_map.has(current_key)) { shader_map[current_key].users--; - if (shader_map[current_key].users==0) { + if (shader_map[current_key].users == 0) { //deallocate shader, as it's no longer in use VS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } - VS::get_singleton()->material_set_shader(_get_material(),RID()); + VS::get_singleton()->material_set_shader(_get_material(), RID()); } - if (material_mutex) material_mutex->unlock(); - } diff --git a/scene/resources/material.h b/scene/resources/material.h index 6b957d0203..a8288153c3 100644 --- a/scene/resources/material.h +++ b/scene/resources/material.h @@ -29,41 +29,38 @@ #ifndef MATERIAL_H #define MATERIAL_H -#include "servers/visual_server.h" -#include "scene/resources/texture.h" -#include "scene/resources/shader.h" #include "resource.h" -#include "servers/visual/shader_language.h" +#include "scene/resources/shader.h" +#include "scene/resources/texture.h" #include "self_list.h" +#include "servers/visual/shader_language.h" +#include "servers/visual_server.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class Material : public Resource { - GDCLASS(Material,Resource); + GDCLASS(Material, Resource); RES_BASE_EXTENSION("mtl"); - OBJ_SAVE_TYPE( Material ); + OBJ_SAVE_TYPE(Material); RID material; + protected: + _FORCE_INLINE_ RID _get_material() const { return material; } - _FORCE_INLINE_ RID _get_material() const { return material; } public: - virtual RID get_rid() const; Material(); virtual ~Material(); }; - class FixedSpatialMaterial : public Material { - GDCLASS(FixedSpatialMaterial,Material) - + GDCLASS(FixedSpatialMaterial, Material) public: - enum TextureParam { TEXTURE_ALBEDO, TEXTURE_SPECULAR, @@ -82,10 +79,8 @@ public: TEXTURE_DETAIL_NORMAL, TEXTURE_MAX - }; - enum DetailUV { DETAIL_UV_1, DETAIL_UV_2 @@ -106,7 +101,6 @@ public: FEATURE_MAX }; - enum BlendMode { BLEND_MODE_MIX, BLEND_MODE_ADD, @@ -167,10 +161,9 @@ private: uint32_t key; - bool operator<(const MaterialKey& p_key) const { + bool operator<(const MaterialKey &p_key) const { return key < p_key.key; } - }; struct ShaderData { @@ -178,31 +171,31 @@ private: int users; }; - static Map<MaterialKey,ShaderData> shader_map; + static Map<MaterialKey, ShaderData> shader_map; MaterialKey current_key; _FORCE_INLINE_ MaterialKey _compute_key() const { MaterialKey mk; - mk.key=0; - for(int i=0;i<FEATURE_MAX;i++) { + mk.key = 0; + for (int i = 0; i < FEATURE_MAX; i++) { if (features[i]) { - mk.feature_mask|=(1<<i); + mk.feature_mask |= (1 << i); } } - mk.detail_uv=detail_uv; - mk.blend_mode=blend_mode; - mk.depth_draw_mode=depth_draw_mode; - mk.cull_mode=cull_mode; - for(int i=0;i<FLAG_MAX;i++) { + mk.detail_uv = detail_uv; + mk.blend_mode = blend_mode; + mk.depth_draw_mode = depth_draw_mode; + mk.cull_mode = cull_mode; + for (int i = 0; i < FLAG_MAX; i++) { if (flags[i]) { - mk.flags|=(1<<i); + mk.flags |= (1 << i); } } - mk.detail_blend_mode=detail_blend_mode; - mk.diffuse_mode=diffuse_mode; - mk.specular_mode=specular_mode; + mk.detail_blend_mode = detail_blend_mode; + mk.diffuse_mode = diffuse_mode; + mk.specular_mode = specular_mode; return mk; } @@ -230,12 +223,11 @@ private: StringName uv2_scale; StringName uv2_offset; StringName texture_names[TEXTURE_MAX]; - }; static Mutex *material_mutex; static SelfList<FixedSpatialMaterial>::List dirty_materials; - static ShaderNames* shader_names; + static ShaderNames *shader_names; SelfList<FixedSpatialMaterial> element; @@ -282,23 +274,20 @@ private: Ref<Texture> textures[TEXTURE_MAX]; - _FORCE_INLINE_ void _validate_feature(const String& text, Feature feature,PropertyInfo& property) const; + _FORCE_INLINE_ void _validate_feature(const String &text, Feature feature, PropertyInfo &property) const; protected: - static void _bind_methods(); - void _validate_property(PropertyInfo& property) const; + void _validate_property(PropertyInfo &property) const; public: - - - void set_albedo(const Color& p_albedo); + void set_albedo(const Color &p_albedo); Color get_albedo() const; void set_specular_mode(SpecularMode p_mode); SpecularMode get_specular_mode() const; - void set_specular(const Color& p_specular); + void set_specular(const Color &p_specular); Color get_specular() const; void set_metalness(float p_metalness); @@ -307,7 +296,7 @@ public: void set_roughness(float p_roughness); float get_roughness() const; - void set_emission(const Color& p_emission); + void set_emission(const Color &p_emission); Color get_emission() const; void set_emission_energy(float p_emission_energy); @@ -367,25 +356,25 @@ public: void set_diffuse_mode(DiffuseMode p_mode); DiffuseMode get_diffuse_mode() const; - void set_flag(Flags p_flag,bool p_enabled); + void set_flag(Flags p_flag, bool p_enabled); bool get_flag(Flags p_flag) const; - void set_texture(TextureParam p_param,const Ref<Texture>& p_texture); + void set_texture(TextureParam p_param, const Ref<Texture> &p_texture); Ref<Texture> get_texture(TextureParam p_param) const; - void set_feature(Feature p_feature,bool p_enabled); + void set_feature(Feature p_feature, bool p_enabled); bool get_feature(Feature p_feature) const; - void set_uv1_scale(const Vector2& p_scale); + void set_uv1_scale(const Vector2 &p_scale); Vector2 get_uv1_scale() const; - void set_uv1_offset(const Vector2& p_offset); + void set_uv1_offset(const Vector2 &p_offset); Vector2 get_uv1_offset() const; - void set_uv2_scale(const Vector2& p_scale); + void set_uv2_scale(const Vector2 &p_scale); Vector2 get_uv2_scale() const; - void set_uv2_offset(const Vector2& p_offset); + void set_uv2_offset(const Vector2 &p_offset); Vector2 get_uv2_offset() const; static void init_shaders(); @@ -396,21 +385,16 @@ public: virtual ~FixedSpatialMaterial(); }; -VARIANT_ENUM_CAST( FixedSpatialMaterial::TextureParam ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::DetailUV ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::Feature ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::BlendMode ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::DepthDrawMode ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::CullMode ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::Flags ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::DiffuseMode ) -VARIANT_ENUM_CAST( FixedSpatialMaterial::SpecularMode ) +VARIANT_ENUM_CAST(FixedSpatialMaterial::TextureParam) +VARIANT_ENUM_CAST(FixedSpatialMaterial::DetailUV) +VARIANT_ENUM_CAST(FixedSpatialMaterial::Feature) +VARIANT_ENUM_CAST(FixedSpatialMaterial::BlendMode) +VARIANT_ENUM_CAST(FixedSpatialMaterial::DepthDrawMode) +VARIANT_ENUM_CAST(FixedSpatialMaterial::CullMode) +VARIANT_ENUM_CAST(FixedSpatialMaterial::Flags) +VARIANT_ENUM_CAST(FixedSpatialMaterial::DiffuseMode) +VARIANT_ENUM_CAST(FixedSpatialMaterial::SpecularMode) ////////////////////// - - - - - #endif diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp index 9990a6e796..f951cf1620 100644 --- a/scene/resources/mesh.cpp +++ b/scene/resources/mesh.cpp @@ -31,7 +31,7 @@ #include "scene/resources/convex_polygon_shape.h" #include "surface_tool.h" -static const char* _array_name[]={ +static const char *_array_name[] = { "vertex_array", "normal_array", "tangent_array", @@ -44,7 +44,7 @@ static const char* _array_name[]={ NULL }; -static const Mesh::ArrayType _array_types[]={ +static const Mesh::ArrayType _array_types[] = { Mesh::ARRAY_VERTEX, Mesh::ARRAY_NORMAL, @@ -57,9 +57,8 @@ static const Mesh::ArrayType _array_types[]={ Mesh::ARRAY_INDEX }; - /* compatibility */ -static const int _format_translate[]={ +static const int _format_translate[] = { Mesh::ARRAY_FORMAT_VERTEX, Mesh::ARRAY_FORMAT_NORMAL, @@ -72,22 +71,21 @@ static const int _format_translate[]={ Mesh::ARRAY_FORMAT_INDEX, }; +bool Mesh::_set(const StringName &p_name, const Variant &p_value) { -bool Mesh::_set(const StringName& p_name, const Variant& p_value) { - - String sname=p_name; + String sname = p_name; - if (p_name=="blend_shape/names") { + if (p_name == "blend_shape/names") { - PoolVector<String> sk=p_value; + PoolVector<String> sk = p_value; int sz = sk.size(); PoolVector<String>::Read r = sk.read(); - for(int i=0;i<sz;i++) + for (int i = 0; i < sz; i++) add_blend_shape(r[i]); return true; } - if (p_name=="blend_shape/mode") { + if (p_name == "blend_shape/mode") { set_blend_shape_mode(BlendShapeMode(int(p_value))); return true; @@ -95,19 +93,19 @@ bool Mesh::_set(const StringName& p_name, const Variant& p_value) { if (sname.begins_with("surface_")) { - int sl=sname.find("/"); - if (sl==-1) + int sl = sname.find("/"); + if (sl == -1) return false; - int idx=sname.substr(8,sl-8).to_int()-1; - String what = sname.get_slicec('/',1); - if (what=="material") - surface_set_material(idx,p_value); - else if (what=="name") - surface_set_name(idx,p_value); + int idx = sname.substr(8, sl - 8).to_int() - 1; + String what = sname.get_slicec('/', 1); + if (what == "material") + surface_set_material(idx, p_value); + else if (what == "name") + surface_set_name(idx, p_value); return true; } - if (sname=="custom_aabb/custom_aabb") { + if (sname == "custom_aabb/custom_aabb") { set_custom_aabb(p_value); return true; @@ -116,52 +114,51 @@ bool Mesh::_set(const StringName& p_name, const Variant& p_value) { if (!sname.begins_with("surfaces")) return false; + int idx = sname.get_slicec('/', 1).to_int(); + String what = sname.get_slicec('/', 2); - int idx=sname.get_slicec('/',1).to_int(); - String what=sname.get_slicec('/',2); - - if (idx==surfaces.size()) { + if (idx == surfaces.size()) { //create - Dictionary d=p_value; - ERR_FAIL_COND_V(!d.has("primitive"),false); + Dictionary d = p_value; + ERR_FAIL_COND_V(!d.has("primitive"), false); if (d.has("arrays")) { //old format - ERR_FAIL_COND_V(!d.has("morph_arrays"),false); - add_surface_from_arrays(PrimitiveType(int(d["primitive"])),d["arrays"],d["morph_arrays"]); + ERR_FAIL_COND_V(!d.has("morph_arrays"), false); + add_surface_from_arrays(PrimitiveType(int(d["primitive"])), d["arrays"], d["morph_arrays"]); } else if (d.has("array_data")) { PoolVector<uint8_t> array_data = d["array_data"]; PoolVector<uint8_t> array_index_data; if (d.has("array_index_data")) - array_index_data=d["array_index_data"]; + array_index_data = d["array_index_data"]; - ERR_FAIL_COND_V(!d.has("format"),false); + ERR_FAIL_COND_V(!d.has("format"), false); uint32_t format = d["format"]; - ERR_FAIL_COND_V(!d.has("primitive"),false); + ERR_FAIL_COND_V(!d.has("primitive"), false); uint32_t primitive = d["primitive"]; - ERR_FAIL_COND_V(!d.has("vertex_count"),false); + ERR_FAIL_COND_V(!d.has("vertex_count"), false); int vertex_count = d["vertex_count"]; - int index_count=0; + int index_count = 0; if (d.has("index_count")) - index_count=d["index_count"]; + index_count = d["index_count"]; - Vector< PoolVector<uint8_t> > blend_shapes; + Vector<PoolVector<uint8_t> > blend_shapes; if (d.has("blend_shape_data")) { - Array blend_shape_data=d["blend_shape_data"]; - for(int i=0;i<blend_shape_data.size();i++) { + Array blend_shape_data = d["blend_shape_data"]; + for (int i = 0; i < blend_shape_data.size(); i++) { PoolVector<uint8_t> shape = blend_shape_data[i]; blend_shapes.push_back(shape); } } - ERR_FAIL_COND_V(!d.has("aabb"),false); + ERR_FAIL_COND_V(!d.has("aabb"), false); Rect3 aabb = d["aabb"]; Vector<Rect3> bone_aabb; @@ -169,247 +166,228 @@ bool Mesh::_set(const StringName& p_name, const Variant& p_value) { Array baabb = d["bone_aabb"]; bone_aabb.resize(baabb.size()); - for(int i=0;i<baabb.size();i++) { - bone_aabb[i]=baabb[i]; + for (int i = 0; i < baabb.size(); i++) { + bone_aabb[i] = baabb[i]; } } - add_surface(format,PrimitiveType(primitive),array_data,vertex_count,array_index_data,index_count,aabb,blend_shapes,bone_aabb); + add_surface(format, PrimitiveType(primitive), array_data, vertex_count, array_index_data, index_count, aabb, blend_shapes, bone_aabb); } else { ERR_FAIL_V(false); } - if (d.has("material")) { - surface_set_material(idx,d["material"]); + surface_set_material(idx, d["material"]); } if (d.has("name")) { - surface_set_name(idx,d["name"]); + surface_set_name(idx, d["name"]); } - return true; } return false; } -bool Mesh::_get(const StringName& p_name,Variant &r_ret) const { +bool Mesh::_get(const StringName &p_name, Variant &r_ret) const { - String sname=p_name; + String sname = p_name; - if (p_name=="blend_shape/names") { + if (p_name == "blend_shape/names") { PoolVector<String> sk; - for(int i=0;i<blend_shapes.size();i++) + for (int i = 0; i < blend_shapes.size(); i++) sk.push_back(blend_shapes[i]); - r_ret=sk; + r_ret = sk; return true; - } else if (p_name=="blend_shape/mode") { + } else if (p_name == "blend_shape/mode") { r_ret = get_blend_shape_mode(); return true; } else if (sname.begins_with("surface_")) { - int sl=sname.find("/"); - if (sl==-1) + int sl = sname.find("/"); + if (sl == -1) return false; - int idx=sname.substr(8,sl-8).to_int()-1; - String what = sname.get_slicec('/',1); - if (what=="material") - r_ret=surface_get_material(idx); - else if (what=="name") - r_ret=surface_get_name(idx); + int idx = sname.substr(8, sl - 8).to_int() - 1; + String what = sname.get_slicec('/', 1); + if (what == "material") + r_ret = surface_get_material(idx); + else if (what == "name") + r_ret = surface_get_name(idx); return true; - } else if (sname=="custom_aabb/custom_aabb") { + } else if (sname == "custom_aabb/custom_aabb") { - r_ret=custom_aabb; + r_ret = custom_aabb; return true; } else if (!sname.begins_with("surfaces")) return false; - - int idx=sname.get_slicec('/',1).to_int(); - ERR_FAIL_INDEX_V(idx,surfaces.size(),false); + int idx = sname.get_slicec('/', 1).to_int(); + ERR_FAIL_INDEX_V(idx, surfaces.size(), false); Dictionary d; - d["array_data"]=VS::get_singleton()->mesh_surface_get_array(mesh,idx); - d["vertex_count"]=VS::get_singleton()->mesh_surface_get_array_len(mesh,idx); - d["array_index_data"]=VS::get_singleton()->mesh_surface_get_index_array(mesh,idx); - d["index_count"]=VS::get_singleton()->mesh_surface_get_array_index_len(mesh,idx); - d["primitive"]=VS::get_singleton()->mesh_surface_get_primitive_type(mesh,idx); - d["format"]=VS::get_singleton()->mesh_surface_get_format(mesh,idx); - d["aabb"]=VS::get_singleton()->mesh_surface_get_aabb(mesh,idx); + d["array_data"] = VS::get_singleton()->mesh_surface_get_array(mesh, idx); + d["vertex_count"] = VS::get_singleton()->mesh_surface_get_array_len(mesh, idx); + d["array_index_data"] = VS::get_singleton()->mesh_surface_get_index_array(mesh, idx); + d["index_count"] = VS::get_singleton()->mesh_surface_get_array_index_len(mesh, idx); + d["primitive"] = VS::get_singleton()->mesh_surface_get_primitive_type(mesh, idx); + d["format"] = VS::get_singleton()->mesh_surface_get_format(mesh, idx); + d["aabb"] = VS::get_singleton()->mesh_surface_get_aabb(mesh, idx); - Vector<Rect3> skel_aabb = VS::get_singleton()->mesh_surface_get_skeleton_aabb(mesh,idx); + Vector<Rect3> skel_aabb = VS::get_singleton()->mesh_surface_get_skeleton_aabb(mesh, idx); Array arr; - for(int i=0;i<skel_aabb.size();i++) { - arr[i]=skel_aabb[i]; + for (int i = 0; i < skel_aabb.size(); i++) { + arr[i] = skel_aabb[i]; } - d["skeleton_aabb"]=arr; + d["skeleton_aabb"] = arr; - Vector< PoolVector<uint8_t> > blend_shape_data = VS::get_singleton()->mesh_surface_get_blend_shapes(mesh,idx); + Vector<PoolVector<uint8_t> > blend_shape_data = VS::get_singleton()->mesh_surface_get_blend_shapes(mesh, idx); Array md; - for(int i=0;i<blend_shape_data.size();i++) { + for (int i = 0; i < blend_shape_data.size(); i++) { md.push_back(blend_shape_data[i]); } - d["blend_shape_data"]=md; + d["blend_shape_data"] = md; Ref<Material> m = surface_get_material(idx); if (m.is_valid()) - d["material"]=m; + d["material"] = m; String n = surface_get_name(idx); - if (n!="") - d["name"]=n; + if (n != "") + d["name"] = n; - r_ret=d; + r_ret = d; return true; } -void Mesh::_get_property_list( List<PropertyInfo> *p_list) const { +void Mesh::_get_property_list(List<PropertyInfo> *p_list) const { if (blend_shapes.size()) { - p_list->push_back(PropertyInfo(Variant::POOL_STRING_ARRAY,"blend_shape/names",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); - p_list->push_back(PropertyInfo(Variant::INT,"blend_shape/mode",PROPERTY_HINT_ENUM,"Normalized,Relative")); + p_list->push_back(PropertyInfo(Variant::POOL_STRING_ARRAY, "blend_shape/names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::INT, "blend_shape/mode", PROPERTY_HINT_ENUM, "Normalized,Relative")); } - for (int i=0;i<surfaces.size();i++) { + for (int i = 0; i < surfaces.size(); i++) { - p_list->push_back( PropertyInfo( Variant::DICTIONARY,"surfaces/"+itos(i), PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR ) ); - p_list->push_back( PropertyInfo( Variant::STRING,"surface_"+itos(i+1)+"/name", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR ) ); - p_list->push_back( PropertyInfo( Variant::OBJECT,"surface_"+itos(i+1)+"/material", PROPERTY_HINT_RESOURCE_TYPE,"Material",PROPERTY_USAGE_EDITOR ) ); + p_list->push_back(PropertyInfo(Variant::DICTIONARY, "surfaces/" + itos(i), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); + p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i + 1) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR)); + p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "Material", PROPERTY_USAGE_EDITOR)); } - p_list->push_back( PropertyInfo( Variant::RECT3,"custom_aabb/custom_aabb" ) ); - + p_list->push_back(PropertyInfo(Variant::RECT3, "custom_aabb/custom_aabb")); } - void Mesh::_recompute_aabb() { // regenerate AABB - aabb=Rect3(); + aabb = Rect3(); - for (int i=0;i<surfaces.size();i++) { + for (int i = 0; i < surfaces.size(); i++) { - if (i==0) - aabb=surfaces[i].aabb; + if (i == 0) + aabb = surfaces[i].aabb; else aabb.merge_with(surfaces[i].aabb); } - } -void Mesh::add_surface(uint32_t p_format,PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes,const Vector<Rect3>& p_bone_aabbs) { +void Mesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes, const Vector<Rect3> &p_bone_aabbs) { Surface s; - s.aabb=p_aabb; + s.aabb = p_aabb; surfaces.push_back(s); - VisualServer::get_singleton()->mesh_add_surface(mesh,p_format,(VS::PrimitiveType)p_primitive,p_array,p_vertex_count,p_index_array,p_index_count,p_aabb,p_blend_shapes,p_bone_aabbs); - + VisualServer::get_singleton()->mesh_add_surface(mesh, p_format, (VS::PrimitiveType)p_primitive, p_array, p_vertex_count, p_index_array, p_index_count, p_aabb, p_blend_shapes, p_bone_aabbs); } -void Mesh::add_surface_from_arrays(PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,uint32_t p_flags) { - +void Mesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, uint32_t p_flags) { - ERR_FAIL_COND(p_arrays.size()!=ARRAY_MAX); + ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX); Surface s; - VisualServer::get_singleton()->mesh_add_surface_from_arrays(mesh,(VisualServer::PrimitiveType)p_primitive, p_arrays,p_blend_shapes,p_flags); + VisualServer::get_singleton()->mesh_add_surface_from_arrays(mesh, (VisualServer::PrimitiveType)p_primitive, p_arrays, p_blend_shapes, p_flags); surfaces.push_back(s); - - /* make aABB? */ { - PoolVector<Vector3> vertices=p_arrays[ARRAY_VERTEX]; - int len=vertices.size(); - ERR_FAIL_COND(len==0); - PoolVector<Vector3>::Read r=vertices.read(); - const Vector3 *vtx=r.ptr(); + PoolVector<Vector3> vertices = p_arrays[ARRAY_VERTEX]; + int len = vertices.size(); + ERR_FAIL_COND(len == 0); + PoolVector<Vector3>::Read r = vertices.read(); + const Vector3 *vtx = r.ptr(); // check AABB Rect3 aabb; - for (int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - if (i==0) - aabb.pos=vtx[i]; + if (i == 0) + aabb.pos = vtx[i]; else aabb.expand_to(vtx[i]); } - surfaces[surfaces.size()-1].aabb=aabb; + surfaces[surfaces.size() - 1].aabb = aabb; _recompute_aabb(); - } - triangle_mesh=Ref<TriangleMesh>(); + triangle_mesh = Ref<TriangleMesh>(); _change_notify(); emit_changed(); - } Array Mesh::surface_get_arrays(int p_surface) const { - ERR_FAIL_INDEX_V(p_surface,surfaces.size(),Array()); - return VisualServer::get_singleton()->mesh_surface_get_arrays(mesh,p_surface); - + ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array()); + return VisualServer::get_singleton()->mesh_surface_get_arrays(mesh, p_surface); } Array Mesh::surface_get_blend_shape_arrays(int p_surface) const { - ERR_FAIL_INDEX_V(p_surface,surfaces.size(),Array()); + ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array()); return Array(); - } - - - int Mesh::get_surface_count() const { return surfaces.size(); } -void Mesh::add_blend_shape(const StringName& p_name) { +void Mesh::add_blend_shape(const StringName &p_name) { if (surfaces.size()) { ERR_EXPLAIN("Can't add a shape key count if surfaces are already created."); ERR_FAIL_COND(surfaces.size()); } - StringName name=p_name; + StringName name = p_name; - if (blend_shapes.find(name)!=-1 ) { + if (blend_shapes.find(name) != -1) { - int count=2; + int count = 2; do { name = String(p_name) + " " + itos(count); count++; - } while(blend_shapes.find(name)!=-1); + } while (blend_shapes.find(name) != -1); } blend_shapes.push_back(name); - VS::get_singleton()->mesh_set_blend_shape_count(mesh,blend_shapes.size()); - + VS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size()); } - int Mesh::get_blend_shape_count() const { return blend_shapes.size(); } StringName Mesh::get_blend_shape_name(int p_index) const { - ERR_FAIL_INDEX_V( p_index, blend_shapes.size(),StringName() ); + ERR_FAIL_INDEX_V(p_index, blend_shapes.size(), StringName()); return blend_shapes[p_index]; } void Mesh::clear_blend_shapes() { @@ -424,8 +402,8 @@ void Mesh::clear_blend_shapes() { void Mesh::set_blend_shape_mode(BlendShapeMode p_mode) { - blend_shape_mode=p_mode; - VS::get_singleton()->mesh_set_blend_shape_mode(mesh,(VS::BlendShapeMode)p_mode); + blend_shape_mode = p_mode; + VS::get_singleton()->mesh_set_blend_shape_mode(mesh, (VS::BlendShapeMode)p_mode); } Mesh::BlendShapeMode Mesh::get_blend_shape_mode() const { @@ -433,113 +411,99 @@ Mesh::BlendShapeMode Mesh::get_blend_shape_mode() const { return blend_shape_mode; } - void Mesh::surface_remove(int p_idx) { - ERR_FAIL_INDEX(p_idx, surfaces.size() ); - VisualServer::get_singleton()->mesh_remove_surface(mesh,p_idx); + ERR_FAIL_INDEX(p_idx, surfaces.size()); + VisualServer::get_singleton()->mesh_remove_surface(mesh, p_idx); surfaces.remove(p_idx); - triangle_mesh=Ref<TriangleMesh>(); + triangle_mesh = Ref<TriangleMesh>(); _recompute_aabb(); _change_notify(); emit_changed(); } - - - - int Mesh::surface_get_array_len(int p_idx) const { - ERR_FAIL_INDEX_V( p_idx, surfaces.size(), -1 ); - return VisualServer::get_singleton()->mesh_surface_get_array_len( mesh, p_idx ); - + ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1); + return VisualServer::get_singleton()->mesh_surface_get_array_len(mesh, p_idx); } int Mesh::surface_get_array_index_len(int p_idx) const { - ERR_FAIL_INDEX_V( p_idx, surfaces.size(), -1 ); - return VisualServer::get_singleton()->mesh_surface_get_array_index_len( mesh, p_idx ); - + ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1); + return VisualServer::get_singleton()->mesh_surface_get_array_index_len(mesh, p_idx); } uint32_t Mesh::surface_get_format(int p_idx) const { - ERR_FAIL_INDEX_V( p_idx, surfaces.size(), 0 ); - return VisualServer::get_singleton()->mesh_surface_get_format( mesh, p_idx ); - + ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0); + return VisualServer::get_singleton()->mesh_surface_get_format(mesh, p_idx); } - - Mesh::PrimitiveType Mesh::surface_get_primitive_type(int p_idx) const { - ERR_FAIL_INDEX_V( p_idx, surfaces.size(), PRIMITIVE_LINES ); - return (PrimitiveType)VisualServer::get_singleton()->mesh_surface_get_primitive_type( mesh, p_idx ); + ERR_FAIL_INDEX_V(p_idx, surfaces.size(), PRIMITIVE_LINES); + return (PrimitiveType)VisualServer::get_singleton()->mesh_surface_get_primitive_type(mesh, p_idx); } +void Mesh::surface_set_material(int p_idx, const Ref<Material> &p_material) { -void Mesh::surface_set_material(int p_idx, const Ref<Material>& p_material) { - - ERR_FAIL_INDEX( p_idx, surfaces.size() ); - if (surfaces[p_idx].material==p_material) + ERR_FAIL_INDEX(p_idx, surfaces.size()); + if (surfaces[p_idx].material == p_material) return; - surfaces[p_idx].material=p_material; - VisualServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null()?RID():p_material->get_rid()); + surfaces[p_idx].material = p_material; + VisualServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null() ? RID() : p_material->get_rid()); _change_notify("material"); } -void Mesh::surface_set_name(int p_idx, const String& p_name) { +void Mesh::surface_set_name(int p_idx, const String &p_name) { - ERR_FAIL_INDEX( p_idx, surfaces.size() ); + ERR_FAIL_INDEX(p_idx, surfaces.size()); - surfaces[p_idx].name=p_name; + surfaces[p_idx].name = p_name; } -String Mesh::surface_get_name(int p_idx) const{ +String Mesh::surface_get_name(int p_idx) const { - ERR_FAIL_INDEX_V( p_idx, surfaces.size(),String() ); + ERR_FAIL_INDEX_V(p_idx, surfaces.size(), String()); return surfaces[p_idx].name; - } -void Mesh::surface_set_custom_aabb(int p_idx,const Rect3& p_aabb) { +void Mesh::surface_set_custom_aabb(int p_idx, const Rect3 &p_aabb) { - ERR_FAIL_INDEX( p_idx, surfaces.size() ); - surfaces[p_idx].aabb=p_aabb; -// set custom aabb too? + ERR_FAIL_INDEX(p_idx, surfaces.size()); + surfaces[p_idx].aabb = p_aabb; + // set custom aabb too? } -Ref<Material> Mesh::surface_get_material(int p_idx) const { +Ref<Material> Mesh::surface_get_material(int p_idx) const { - ERR_FAIL_INDEX_V( p_idx, surfaces.size(), Ref<Material>() ); + ERR_FAIL_INDEX_V(p_idx, surfaces.size(), Ref<Material>()); return surfaces[p_idx].material; - } -void Mesh::add_surface_from_mesh_data(const Geometry::MeshData& p_mesh_data) { +void Mesh::add_surface_from_mesh_data(const Geometry::MeshData &p_mesh_data) { - VisualServer::get_singleton()->mesh_add_surface_from_mesh_data( mesh, p_mesh_data ); + VisualServer::get_singleton()->mesh_add_surface_from_mesh_data(mesh, p_mesh_data); Rect3 aabb; - for (int i=0;i<p_mesh_data.vertices.size();i++) { + for (int i = 0; i < p_mesh_data.vertices.size(); i++) { - if (i==0) - aabb.pos=p_mesh_data.vertices[i]; + if (i == 0) + aabb.pos = p_mesh_data.vertices[i]; else aabb.expand_to(p_mesh_data.vertices[i]); } - Surface s; - s.aabb=aabb; - if (surfaces.size()==0) - aabb=s.aabb; + s.aabb = aabb; + if (surfaces.size() == 0) + aabb = s.aabb; else aabb.merge_with(s.aabb); - triangle_mesh=Ref<TriangleMesh>(); + triangle_mesh = Ref<TriangleMesh>(); surfaces.push_back(s); _change_notify(); @@ -556,11 +520,10 @@ Rect3 Mesh::get_aabb() const { return aabb; } +void Mesh::set_custom_aabb(const Rect3 &p_custom) { -void Mesh::set_custom_aabb(const Rect3& p_custom) { - - custom_aabb=p_custom; - VS::get_singleton()->mesh_set_custom_aabb(mesh,custom_aabb); + custom_aabb = p_custom; + VS::get_singleton()->mesh_set_custom_aabb(mesh, custom_aabb); } Rect3 Mesh::get_custom_aabb() const { @@ -568,15 +531,13 @@ Rect3 Mesh::get_custom_aabb() const { return custom_aabb; } - PoolVector<Face3> Mesh::get_faces() const { - Ref<TriangleMesh> tm = generate_triangle_mesh(); if (tm.is_valid()) return tm->get_faces(); return PoolVector<Face3>(); -/* + /* for (int i=0;i<surfaces.size();i++) { if (VisualServer::get_singleton()->mesh_surface_get_primitive_type( mesh, i ) != VisualServer::PRIMITIVE_TRIANGLES ) @@ -634,22 +595,20 @@ PoolVector<Face3> Mesh::get_faces() const { } */ - } Ref<Shape> Mesh::create_convex_shape() const { PoolVector<Vector3> vertices; - for(int i=0;i<get_surface_count();i++) { + for (int i = 0; i < get_surface_count(); i++) { Array a = surface_get_arrays(i); - PoolVector<Vector3> v=a[ARRAY_VERTEX]; + PoolVector<Vector3> v = a[ARRAY_VERTEX]; vertices.append_array(v); - } - Ref<ConvexPolygonShape> shape = memnew( ConvexPolygonShape ); + Ref<ConvexPolygonShape> shape = memnew(ConvexPolygonShape); shape->set_points(vertices); return shape; } @@ -657,26 +616,26 @@ Ref<Shape> Mesh::create_convex_shape() const { Ref<Shape> Mesh::create_trimesh_shape() const { PoolVector<Face3> faces = get_faces(); - if (faces.size()==0) + if (faces.size() == 0) return Ref<Shape>(); PoolVector<Vector3> face_points; - face_points.resize( faces.size()*3 ); + face_points.resize(faces.size() * 3); - for (int i=0;i<face_points.size();i++) { + for (int i = 0; i < face_points.size(); i++) { - Face3 f = faces.get( i/3 ); - face_points.set(i, f.vertex[i%3] ); + Face3 f = faces.get(i / 3); + face_points.set(i, f.vertex[i % 3]); } - Ref<ConcavePolygonShape> shape = memnew( ConcavePolygonShape ); + Ref<ConcavePolygonShape> shape = memnew(ConcavePolygonShape); shape->set_faces(face_points); return shape; } void Mesh::center_geometry() { -/* + /* Vector3 ofs = aabb.pos+aabb.size*0.5; for(int i=0;i<get_surface_count();i++) { @@ -700,17 +659,15 @@ void Mesh::center_geometry() { aabb.pos-=ofs; */ - } void Mesh::regen_normalmaps() { + Vector<Ref<SurfaceTool> > surfs; + for (int i = 0; i < get_surface_count(); i++) { - Vector< Ref<SurfaceTool> > surfs; - for(int i=0;i<get_surface_count();i++) { - - Ref<SurfaceTool> st = memnew( SurfaceTool ); - st->create_from(Ref<Mesh>(this),i); + Ref<SurfaceTool> st = memnew(SurfaceTool); + st->create_from(Ref<Mesh>(this), i); surfs.push_back(st); } @@ -718,129 +675,121 @@ void Mesh::regen_normalmaps() { surface_remove(0); } - for(int i=0;i<surfs.size();i++) { + for (int i = 0; i < surfs.size(); i++) { surfs[i]->generate_tangents(); surfs[i]->commit(Ref<Mesh>(this)); } } - - Ref<TriangleMesh> Mesh::generate_triangle_mesh() const { if (triangle_mesh.is_valid()) return triangle_mesh; - int facecount=0; + int facecount = 0; - for(int i=0;i<get_surface_count();i++) { + for (int i = 0; i < get_surface_count(); i++) { - if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES) + if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) continue; - if (surface_get_format(i)&ARRAY_FORMAT_INDEX) { + if (surface_get_format(i) & ARRAY_FORMAT_INDEX) { - facecount+=surface_get_array_index_len(i); + facecount += surface_get_array_index_len(i); } else { - facecount+=surface_get_array_len(i); + facecount += surface_get_array_len(i); } - } - if (facecount==0 || (facecount%3)!=0) + if (facecount == 0 || (facecount % 3) != 0) return triangle_mesh; PoolVector<Vector3> faces; faces.resize(facecount); - PoolVector<Vector3>::Write facesw=faces.write(); + PoolVector<Vector3>::Write facesw = faces.write(); - int widx=0; + int widx = 0; - for(int i=0;i<get_surface_count();i++) { + for (int i = 0; i < get_surface_count(); i++) { - if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES) + if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) continue; Array a = surface_get_arrays(i); int vc = surface_get_array_len(i); PoolVector<Vector3> vertices = a[ARRAY_VERTEX]; - PoolVector<Vector3>::Read vr=vertices.read(); + PoolVector<Vector3>::Read vr = vertices.read(); - if (surface_get_format(i)&ARRAY_FORMAT_INDEX) { + if (surface_get_format(i) & ARRAY_FORMAT_INDEX) { - int ic=surface_get_array_index_len(i); + int ic = surface_get_array_index_len(i); PoolVector<int> indices = a[ARRAY_INDEX]; PoolVector<int>::Read ir = indices.read(); - for(int i=0;i<ic;i++) { + for (int i = 0; i < ic; i++) { int index = ir[i]; - facesw[widx++]=vr[ index ]; + facesw[widx++] = vr[index]; } } else { - for(int i=0;i<vc;i++) - facesw[widx++]=vr[ i ]; + for (int i = 0; i < vc; i++) + facesw[widx++] = vr[i]; } - } - facesw=PoolVector<Vector3>::Write(); - + facesw = PoolVector<Vector3>::Write(); - triangle_mesh = Ref<TriangleMesh>( memnew( TriangleMesh )); + triangle_mesh = Ref<TriangleMesh>(memnew(TriangleMesh)); triangle_mesh->create(faces); return triangle_mesh; - - } Ref<Mesh> Mesh::create_outline(float p_margin) const { - Array arrays; - int index_accum=0; - for(int i=0;i<get_surface_count();i++) { + int index_accum = 0; + for (int i = 0; i < get_surface_count(); i++) { - if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES) + if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) continue; Array a = surface_get_arrays(i); - int vcount=0; + int vcount = 0; - if (i==0) { - arrays=a; - PoolVector<Vector3> v=a[ARRAY_VERTEX]; - index_accum+=v.size(); + if (i == 0) { + arrays = a; + PoolVector<Vector3> v = a[ARRAY_VERTEX]; + index_accum += v.size(); } else { - for(int j=0;j<arrays.size();j++) { + for (int j = 0; j < arrays.size(); j++) { - if (arrays[j].get_type()==Variant::NIL || a[j].get_type()==Variant::NIL) { + if (arrays[j].get_type() == Variant::NIL || a[j].get_type() == Variant::NIL) { //mismatch, do not use - arrays[j]=Variant(); + arrays[j] = Variant(); continue; } - switch(j) { + switch (j) { case ARRAY_VERTEX: - case ARRAY_NORMAL: { + case ARRAY_NORMAL: { PoolVector<Vector3> dst = arrays[j]; PoolVector<Vector3> src = a[j]; - if (j==ARRAY_VERTEX) - vcount=src.size(); - if (dst.size()==0 || src.size()==0) { - arrays[j]=Variant(); + if (j == ARRAY_VERTEX) + vcount = src.size(); + if (dst.size() == 0 || src.size() == 0) { + arrays[j] = Variant(); continue; } dst.append_array(src); - arrays[j]=dst; + arrays[j] = dst; } break; case ARRAY_TANGENT: case ARRAY_BONES: @@ -848,58 +797,56 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const { PoolVector<real_t> dst = arrays[j]; PoolVector<real_t> src = a[j]; - if (dst.size()==0 || src.size()==0) { - arrays[j]=Variant(); + if (dst.size() == 0 || src.size() == 0) { + arrays[j] = Variant(); continue; } dst.append_array(src); - arrays[j]=dst; + arrays[j] = dst; } break; case ARRAY_COLOR: { PoolVector<Color> dst = arrays[j]; PoolVector<Color> src = a[j]; - if (dst.size()==0 || src.size()==0) { - arrays[j]=Variant(); + if (dst.size() == 0 || src.size() == 0) { + arrays[j] = Variant(); continue; } dst.append_array(src); - arrays[j]=dst; + arrays[j] = dst; } break; case ARRAY_TEX_UV: case ARRAY_TEX_UV2: { PoolVector<Vector2> dst = arrays[j]; PoolVector<Vector2> src = a[j]; - if (dst.size()==0 || src.size()==0) { - arrays[j]=Variant(); + if (dst.size() == 0 || src.size() == 0) { + arrays[j] = Variant(); continue; } dst.append_array(src); - arrays[j]=dst; + arrays[j] = dst; } break; case ARRAY_INDEX: { PoolVector<int> dst = arrays[j]; PoolVector<int> src = a[j]; - if (dst.size()==0 || src.size()==0) { - arrays[j]=Variant(); + if (dst.size() == 0 || src.size() == 0) { + arrays[j] = Variant(); continue; } { int ss = src.size(); PoolVector<int>::Write w = src.write(); - for(int k=0;k<ss;k++) { - w[k]+=index_accum; + for (int k = 0; k < ss; k++) { + w[k] += index_accum; } - } dst.append_array(src); - arrays[j]=dst; - index_accum+=vcount; + arrays[j] = dst; + index_accum += vcount; } break; - } } } @@ -907,49 +854,47 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const { { PoolVector<int>::Write ir; - PoolVector<int> indices =arrays[ARRAY_INDEX]; - bool has_indices=false; - PoolVector<Vector3> vertices =arrays[ARRAY_VERTEX]; + PoolVector<int> indices = arrays[ARRAY_INDEX]; + bool has_indices = false; + PoolVector<Vector3> vertices = arrays[ARRAY_VERTEX]; int vc = vertices.size(); - ERR_FAIL_COND_V(!vc,Ref<Mesh>()); - PoolVector<Vector3>::Write r=vertices.write(); - + ERR_FAIL_COND_V(!vc, Ref<Mesh>()); + PoolVector<Vector3>::Write r = vertices.write(); if (indices.size()) { - vc=indices.size(); - ir=indices.write(); - has_indices=true; + vc = indices.size(); + ir = indices.write(); + has_indices = true; } - Map<Vector3,Vector3> normal_accum; + Map<Vector3, Vector3> normal_accum; //fill normals with triangle normals - for(int i=0;i<vc;i+=3) { - + for (int i = 0; i < vc; i += 3) { Vector3 t[3]; if (has_indices) { - t[0]=r[ir[i+0]]; - t[1]=r[ir[i+1]]; - t[2]=r[ir[i+2]]; + t[0] = r[ir[i + 0]]; + t[1] = r[ir[i + 1]]; + t[2] = r[ir[i + 2]]; } else { - t[0]=r[i+0]; - t[1]=r[i+1]; - t[2]=r[i+2]; + t[0] = r[i + 0]; + t[1] = r[i + 1]; + t[2] = r[i + 2]; } - Vector3 n = Plane(t[0],t[1],t[2]).normal; + Vector3 n = Plane(t[0], t[1], t[2]).normal; - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - Map<Vector3,Vector3>::Element *E=normal_accum.find(t[j]); + Map<Vector3, Vector3>::Element *E = normal_accum.find(t[j]); if (!E) { - normal_accum[t[j]]=n; + normal_accum[t[j]] = n; } else { float d = n.dot(E->get()); - if (d<1.0) - E->get()+=n*(1.0-d); + if (d < 1.0) + E->get() += n * (1.0 - d); //E->get()+=n; } } @@ -957,28 +902,26 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const { //normalize - for (Map<Vector3,Vector3>::Element *E=normal_accum.front();E;E=E->next()) { + for (Map<Vector3, Vector3>::Element *E = normal_accum.front(); E; E = E->next()) { E->get().normalize(); } - //displace normals int vc2 = vertices.size(); - for(int i=0;i<vc2;i++) { - + for (int i = 0; i < vc2; i++) { - Vector3 t=r[i]; + Vector3 t = r[i]; - Map<Vector3,Vector3>::Element *E=normal_accum.find(t); + Map<Vector3, Vector3>::Element *E = normal_accum.find(t); ERR_CONTINUE(!E); - t+=E->get()*p_margin; - r[i]=t; + t += E->get() * p_margin; + r[i] = t; } r = PoolVector<Vector3>::Write(); - arrays[ARRAY_VERTEX]=vertices; + arrays[ARRAY_VERTEX] = vertices; if (!has_indices) { @@ -986,112 +929,99 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const { new_indices.resize(vertices.size()); PoolVector<int>::Write iw = new_indices.write(); - for(int j=0;j<vc2;j+=3) { + for (int j = 0; j < vc2; j += 3) { - iw[j]=j; - iw[j+1]=j+2; - iw[j+2]=j+1; + iw[j] = j; + iw[j + 1] = j + 2; + iw[j + 2] = j + 1; } - iw=PoolVector<int>::Write(); - arrays[ARRAY_INDEX]=new_indices; + iw = PoolVector<int>::Write(); + arrays[ARRAY_INDEX] = new_indices; } else { - for(int j=0;j<vc;j+=3) { + for (int j = 0; j < vc; j += 3) { - SWAP(ir[j+1],ir[j+2]); + SWAP(ir[j + 1], ir[j + 2]); } - ir=PoolVector<int>::Write(); - arrays[ARRAY_INDEX]=indices; - + ir = PoolVector<int>::Write(); + arrays[ARRAY_INDEX] = indices; } } - - - - Ref<Mesh> newmesh = memnew( Mesh ); - newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES,arrays); + Ref<Mesh> newmesh = memnew(Mesh); + newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES, arrays); return newmesh; } - void Mesh::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_blend_shape","name"),&Mesh::add_blend_shape); - ClassDB::bind_method(D_METHOD("get_blend_shape_count"),&Mesh::get_blend_shape_count); - ClassDB::bind_method(D_METHOD("get_blend_shape_name","index"),&Mesh::get_blend_shape_name); - ClassDB::bind_method(D_METHOD("clear_blend_shapes"),&Mesh::clear_blend_shapes); - ClassDB::bind_method(D_METHOD("set_blend_shape_mode","mode"),&Mesh::set_blend_shape_mode); - ClassDB::bind_method(D_METHOD("get_blend_shape_mode"),&Mesh::get_blend_shape_mode); - - ClassDB::bind_method(D_METHOD("add_surface_from_arrays","primitive","arrays","blend_shapes","compress_flags"),&Mesh::add_surface_from_arrays,DEFVAL(Array()),DEFVAL(ARRAY_COMPRESS_DEFAULT)); - ClassDB::bind_method(D_METHOD("get_surface_count"),&Mesh::get_surface_count); - ClassDB::bind_method(D_METHOD("surface_remove","surf_idx"),&Mesh::surface_remove); - ClassDB::bind_method(D_METHOD("surface_get_array_len","surf_idx"),&Mesh::surface_get_array_len); - ClassDB::bind_method(D_METHOD("surface_get_array_index_len","surf_idx"),&Mesh::surface_get_array_index_len); - ClassDB::bind_method(D_METHOD("surface_get_format","surf_idx"),&Mesh::surface_get_format); - ClassDB::bind_method(D_METHOD("surface_get_primitive_type","surf_idx"),&Mesh::surface_get_primitive_type); - ClassDB::bind_method(D_METHOD("surface_set_material","surf_idx","material:Material"),&Mesh::surface_set_material); - ClassDB::bind_method(D_METHOD("surface_get_material:Material","surf_idx"),&Mesh::surface_get_material); - ClassDB::bind_method(D_METHOD("surface_set_name","surf_idx","name"),&Mesh::surface_set_name); - ClassDB::bind_method(D_METHOD("surface_get_name","surf_idx"),&Mesh::surface_get_name); - ClassDB::bind_method(D_METHOD("center_geometry"),&Mesh::center_geometry); - ClassDB::set_method_flags(get_class_static(),_scs_create("center_geometry"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - ClassDB::bind_method(D_METHOD("regen_normalmaps"),&Mesh::regen_normalmaps); - ClassDB::set_method_flags(get_class_static(),_scs_create("regen_normalmaps"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - - ClassDB::bind_method(D_METHOD("set_custom_aabb","aabb"),&Mesh::set_custom_aabb); - ClassDB::bind_method(D_METHOD("get_custom_aabb"),&Mesh::get_custom_aabb); - - - BIND_CONSTANT( NO_INDEX_ARRAY ); - BIND_CONSTANT( ARRAY_WEIGHTS_SIZE ); - - BIND_CONSTANT( ARRAY_VERTEX ); - BIND_CONSTANT( ARRAY_NORMAL ); - BIND_CONSTANT( ARRAY_TANGENT ); - BIND_CONSTANT( ARRAY_COLOR ); - BIND_CONSTANT( ARRAY_TEX_UV ); - BIND_CONSTANT( ARRAY_TEX_UV2 ); - BIND_CONSTANT( ARRAY_BONES ); - BIND_CONSTANT( ARRAY_WEIGHTS ); - BIND_CONSTANT( ARRAY_INDEX ); - - BIND_CONSTANT( ARRAY_FORMAT_VERTEX ); - BIND_CONSTANT( ARRAY_FORMAT_NORMAL ); - BIND_CONSTANT( ARRAY_FORMAT_TANGENT ); - BIND_CONSTANT( ARRAY_FORMAT_COLOR ); - BIND_CONSTANT( ARRAY_FORMAT_TEX_UV ); - BIND_CONSTANT( ARRAY_FORMAT_TEX_UV2 ); - BIND_CONSTANT( ARRAY_FORMAT_BONES ); - BIND_CONSTANT( ARRAY_FORMAT_WEIGHTS ); - BIND_CONSTANT( ARRAY_FORMAT_INDEX ); - - BIND_CONSTANT( PRIMITIVE_POINTS ); - BIND_CONSTANT( PRIMITIVE_LINES ); - BIND_CONSTANT( PRIMITIVE_LINE_STRIP ); - BIND_CONSTANT( PRIMITIVE_LINE_LOOP ); - BIND_CONSTANT( PRIMITIVE_TRIANGLES ); - BIND_CONSTANT( PRIMITIVE_TRIANGLE_STRIP ); - BIND_CONSTANT( PRIMITIVE_TRIANGLE_FAN ); - + ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &Mesh::add_blend_shape); + ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &Mesh::get_blend_shape_count); + ClassDB::bind_method(D_METHOD("get_blend_shape_name", "index"), &Mesh::get_blend_shape_name); + ClassDB::bind_method(D_METHOD("clear_blend_shapes"), &Mesh::clear_blend_shapes); + ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &Mesh::set_blend_shape_mode); + ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &Mesh::get_blend_shape_mode); + + ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "compress_flags"), &Mesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(ARRAY_COMPRESS_DEFAULT)); + ClassDB::bind_method(D_METHOD("get_surface_count"), &Mesh::get_surface_count); + ClassDB::bind_method(D_METHOD("surface_remove", "surf_idx"), &Mesh::surface_remove); + ClassDB::bind_method(D_METHOD("surface_get_array_len", "surf_idx"), &Mesh::surface_get_array_len); + ClassDB::bind_method(D_METHOD("surface_get_array_index_len", "surf_idx"), &Mesh::surface_get_array_index_len); + ClassDB::bind_method(D_METHOD("surface_get_format", "surf_idx"), &Mesh::surface_get_format); + ClassDB::bind_method(D_METHOD("surface_get_primitive_type", "surf_idx"), &Mesh::surface_get_primitive_type); + ClassDB::bind_method(D_METHOD("surface_set_material", "surf_idx", "material:Material"), &Mesh::surface_set_material); + ClassDB::bind_method(D_METHOD("surface_get_material:Material", "surf_idx"), &Mesh::surface_get_material); + ClassDB::bind_method(D_METHOD("surface_set_name", "surf_idx", "name"), &Mesh::surface_set_name); + ClassDB::bind_method(D_METHOD("surface_get_name", "surf_idx"), &Mesh::surface_get_name); + ClassDB::bind_method(D_METHOD("center_geometry"), &Mesh::center_geometry); + ClassDB::set_method_flags(get_class_static(), _scs_create("center_geometry"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("regen_normalmaps"), &Mesh::regen_normalmaps); + ClassDB::set_method_flags(get_class_static(), _scs_create("regen_normalmaps"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + + ClassDB::bind_method(D_METHOD("set_custom_aabb", "aabb"), &Mesh::set_custom_aabb); + ClassDB::bind_method(D_METHOD("get_custom_aabb"), &Mesh::get_custom_aabb); + + BIND_CONSTANT(NO_INDEX_ARRAY); + BIND_CONSTANT(ARRAY_WEIGHTS_SIZE); + + BIND_CONSTANT(ARRAY_VERTEX); + BIND_CONSTANT(ARRAY_NORMAL); + BIND_CONSTANT(ARRAY_TANGENT); + BIND_CONSTANT(ARRAY_COLOR); + BIND_CONSTANT(ARRAY_TEX_UV); + BIND_CONSTANT(ARRAY_TEX_UV2); + BIND_CONSTANT(ARRAY_BONES); + BIND_CONSTANT(ARRAY_WEIGHTS); + BIND_CONSTANT(ARRAY_INDEX); + + BIND_CONSTANT(ARRAY_FORMAT_VERTEX); + BIND_CONSTANT(ARRAY_FORMAT_NORMAL); + BIND_CONSTANT(ARRAY_FORMAT_TANGENT); + BIND_CONSTANT(ARRAY_FORMAT_COLOR); + BIND_CONSTANT(ARRAY_FORMAT_TEX_UV); + BIND_CONSTANT(ARRAY_FORMAT_TEX_UV2); + BIND_CONSTANT(ARRAY_FORMAT_BONES); + BIND_CONSTANT(ARRAY_FORMAT_WEIGHTS); + BIND_CONSTANT(ARRAY_FORMAT_INDEX); + + BIND_CONSTANT(PRIMITIVE_POINTS); + BIND_CONSTANT(PRIMITIVE_LINES); + BIND_CONSTANT(PRIMITIVE_LINE_STRIP); + BIND_CONSTANT(PRIMITIVE_LINE_LOOP); + BIND_CONSTANT(PRIMITIVE_TRIANGLES); + BIND_CONSTANT(PRIMITIVE_TRIANGLE_STRIP); + BIND_CONSTANT(PRIMITIVE_TRIANGLE_FAN); } - - Mesh::Mesh() { - mesh=VisualServer::get_singleton()->mesh_create(); - blend_shape_mode=BLEND_SHAPE_MODE_RELATIVE; - + mesh = VisualServer::get_singleton()->mesh_create(); + blend_shape_mode = BLEND_SHAPE_MODE_RELATIVE; } - Mesh::~Mesh() { VisualServer::get_singleton()->free(mesh); } - - diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h index 1af33ad836..8b1936ed06 100644 --- a/scene/resources/mesh.h +++ b/scene/resources/mesh.h @@ -29,86 +29,85 @@ #ifndef MESH_H #define MESH_H -#include "servers/visual_server.h" +#include "resource.h" #include "scene/resources/material.h" #include "scene/resources/shape.h" -#include "resource.h" +#include "servers/visual_server.h" #include "triangle_mesh.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class Mesh : public Resource { - GDCLASS( Mesh, Resource ); + GDCLASS(Mesh, Resource); RES_BASE_EXTENSION("msh"); public: - enum { - NO_INDEX_ARRAY=VisualServer::NO_INDEX_ARRAY, - ARRAY_WEIGHTS_SIZE=VisualServer::ARRAY_WEIGHTS_SIZE + NO_INDEX_ARRAY = VisualServer::NO_INDEX_ARRAY, + ARRAY_WEIGHTS_SIZE = VisualServer::ARRAY_WEIGHTS_SIZE }; enum ArrayType { - ARRAY_VERTEX=VisualServer::ARRAY_VERTEX, - ARRAY_NORMAL=VisualServer::ARRAY_NORMAL, - ARRAY_TANGENT=VisualServer::ARRAY_TANGENT, - ARRAY_COLOR=VisualServer::ARRAY_COLOR, - ARRAY_TEX_UV=VisualServer::ARRAY_TEX_UV, - ARRAY_TEX_UV2=VisualServer::ARRAY_TEX_UV2, - ARRAY_BONES=VisualServer::ARRAY_BONES, - ARRAY_WEIGHTS=VisualServer::ARRAY_WEIGHTS, - ARRAY_INDEX=VisualServer::ARRAY_INDEX, - ARRAY_MAX=VisualServer::ARRAY_MAX + ARRAY_VERTEX = VisualServer::ARRAY_VERTEX, + ARRAY_NORMAL = VisualServer::ARRAY_NORMAL, + ARRAY_TANGENT = VisualServer::ARRAY_TANGENT, + ARRAY_COLOR = VisualServer::ARRAY_COLOR, + ARRAY_TEX_UV = VisualServer::ARRAY_TEX_UV, + ARRAY_TEX_UV2 = VisualServer::ARRAY_TEX_UV2, + ARRAY_BONES = VisualServer::ARRAY_BONES, + ARRAY_WEIGHTS = VisualServer::ARRAY_WEIGHTS, + ARRAY_INDEX = VisualServer::ARRAY_INDEX, + ARRAY_MAX = VisualServer::ARRAY_MAX }; enum ArrayFormat { /* ARRAY FORMAT FLAGS */ - ARRAY_FORMAT_VERTEX=1<<ARRAY_VERTEX, // mandatory - ARRAY_FORMAT_NORMAL=1<<ARRAY_NORMAL, - ARRAY_FORMAT_TANGENT=1<<ARRAY_TANGENT, - ARRAY_FORMAT_COLOR=1<<ARRAY_COLOR, - ARRAY_FORMAT_TEX_UV=1<<ARRAY_TEX_UV, - ARRAY_FORMAT_TEX_UV2=1<<ARRAY_TEX_UV2, - ARRAY_FORMAT_BONES=1<<ARRAY_BONES, - ARRAY_FORMAT_WEIGHTS=1<<ARRAY_WEIGHTS, - ARRAY_FORMAT_INDEX=1<<ARRAY_INDEX, - - ARRAY_COMPRESS_BASE=(ARRAY_INDEX+1), - ARRAY_COMPRESS_VERTEX=1<<(ARRAY_VERTEX+ARRAY_COMPRESS_BASE), // mandatory - ARRAY_COMPRESS_NORMAL=1<<(ARRAY_NORMAL+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_TANGENT=1<<(ARRAY_TANGENT+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_COLOR=1<<(ARRAY_COLOR+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_TEX_UV=1<<(ARRAY_TEX_UV+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_TEX_UV2=1<<(ARRAY_TEX_UV2+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_BONES=1<<(ARRAY_BONES+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_WEIGHTS=1<<(ARRAY_WEIGHTS+ARRAY_COMPRESS_BASE), - ARRAY_COMPRESS_INDEX=1<<(ARRAY_INDEX+ARRAY_COMPRESS_BASE), - - ARRAY_FLAG_USE_2D_VERTICES=ARRAY_COMPRESS_INDEX<<1, - ARRAY_FLAG_USE_16_BIT_BONES=ARRAY_COMPRESS_INDEX<<2, - - ARRAY_COMPRESS_DEFAULT=ARRAY_COMPRESS_VERTEX|ARRAY_COMPRESS_NORMAL|ARRAY_COMPRESS_TANGENT|ARRAY_COMPRESS_COLOR|ARRAY_COMPRESS_TEX_UV|ARRAY_COMPRESS_TEX_UV2|ARRAY_COMPRESS_WEIGHTS + ARRAY_FORMAT_VERTEX = 1 << ARRAY_VERTEX, // mandatory + ARRAY_FORMAT_NORMAL = 1 << ARRAY_NORMAL, + ARRAY_FORMAT_TANGENT = 1 << ARRAY_TANGENT, + ARRAY_FORMAT_COLOR = 1 << ARRAY_COLOR, + ARRAY_FORMAT_TEX_UV = 1 << ARRAY_TEX_UV, + ARRAY_FORMAT_TEX_UV2 = 1 << ARRAY_TEX_UV2, + ARRAY_FORMAT_BONES = 1 << ARRAY_BONES, + ARRAY_FORMAT_WEIGHTS = 1 << ARRAY_WEIGHTS, + ARRAY_FORMAT_INDEX = 1 << ARRAY_INDEX, + + ARRAY_COMPRESS_BASE = (ARRAY_INDEX + 1), + ARRAY_COMPRESS_VERTEX = 1 << (ARRAY_VERTEX + ARRAY_COMPRESS_BASE), // mandatory + ARRAY_COMPRESS_NORMAL = 1 << (ARRAY_NORMAL + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_TANGENT = 1 << (ARRAY_TANGENT + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_COLOR = 1 << (ARRAY_COLOR + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_TEX_UV = 1 << (ARRAY_TEX_UV + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_TEX_UV2 = 1 << (ARRAY_TEX_UV2 + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_BONES = 1 << (ARRAY_BONES + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_WEIGHTS = 1 << (ARRAY_WEIGHTS + ARRAY_COMPRESS_BASE), + ARRAY_COMPRESS_INDEX = 1 << (ARRAY_INDEX + ARRAY_COMPRESS_BASE), + + ARRAY_FLAG_USE_2D_VERTICES = ARRAY_COMPRESS_INDEX << 1, + ARRAY_FLAG_USE_16_BIT_BONES = ARRAY_COMPRESS_INDEX << 2, + + ARRAY_COMPRESS_DEFAULT = ARRAY_COMPRESS_VERTEX | ARRAY_COMPRESS_NORMAL | ARRAY_COMPRESS_TANGENT | ARRAY_COMPRESS_COLOR | ARRAY_COMPRESS_TEX_UV | ARRAY_COMPRESS_TEX_UV2 | ARRAY_COMPRESS_WEIGHTS }; enum PrimitiveType { - PRIMITIVE_POINTS=VisualServer::PRIMITIVE_POINTS, - PRIMITIVE_LINES=VisualServer::PRIMITIVE_LINES, - PRIMITIVE_LINE_STRIP=VisualServer::PRIMITIVE_LINE_STRIP, - PRIMITIVE_LINE_LOOP=VisualServer::PRIMITIVE_LINE_LOOP, - PRIMITIVE_TRIANGLES=VisualServer::PRIMITIVE_TRIANGLES, - PRIMITIVE_TRIANGLE_STRIP=VisualServer::PRIMITIVE_TRIANGLE_STRIP, - PRIMITIVE_TRIANGLE_FAN=VisualServer::PRIMITIVE_TRIANGLE_FAN, + PRIMITIVE_POINTS = VisualServer::PRIMITIVE_POINTS, + PRIMITIVE_LINES = VisualServer::PRIMITIVE_LINES, + PRIMITIVE_LINE_STRIP = VisualServer::PRIMITIVE_LINE_STRIP, + PRIMITIVE_LINE_LOOP = VisualServer::PRIMITIVE_LINE_LOOP, + PRIMITIVE_TRIANGLES = VisualServer::PRIMITIVE_TRIANGLES, + PRIMITIVE_TRIANGLE_STRIP = VisualServer::PRIMITIVE_TRIANGLE_STRIP, + PRIMITIVE_TRIANGLE_FAN = VisualServer::PRIMITIVE_TRIANGLE_FAN, }; enum BlendShapeMode { - BLEND_SHAPE_MODE_NORMALIZED=VS::BLEND_SHAPE_MODE_NORMALIZED, - BLEND_SHAPE_MODE_RELATIVE=VS::BLEND_SHAPE_MODE_RELATIVE, + BLEND_SHAPE_MODE_NORMALIZED = VS::BLEND_SHAPE_MODE_NORMALIZED, + BLEND_SHAPE_MODE_RELATIVE = VS::BLEND_SHAPE_MODE_RELATIVE, }; private: @@ -126,25 +125,23 @@ private: mutable Ref<TriangleMesh> triangle_mesh; - void _recompute_aabb(); -protected: - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; +protected: + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); public: - - void add_surface_from_arrays(PrimitiveType p_primitive, const Array& p_arrays, const Array& p_blend_shapes=Array(), uint32_t p_flags=ARRAY_COMPRESS_DEFAULT); - void add_surface(uint32_t p_format,PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>()); + void add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), uint32_t p_flags = ARRAY_COMPRESS_DEFAULT); + void add_surface(uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>()); Array surface_get_arrays(int p_surface) const; virtual Array surface_get_blend_shape_arrays(int p_surface) const; - void add_blend_shape(const StringName& p_name); + void add_blend_shape(const StringName &p_name); int get_blend_shape_count() const; StringName get_blend_shape_name(int p_index) const; void clear_blend_shapes(); @@ -155,8 +152,7 @@ public: int get_surface_count() const; void surface_remove(int p_idx); - void surface_set_custom_aabb(int p_surface,const Rect3& p_aabb); //only recognized by driver - + void surface_set_custom_aabb(int p_surface, const Rect3 &p_aabb); //only recognized by driver int surface_get_array_len(int p_idx) const; int surface_get_array_index_len(int p_idx) const; @@ -164,15 +160,15 @@ public: PrimitiveType surface_get_primitive_type(int p_idx) const; bool surface_is_alpha_sorting_enabled(int p_idx) const; - void surface_set_material(int p_idx, const Ref<Material>& p_material); + void surface_set_material(int p_idx, const Ref<Material> &p_material); Ref<Material> surface_get_material(int p_idx) const; - void surface_set_name(int p_idx, const String& p_name); + void surface_set_name(int p_idx, const String &p_name); String surface_get_name(int p_idx) const; - void add_surface_from_mesh_data(const Geometry::MeshData& p_mesh_data); + void add_surface_from_mesh_data(const Geometry::MeshData &p_mesh_data); - void set_custom_aabb(const Rect3& p_custom); + void set_custom_aabb(const Rect3 &p_custom); Rect3 get_custom_aabb() const; Rect3 get_aabb() const; @@ -191,11 +187,10 @@ public: Mesh(); ~Mesh(); - }; -VARIANT_ENUM_CAST( Mesh::ArrayType ); -VARIANT_ENUM_CAST( Mesh::PrimitiveType ); -VARIANT_ENUM_CAST( Mesh::BlendShapeMode ); +VARIANT_ENUM_CAST(Mesh::ArrayType); +VARIANT_ENUM_CAST(Mesh::PrimitiveType); +VARIANT_ENUM_CAST(Mesh::BlendShapeMode); #endif diff --git a/scene/resources/mesh_data_tool.cpp b/scene/resources/mesh_data_tool.cpp index abe335aa5b..fcc1f80d25 100644 --- a/scene/resources/mesh_data_tool.cpp +++ b/scene/resources/mesh_data_tool.cpp @@ -28,152 +28,142 @@ /*************************************************************************/ #include "mesh_data_tool.h" - void MeshDataTool::clear() { vertices.clear(); edges.clear(); faces.clear(); material = Ref<Material>(); - format=0; + format = 0; } +Error MeshDataTool::create_from_surface(const Ref<Mesh> &p_mesh, int p_surface) { -Error MeshDataTool::create_from_surface(const Ref<Mesh>& p_mesh,int p_surface) { - - ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER); - - ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(p_mesh->surface_get_primitive_type(p_surface)!=Mesh::PRIMITIVE_TRIANGLES,ERR_INVALID_PARAMETER); - + ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_mesh->surface_get_primitive_type(p_surface) != Mesh::PRIMITIVE_TRIANGLES, ERR_INVALID_PARAMETER); Array arrays = p_mesh->surface_get_arrays(p_surface); - ERR_FAIL_COND_V( arrays.empty(), ERR_INVALID_PARAMETER ); + ERR_FAIL_COND_V(arrays.empty(), ERR_INVALID_PARAMETER); PoolVector<Vector3> varray = arrays[Mesh::ARRAY_VERTEX]; int vcount = varray.size(); - ERR_FAIL_COND_V( vcount == 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(vcount == 0, ERR_INVALID_PARAMETER); clear(); format = p_mesh->surface_get_format(p_surface); - material=p_mesh->surface_get_material(p_surface); + material = p_mesh->surface_get_material(p_surface); PoolVector<Vector3>::Read vr = varray.read(); PoolVector<Vector3>::Read nr; - if (arrays[Mesh::ARRAY_NORMAL].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_NORMAL].get_type() != Variant::NIL) nr = arrays[Mesh::ARRAY_NORMAL].operator PoolVector<Vector3>().read(); PoolVector<real_t>::Read ta; - if (arrays[Mesh::ARRAY_TANGENT].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_TANGENT].get_type() != Variant::NIL) ta = arrays[Mesh::ARRAY_TANGENT].operator PoolVector<real_t>().read(); PoolVector<Vector2>::Read uv; - if (arrays[Mesh::ARRAY_TEX_UV].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_TEX_UV].get_type() != Variant::NIL) uv = arrays[Mesh::ARRAY_TEX_UV].operator PoolVector<Vector2>().read(); PoolVector<Vector2>::Read uv2; - if (arrays[Mesh::ARRAY_TEX_UV2].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_TEX_UV2].get_type() != Variant::NIL) uv2 = arrays[Mesh::ARRAY_TEX_UV2].operator PoolVector<Vector2>().read(); PoolVector<Color>::Read col; - if (arrays[Mesh::ARRAY_COLOR].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_COLOR].get_type() != Variant::NIL) col = arrays[Mesh::ARRAY_COLOR].operator PoolVector<Color>().read(); PoolVector<real_t>::Read bo; - if (arrays[Mesh::ARRAY_BONES].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_BONES].get_type() != Variant::NIL) bo = arrays[Mesh::ARRAY_BONES].operator PoolVector<real_t>().read(); PoolVector<real_t>::Read we; - if (arrays[Mesh::ARRAY_WEIGHTS].get_type()!=Variant::NIL) + if (arrays[Mesh::ARRAY_WEIGHTS].get_type() != Variant::NIL) we = arrays[Mesh::ARRAY_WEIGHTS].operator PoolVector<real_t>().read(); - vertices.resize(vcount); - for(int i=0;i<vcount;i++) { + for (int i = 0; i < vcount; i++) { Vertex v; - v.vertex=vr[i]; + v.vertex = vr[i]; if (nr.ptr()) - v.normal=nr[i]; + v.normal = nr[i]; if (ta.ptr()) - v.tangent=Plane(ta[i*4+0],ta[i*4+1],ta[i*4+2],ta[i*4+3]); + v.tangent = Plane(ta[i * 4 + 0], ta[i * 4 + 1], ta[i * 4 + 2], ta[i * 4 + 3]); if (uv.ptr()) - v.uv=uv[i]; + v.uv = uv[i]; if (uv2.ptr()) - v.uv2=uv2[i]; + v.uv2 = uv2[i]; if (col.ptr()) - v.color=col[i]; + v.color = col[i]; if (we.ptr()) { - v.weights.push_back(we[i*4+0]); - v.weights.push_back(we[i*4+1]); - v.weights.push_back(we[i*4+2]); - v.weights.push_back(we[i*4+3]); + v.weights.push_back(we[i * 4 + 0]); + v.weights.push_back(we[i * 4 + 1]); + v.weights.push_back(we[i * 4 + 2]); + v.weights.push_back(we[i * 4 + 3]); } if (bo.ptr()) { - v.bones.push_back(bo[i*4+0]); - v.bones.push_back(bo[i*4+1]); - v.bones.push_back(bo[i*4+2]); - v.bones.push_back(bo[i*4+3]); + v.bones.push_back(bo[i * 4 + 0]); + v.bones.push_back(bo[i * 4 + 1]); + v.bones.push_back(bo[i * 4 + 2]); + v.bones.push_back(bo[i * 4 + 3]); } - vertices[i]=v; - - + vertices[i] = v; } - PoolVector<int> indices; - if (arrays[Mesh::ARRAY_INDEX].get_type()!=Variant::NIL) { + if (arrays[Mesh::ARRAY_INDEX].get_type() != Variant::NIL) { indices = arrays[Mesh::ARRAY_INDEX]; } else { //make code simpler indices.resize(vcount); - PoolVector<int>::Write iw=indices.write(); - for(int i=0;i<vcount;i++) - iw[i]=i; + PoolVector<int>::Write iw = indices.write(); + for (int i = 0; i < vcount; i++) + iw[i] = i; } - - int icount=indices.size(); + int icount = indices.size(); PoolVector<int>::Read r = indices.read(); + Map<Point2i, int> edge_indices; - Map<Point2i,int> edge_indices; + for (int i = 0; i < icount; i += 3) { - for(int i=0;i<icount;i+=3) { + Vertex *v[3] = { &vertices[r[i + 0]], &vertices[r[i + 1]], &vertices[r[i + 2]] }; - Vertex*v[3]={ &vertices[r[i+0]], &vertices[r[i+1]], &vertices[r[i+2]] }; - - int fidx=faces.size(); + int fidx = faces.size(); Face face; - for(int j=0;j<3;j++) { + for (int j = 0; j < 3; j++) { - face.v[j]=r[i+j]; + face.v[j] = r[i + j]; - Point2i edge(r[i+j],r[i+(j+1)%3]); + Point2i edge(r[i + j], r[i + (j + 1) % 3]); if (edge.x > edge.y) { - SWAP(edge.x,edge.y); + SWAP(edge.x, edge.y); } if (edge_indices.has(edge)) { - face.edges[j]=edge_indices[edge]; + face.edges[j] = edge_indices[edge]; } else { - face.edges[j]=edge_indices.size(); - edge_indices[edge]=face.edges[j]; + face.edges[j] = edge_indices.size(); + edge_indices[edge] = face.edges[j]; Edge e; - e.vertex[0]=edge.x; - e.vertex[1]=edge.y; + e.vertex[0] = edge.x; + e.vertex[1] = edge.y; edges.push_back(e); } @@ -182,22 +172,19 @@ Error MeshDataTool::create_from_surface(const Ref<Mesh>& p_mesh,int p_surface) { v[j]->edges.push_back(face.edges[j]); } - faces.push_back(face); } - return OK; } -Error MeshDataTool::commit_to_surface(const Ref<Mesh>& p_mesh) { +Error MeshDataTool::commit_to_surface(const Ref<Mesh> &p_mesh) { - ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER); Array arr; arr.resize(Mesh::ARRAY_MAX); - - int vcount=vertices.size(); + int vcount = vertices.size(); PoolVector<Vector3> v; PoolVector<Vector3> n; @@ -212,124 +199,119 @@ Error MeshDataTool::commit_to_surface(const Ref<Mesh>& p_mesh) { { v.resize(vcount); - PoolVector<Vector3>::Write vr=v.write(); + PoolVector<Vector3>::Write vr = v.write(); PoolVector<Vector3>::Write nr; - if (format&Mesh::ARRAY_FORMAT_NORMAL) { + if (format & Mesh::ARRAY_FORMAT_NORMAL) { n.resize(vcount); nr = n.write(); } PoolVector<real_t>::Write ta; - if (format&Mesh::ARRAY_FORMAT_TANGENT) { - t.resize(vcount*4); + if (format & Mesh::ARRAY_FORMAT_TANGENT) { + t.resize(vcount * 4); ta = t.write(); } - PoolVector<Vector2>::Write uv; - if (format&Mesh::ARRAY_FORMAT_TEX_UV) { + if (format & Mesh::ARRAY_FORMAT_TEX_UV) { u.resize(vcount); uv = u.write(); } PoolVector<Vector2>::Write uv2; - if (format&Mesh::ARRAY_FORMAT_TEX_UV2) { + if (format & Mesh::ARRAY_FORMAT_TEX_UV2) { u2.resize(vcount); uv2 = u2.write(); } PoolVector<Color>::Write col; - if (format&Mesh::ARRAY_FORMAT_COLOR) { + if (format & Mesh::ARRAY_FORMAT_COLOR) { c.resize(vcount); col = c.write(); } PoolVector<real_t>::Write bo; - if (format&Mesh::ARRAY_FORMAT_BONES) { - b.resize(vcount*4); + if (format & Mesh::ARRAY_FORMAT_BONES) { + b.resize(vcount * 4); bo = b.write(); } PoolVector<real_t>::Write we; - if (format&Mesh::ARRAY_FORMAT_WEIGHTS) { - w.resize(vcount*4); + if (format & Mesh::ARRAY_FORMAT_WEIGHTS) { + w.resize(vcount * 4); we = w.write(); } + for (int i = 0; i < vcount; i++) { - for(int i=0;i<vcount;i++) { - - Vertex &vtx=vertices[i]; + Vertex &vtx = vertices[i]; - vr[i]=vtx.vertex; + vr[i] = vtx.vertex; if (nr.ptr()) - nr[i]=vtx.normal; + nr[i] = vtx.normal; if (ta.ptr()) { - ta[i*4+0]=vtx.tangent.normal.x; - ta[i*4+1]=vtx.tangent.normal.y; - ta[i*4+2]=vtx.tangent.normal.z; - ta[i*4+3]=vtx.tangent.d; + ta[i * 4 + 0] = vtx.tangent.normal.x; + ta[i * 4 + 1] = vtx.tangent.normal.y; + ta[i * 4 + 2] = vtx.tangent.normal.z; + ta[i * 4 + 3] = vtx.tangent.d; } if (uv.ptr()) - uv[i]=vtx.uv; + uv[i] = vtx.uv; if (uv2.ptr()) - uv2[i]=vtx.uv2; + uv2[i] = vtx.uv2; if (col.ptr()) - col[i]=vtx.color; + col[i] = vtx.color; if (we.ptr()) { - we[i*4+0]=vtx.weights[0]; - we[i*4+1]=vtx.weights[1]; - we[i*4+2]=vtx.weights[2]; - we[i*4+3]=vtx.weights[3]; - + we[i * 4 + 0] = vtx.weights[0]; + we[i * 4 + 1] = vtx.weights[1]; + we[i * 4 + 2] = vtx.weights[2]; + we[i * 4 + 3] = vtx.weights[3]; } if (bo.ptr()) { - bo[i*4+0]=vtx.bones[0]; - bo[i*4+1]=vtx.bones[1]; - bo[i*4+2]=vtx.bones[2]; - bo[i*4+3]=vtx.bones[3]; + bo[i * 4 + 0] = vtx.bones[0]; + bo[i * 4 + 1] = vtx.bones[1]; + bo[i * 4 + 2] = vtx.bones[2]; + bo[i * 4 + 3] = vtx.bones[3]; } - } int fc = faces.size(); - in.resize(fc*3); - PoolVector<int>::Write iw=in.write(); - for(int i=0;i<fc;i++) { + in.resize(fc * 3); + PoolVector<int>::Write iw = in.write(); + for (int i = 0; i < fc; i++) { - iw[i*3+0]=faces[i].v[0]; - iw[i*3+1]=faces[i].v[1]; - iw[i*3+2]=faces[i].v[2]; + iw[i * 3 + 0] = faces[i].v[0]; + iw[i * 3 + 1] = faces[i].v[1]; + iw[i * 3 + 2] = faces[i].v[2]; } - } - arr[Mesh::ARRAY_VERTEX]=v; - arr[Mesh::ARRAY_INDEX]=in; + arr[Mesh::ARRAY_VERTEX] = v; + arr[Mesh::ARRAY_INDEX] = in; if (n.size()) - arr[Mesh::ARRAY_NORMAL]=n; + arr[Mesh::ARRAY_NORMAL] = n; if (c.size()) - arr[Mesh::ARRAY_COLOR]=c; + arr[Mesh::ARRAY_COLOR] = c; if (u.size()) - arr[Mesh::ARRAY_TEX_UV]=u; + arr[Mesh::ARRAY_TEX_UV] = u; if (u2.size()) - arr[Mesh::ARRAY_TEX_UV2]=u2; + arr[Mesh::ARRAY_TEX_UV2] = u2; if (t.size()) - arr[Mesh::ARRAY_TANGENT]=t; + arr[Mesh::ARRAY_TANGENT] = t; if (b.size()) - arr[Mesh::ARRAY_BONES]=b; + arr[Mesh::ARRAY_BONES] = b; if (w.size()) - arr[Mesh::ARRAY_WEIGHTS]=w; + arr[Mesh::ARRAY_WEIGHTS] = w; - Ref<Mesh> ncmesh=p_mesh; + Ref<Mesh> ncmesh = p_mesh; int sc = ncmesh->get_surface_count(); - ncmesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr); - ncmesh->surface_set_material(sc,material); + ncmesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr); + ncmesh->surface_set_material(sc, material); return OK; } @@ -343,213 +325,185 @@ int MeshDataTool::get_vertex_count() const { return vertices.size(); } -int MeshDataTool::get_edge_count() const{ +int MeshDataTool::get_edge_count() const { return edges.size(); } -int MeshDataTool::get_face_count() const{ +int MeshDataTool::get_face_count() const { return faces.size(); } Vector3 MeshDataTool::get_vertex(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector3()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector3()); return vertices[p_idx].vertex; } -void MeshDataTool::set_vertex(int p_idx,const Vector3& p_vertex){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].vertex=p_vertex; +void MeshDataTool::set_vertex(int p_idx, const Vector3 &p_vertex) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].vertex = p_vertex; } -Vector3 MeshDataTool::get_vertex_normal(int p_idx) const{ +Vector3 MeshDataTool::get_vertex_normal(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector3()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector3()); return vertices[p_idx].normal; - } -void MeshDataTool::set_vertex_normal(int p_idx,const Vector3& p_normal){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].normal=p_normal; - format|=Mesh::ARRAY_FORMAT_NORMAL; +void MeshDataTool::set_vertex_normal(int p_idx, const Vector3 &p_normal) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].normal = p_normal; + format |= Mesh::ARRAY_FORMAT_NORMAL; } -Plane MeshDataTool::get_vertex_tangent(int p_idx) const{ +Plane MeshDataTool::get_vertex_tangent(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Plane()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Plane()); return vertices[p_idx].tangent; - } -void MeshDataTool::set_vertex_tangent(int p_idx,const Plane& p_tangent){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].tangent=p_tangent; - format|=Mesh::ARRAY_FORMAT_TANGENT; +void MeshDataTool::set_vertex_tangent(int p_idx, const Plane &p_tangent) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].tangent = p_tangent; + format |= Mesh::ARRAY_FORMAT_TANGENT; } -Vector2 MeshDataTool::get_vertex_uv(int p_idx) const{ +Vector2 MeshDataTool::get_vertex_uv(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector2()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector2()); return vertices[p_idx].uv; - } -void MeshDataTool::set_vertex_uv(int p_idx,const Vector2& p_uv){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].uv=p_uv; - format|=Mesh::ARRAY_FORMAT_TEX_UV; +void MeshDataTool::set_vertex_uv(int p_idx, const Vector2 &p_uv) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].uv = p_uv; + format |= Mesh::ARRAY_FORMAT_TEX_UV; } -Vector2 MeshDataTool::get_vertex_uv2(int p_idx) const{ +Vector2 MeshDataTool::get_vertex_uv2(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector2()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector2()); return vertices[p_idx].uv2; - } -void MeshDataTool::set_vertex_uv2(int p_idx,const Vector2& p_uv2){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].uv2=p_uv2; - format|=Mesh::ARRAY_FORMAT_TEX_UV2; +void MeshDataTool::set_vertex_uv2(int p_idx, const Vector2 &p_uv2) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].uv2 = p_uv2; + format |= Mesh::ARRAY_FORMAT_TEX_UV2; } -Color MeshDataTool::get_vertex_color(int p_idx) const{ +Color MeshDataTool::get_vertex_color(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Color()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Color()); return vertices[p_idx].color; - - } -void MeshDataTool::set_vertex_color(int p_idx,const Color& p_color){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].color=p_color; - format|=Mesh::ARRAY_FORMAT_COLOR; +void MeshDataTool::set_vertex_color(int p_idx, const Color &p_color) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].color = p_color; + format |= Mesh::ARRAY_FORMAT_COLOR; } -Vector<int> MeshDataTool::get_vertex_bones(int p_idx) const{ +Vector<int> MeshDataTool::get_vertex_bones(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<int>()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<int>()); return vertices[p_idx].bones; - } -void MeshDataTool::set_vertex_bones(int p_idx,const Vector<int>& p_bones){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].bones=p_bones; - format|=Mesh::ARRAY_FORMAT_BONES; +void MeshDataTool::set_vertex_bones(int p_idx, const Vector<int> &p_bones) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].bones = p_bones; + format |= Mesh::ARRAY_FORMAT_BONES; } -Vector<float> MeshDataTool::get_vertex_weights(int p_idx) const{ +Vector<float> MeshDataTool::get_vertex_weights(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<float>()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<float>()); return vertices[p_idx].weights; - } -void MeshDataTool::set_vertex_weights(int p_idx,const Vector<float>& p_weights){ - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].weights=p_weights; - format|=Mesh::ARRAY_FORMAT_WEIGHTS; - - +void MeshDataTool::set_vertex_weights(int p_idx, const Vector<float> &p_weights) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].weights = p_weights; + format |= Mesh::ARRAY_FORMAT_WEIGHTS; } -Variant MeshDataTool::get_vertex_meta(int p_idx) const{ +Variant MeshDataTool::get_vertex_meta(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Variant()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Variant()); return vertices[p_idx].meta; - } -void MeshDataTool::set_vertex_meta(int p_idx,const Variant& p_meta){ - - ERR_FAIL_INDEX(p_idx,vertices.size()); - vertices[p_idx].meta=p_meta; +void MeshDataTool::set_vertex_meta(int p_idx, const Variant &p_meta) { + ERR_FAIL_INDEX(p_idx, vertices.size()); + vertices[p_idx].meta = p_meta; } Vector<int> MeshDataTool::get_vertex_edges(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<int>()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<int>()); return vertices[p_idx].edges; - } -Vector<int> MeshDataTool::get_vertex_faces(int p_idx) const{ +Vector<int> MeshDataTool::get_vertex_faces(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<int>()); + ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<int>()); return vertices[p_idx].faces; - } -int MeshDataTool::get_edge_vertex(int p_edge,int p_vertex) const { +int MeshDataTool::get_edge_vertex(int p_edge, int p_vertex) const { - ERR_FAIL_INDEX_V(p_edge,edges.size(),-1); - ERR_FAIL_INDEX_V(p_vertex,2,-1); + ERR_FAIL_INDEX_V(p_edge, edges.size(), -1); + ERR_FAIL_INDEX_V(p_vertex, 2, -1); return edges[p_edge].vertex[p_vertex]; - } -Vector<int> MeshDataTool::get_edge_faces(int p_edge) const{ +Vector<int> MeshDataTool::get_edge_faces(int p_edge) const { - ERR_FAIL_INDEX_V(p_edge,edges.size(),Vector<int>()); + ERR_FAIL_INDEX_V(p_edge, edges.size(), Vector<int>()); return edges[p_edge].faces; - } -Variant MeshDataTool::get_edge_meta(int p_idx) const{ +Variant MeshDataTool::get_edge_meta(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,edges.size(),Variant()); + ERR_FAIL_INDEX_V(p_idx, edges.size(), Variant()); return edges[p_idx].meta; - } -void MeshDataTool::set_edge_meta(int p_idx,const Variant& p_meta){ +void MeshDataTool::set_edge_meta(int p_idx, const Variant &p_meta) { - ERR_FAIL_INDEX(p_idx,edges.size()); - edges[p_idx].meta=p_meta; + ERR_FAIL_INDEX(p_idx, edges.size()); + edges[p_idx].meta = p_meta; } -int MeshDataTool::get_face_vertex(int p_face,int p_vertex) const { +int MeshDataTool::get_face_vertex(int p_face, int p_vertex) const { - ERR_FAIL_INDEX_V(p_face,faces.size(),-1); - ERR_FAIL_INDEX_V(p_vertex,3,-1); + ERR_FAIL_INDEX_V(p_face, faces.size(), -1); + ERR_FAIL_INDEX_V(p_vertex, 3, -1); return faces[p_face].v[p_vertex]; - } -int MeshDataTool::get_face_edge(int p_face,int p_vertex) const{ +int MeshDataTool::get_face_edge(int p_face, int p_vertex) const { - ERR_FAIL_INDEX_V(p_face,faces.size(),-1); - ERR_FAIL_INDEX_V(p_vertex,3,-1); + ERR_FAIL_INDEX_V(p_face, faces.size(), -1); + ERR_FAIL_INDEX_V(p_vertex, 3, -1); return faces[p_face].edges[p_vertex]; - } -Variant MeshDataTool::get_face_meta(int p_face) const{ +Variant MeshDataTool::get_face_meta(int p_face) const { - ERR_FAIL_INDEX_V(p_face,faces.size(),Variant()); + ERR_FAIL_INDEX_V(p_face, faces.size(), Variant()); return faces[p_face].meta; - } -void MeshDataTool::set_face_meta(int p_face,const Variant& p_meta){ +void MeshDataTool::set_face_meta(int p_face, const Variant &p_meta) { - ERR_FAIL_INDEX(p_face,faces.size()); - faces[p_face].meta=p_meta; + ERR_FAIL_INDEX(p_face, faces.size()); + faces[p_face].meta = p_meta; } Vector3 MeshDataTool::get_face_normal(int p_face) const { - ERR_FAIL_INDEX_V(p_face,faces.size(),Vector3()); + ERR_FAIL_INDEX_V(p_face, faces.size(), Vector3()); Vector3 v0 = vertices[faces[p_face].v[0]].vertex; Vector3 v1 = vertices[faces[p_face].v[1]].vertex; Vector3 v2 = vertices[faces[p_face].v[2]].vertex; - return Plane(v0,v1,v2).normal; - + return Plane(v0, v1, v2).normal; } Ref<Material> MeshDataTool::get_material() const { @@ -559,71 +513,70 @@ Ref<Material> MeshDataTool::get_material() const { void MeshDataTool::set_material(const Ref<Material> &p_material) { - material=p_material; + material = p_material; } - void MeshDataTool::_bind_methods() { - ClassDB::bind_method(D_METHOD("clear"),&MeshDataTool::clear); - ClassDB::bind_method(D_METHOD("create_from_surface","mesh","surface"),&MeshDataTool::create_from_surface); - ClassDB::bind_method(D_METHOD("commit_to_surface","mesh"),&MeshDataTool::commit_to_surface); + ClassDB::bind_method(D_METHOD("clear"), &MeshDataTool::clear); + ClassDB::bind_method(D_METHOD("create_from_surface", "mesh", "surface"), &MeshDataTool::create_from_surface); + ClassDB::bind_method(D_METHOD("commit_to_surface", "mesh"), &MeshDataTool::commit_to_surface); - ClassDB::bind_method(D_METHOD("get_format"),&MeshDataTool::get_format); + ClassDB::bind_method(D_METHOD("get_format"), &MeshDataTool::get_format); - ClassDB::bind_method(D_METHOD("get_vertex_count"),&MeshDataTool::get_vertex_count); - ClassDB::bind_method(D_METHOD("get_edge_count"),&MeshDataTool::get_edge_count); - ClassDB::bind_method(D_METHOD("get_face_count"),&MeshDataTool::get_face_count); + ClassDB::bind_method(D_METHOD("get_vertex_count"), &MeshDataTool::get_vertex_count); + ClassDB::bind_method(D_METHOD("get_edge_count"), &MeshDataTool::get_edge_count); + ClassDB::bind_method(D_METHOD("get_face_count"), &MeshDataTool::get_face_count); - ClassDB::bind_method(D_METHOD("set_vertex","idx","vertex"),&MeshDataTool::set_vertex); - ClassDB::bind_method(D_METHOD("get_vertex","idx"),&MeshDataTool::get_vertex); + ClassDB::bind_method(D_METHOD("set_vertex", "idx", "vertex"), &MeshDataTool::set_vertex); + ClassDB::bind_method(D_METHOD("get_vertex", "idx"), &MeshDataTool::get_vertex); - ClassDB::bind_method(D_METHOD("set_vertex_normal","idx","normal"),&MeshDataTool::set_vertex_normal); - ClassDB::bind_method(D_METHOD("get_vertex_normal","idx"),&MeshDataTool::get_vertex_normal); + ClassDB::bind_method(D_METHOD("set_vertex_normal", "idx", "normal"), &MeshDataTool::set_vertex_normal); + ClassDB::bind_method(D_METHOD("get_vertex_normal", "idx"), &MeshDataTool::get_vertex_normal); - ClassDB::bind_method(D_METHOD("set_vertex_tangent","idx","tangent"),&MeshDataTool::set_vertex_tangent); - ClassDB::bind_method(D_METHOD("get_vertex_tangent","idx"),&MeshDataTool::get_vertex_tangent); + ClassDB::bind_method(D_METHOD("set_vertex_tangent", "idx", "tangent"), &MeshDataTool::set_vertex_tangent); + ClassDB::bind_method(D_METHOD("get_vertex_tangent", "idx"), &MeshDataTool::get_vertex_tangent); - ClassDB::bind_method(D_METHOD("set_vertex_uv","idx","uv"),&MeshDataTool::set_vertex_uv); - ClassDB::bind_method(D_METHOD("get_vertex_uv","idx"),&MeshDataTool::get_vertex_uv); + ClassDB::bind_method(D_METHOD("set_vertex_uv", "idx", "uv"), &MeshDataTool::set_vertex_uv); + ClassDB::bind_method(D_METHOD("get_vertex_uv", "idx"), &MeshDataTool::get_vertex_uv); - ClassDB::bind_method(D_METHOD("set_vertex_uv2","idx","uv2"),&MeshDataTool::set_vertex_uv2); - ClassDB::bind_method(D_METHOD("get_vertex_uv2","idx"),&MeshDataTool::get_vertex_uv2); + ClassDB::bind_method(D_METHOD("set_vertex_uv2", "idx", "uv2"), &MeshDataTool::set_vertex_uv2); + ClassDB::bind_method(D_METHOD("get_vertex_uv2", "idx"), &MeshDataTool::get_vertex_uv2); - ClassDB::bind_method(D_METHOD("set_vertex_color","idx","color"),&MeshDataTool::set_vertex_color); - ClassDB::bind_method(D_METHOD("get_vertex_color","idx"),&MeshDataTool::get_vertex_color); + ClassDB::bind_method(D_METHOD("set_vertex_color", "idx", "color"), &MeshDataTool::set_vertex_color); + ClassDB::bind_method(D_METHOD("get_vertex_color", "idx"), &MeshDataTool::get_vertex_color); - ClassDB::bind_method(D_METHOD("set_vertex_bones","idx","bones"),&MeshDataTool::set_vertex_bones); - ClassDB::bind_method(D_METHOD("get_vertex_bones","idx"),&MeshDataTool::get_vertex_bones); + ClassDB::bind_method(D_METHOD("set_vertex_bones", "idx", "bones"), &MeshDataTool::set_vertex_bones); + ClassDB::bind_method(D_METHOD("get_vertex_bones", "idx"), &MeshDataTool::get_vertex_bones); - ClassDB::bind_method(D_METHOD("set_vertex_weights","idx","weights"),&MeshDataTool::set_vertex_weights); - ClassDB::bind_method(D_METHOD("get_vertex_weights","idx"),&MeshDataTool::get_vertex_weights); + ClassDB::bind_method(D_METHOD("set_vertex_weights", "idx", "weights"), &MeshDataTool::set_vertex_weights); + ClassDB::bind_method(D_METHOD("get_vertex_weights", "idx"), &MeshDataTool::get_vertex_weights); - ClassDB::bind_method(D_METHOD("set_vertex_meta","idx","meta"),&MeshDataTool::set_vertex_meta); - ClassDB::bind_method(D_METHOD("get_vertex_meta","idx"),&MeshDataTool::get_vertex_meta); + ClassDB::bind_method(D_METHOD("set_vertex_meta", "idx", "meta"), &MeshDataTool::set_vertex_meta); + ClassDB::bind_method(D_METHOD("get_vertex_meta", "idx"), &MeshDataTool::get_vertex_meta); - ClassDB::bind_method(D_METHOD("get_vertex_edges","idx"),&MeshDataTool::get_vertex_edges); - ClassDB::bind_method(D_METHOD("get_vertex_faces","idx"),&MeshDataTool::get_vertex_faces); + ClassDB::bind_method(D_METHOD("get_vertex_edges", "idx"), &MeshDataTool::get_vertex_edges); + ClassDB::bind_method(D_METHOD("get_vertex_faces", "idx"), &MeshDataTool::get_vertex_faces); - ClassDB::bind_method(D_METHOD("get_edge_vertex","idx","vertex"),&MeshDataTool::get_edge_vertex); - ClassDB::bind_method(D_METHOD("get_edge_faces","idx","faces"),&MeshDataTool::get_edge_faces); + ClassDB::bind_method(D_METHOD("get_edge_vertex", "idx", "vertex"), &MeshDataTool::get_edge_vertex); + ClassDB::bind_method(D_METHOD("get_edge_faces", "idx", "faces"), &MeshDataTool::get_edge_faces); - ClassDB::bind_method(D_METHOD("set_edge_meta","idx","meta"),&MeshDataTool::set_edge_meta); - ClassDB::bind_method(D_METHOD("get_edge_meta","idx"),&MeshDataTool::get_edge_meta); + ClassDB::bind_method(D_METHOD("set_edge_meta", "idx", "meta"), &MeshDataTool::set_edge_meta); + ClassDB::bind_method(D_METHOD("get_edge_meta", "idx"), &MeshDataTool::get_edge_meta); - ClassDB::bind_method(D_METHOD("get_face_vertex","idx","vertex"),&MeshDataTool::get_face_vertex); - ClassDB::bind_method(D_METHOD("get_face_edge","idx","edge"),&MeshDataTool::get_face_edge); + ClassDB::bind_method(D_METHOD("get_face_vertex", "idx", "vertex"), &MeshDataTool::get_face_vertex); + ClassDB::bind_method(D_METHOD("get_face_edge", "idx", "edge"), &MeshDataTool::get_face_edge); - ClassDB::bind_method(D_METHOD("set_face_meta","idx","meta"),&MeshDataTool::set_face_meta); - ClassDB::bind_method(D_METHOD("get_face_meta","idx"),&MeshDataTool::get_face_meta); + ClassDB::bind_method(D_METHOD("set_face_meta", "idx", "meta"), &MeshDataTool::set_face_meta); + ClassDB::bind_method(D_METHOD("get_face_meta", "idx"), &MeshDataTool::get_face_meta); - ClassDB::bind_method(D_METHOD("get_face_normal","idx"),&MeshDataTool::get_face_normal); + ClassDB::bind_method(D_METHOD("get_face_normal", "idx"), &MeshDataTool::get_face_normal); - ClassDB::bind_method(D_METHOD("set_material","material:Material"),&MeshDataTool::set_material); - ClassDB::bind_method(D_METHOD("get_material","material"),&MeshDataTool::get_material); + ClassDB::bind_method(D_METHOD("set_material", "material:Material"), &MeshDataTool::set_material); + ClassDB::bind_method(D_METHOD("get_material", "material"), &MeshDataTool::get_material); } -MeshDataTool::MeshDataTool(){ +MeshDataTool::MeshDataTool() { clear(); } diff --git a/scene/resources/mesh_data_tool.h b/scene/resources/mesh_data_tool.h index fa9c50d2ec..14318a9f82 100644 --- a/scene/resources/mesh_data_tool.h +++ b/scene/resources/mesh_data_tool.h @@ -31,10 +31,9 @@ #include "scene/resources/mesh.h" -class MeshDataTool : public Reference { - - GDCLASS(MeshDataTool,Reference); +class MeshDataTool : public Reference { + GDCLASS(MeshDataTool, Reference); int format; struct Vertex { @@ -69,18 +68,17 @@ class MeshDataTool : public Reference { Variant meta; }; - Vector<Face> faces; Ref<Material> material; -protected: +protected: static void _bind_methods(); -public: +public: void clear(); - Error create_from_surface(const Ref<Mesh>& p_mesh,int p_surface); - Error commit_to_surface(const Ref<Mesh>& p_mesh); + Error create_from_surface(const Ref<Mesh> &p_mesh, int p_surface); + Error commit_to_surface(const Ref<Mesh> &p_mesh); int get_format() const; @@ -89,44 +87,44 @@ public: int get_face_count() const; Vector3 get_vertex(int p_idx) const; - void set_vertex(int p_idx,const Vector3& p_vertex); + void set_vertex(int p_idx, const Vector3 &p_vertex); Vector3 get_vertex_normal(int p_idx) const; - void set_vertex_normal(int p_idx,const Vector3& p_normal); + void set_vertex_normal(int p_idx, const Vector3 &p_normal); Plane get_vertex_tangent(int p_idx) const; - void set_vertex_tangent(int p_idx,const Plane& p_tangent); + void set_vertex_tangent(int p_idx, const Plane &p_tangent); Vector2 get_vertex_uv(int p_idx) const; - void set_vertex_uv(int p_idx,const Vector2& p_uv); + void set_vertex_uv(int p_idx, const Vector2 &p_uv); Vector2 get_vertex_uv2(int p_idx) const; - void set_vertex_uv2(int p_idx,const Vector2& p_uv2); + void set_vertex_uv2(int p_idx, const Vector2 &p_uv2); Color get_vertex_color(int p_idx) const; - void set_vertex_color(int p_idx,const Color& p_color); + void set_vertex_color(int p_idx, const Color &p_color); Vector<int> get_vertex_bones(int p_idx) const; - void set_vertex_bones(int p_idx,const Vector<int>& p_bones); + void set_vertex_bones(int p_idx, const Vector<int> &p_bones); Vector<float> get_vertex_weights(int p_idx) const; - void set_vertex_weights(int p_idx,const Vector<float>& p_weights); + void set_vertex_weights(int p_idx, const Vector<float> &p_weights); Variant get_vertex_meta(int p_idx) const; - void set_vertex_meta(int p_idx,const Variant& p_meta); + void set_vertex_meta(int p_idx, const Variant &p_meta); Vector<int> get_vertex_edges(int p_idx) const; Vector<int> get_vertex_faces(int p_idx) const; - int get_edge_vertex(int p_edge,int p_vertex) const; + int get_edge_vertex(int p_edge, int p_vertex) const; Vector<int> get_edge_faces(int p_edge) const; Variant get_edge_meta(int p_idx) const; - void set_edge_meta(int p_idx,const Variant& p_meta); + void set_edge_meta(int p_idx, const Variant &p_meta); - int get_face_vertex(int p_face,int p_vertex) const; - int get_face_edge(int p_face,int p_vertex) const; + int get_face_vertex(int p_face, int p_vertex) const; + int get_face_edge(int p_face, int p_vertex) const; Variant get_face_meta(int p_face) const; - void set_face_meta(int p_face,const Variant& p_meta); + void set_face_meta(int p_face, const Variant &p_meta); Vector3 get_face_normal(int p_face) const; Ref<Material> get_material() const; diff --git a/scene/resources/mesh_library.cpp b/scene/resources/mesh_library.cpp index becbf39dad..92ca921f25 100644 --- a/scene/resources/mesh_library.cpp +++ b/scene/resources/mesh_library.cpp @@ -28,28 +28,26 @@ /*************************************************************************/ #include "mesh_library.h" +bool MeshLibrary::_set(const StringName &p_name, const Variant &p_value) { - -bool MeshLibrary::_set(const StringName& p_name, const Variant& p_value) { - - String name=p_name; + String name = p_name; if (name.begins_with("item/")) { - int idx = name.get_slicec('/',1).to_int(); - String what = name.get_slicec('/',2); + int idx = name.get_slicec('/', 1).to_int(); + String what = name.get_slicec('/', 2); if (!item_map.has(idx)) create_item(idx); - if(what=="name") - set_item_name(idx,p_value); - else if(what=="mesh") - set_item_mesh(idx,p_value); - else if(what=="shape") - set_item_shape(idx,p_value); - else if(what=="preview") - set_item_preview(idx,p_value); - else if(what=="navmesh") - set_item_navmesh(idx,p_value); + if (what == "name") + set_item_name(idx, p_value); + else if (what == "mesh") + set_item_mesh(idx, p_value); + else if (what == "shape") + set_item_shape(idx, p_value); + else if (what == "preview") + set_item_preview(idx, p_value); + else if (what == "navmesh") + set_item_navmesh(idx, p_value); else return false; @@ -59,137 +57,125 @@ bool MeshLibrary::_set(const StringName& p_name, const Variant& p_value) { return false; } -bool MeshLibrary::_get(const StringName& p_name,Variant &r_ret) const { - - String name=p_name; - int idx = name.get_slicec('/',1).to_int(); - ERR_FAIL_COND_V(!item_map.has(idx),false); - String what = name.get_slicec('/',2); - - if(what=="name") - r_ret= get_item_name(idx); - else if(what=="mesh") - r_ret= get_item_mesh(idx); - else if(what=="shape") - r_ret= get_item_shape(idx); - else if(what=="navmesh") - r_ret= get_item_navmesh(idx); - else if(what=="preview") - r_ret= get_item_preview(idx); +bool MeshLibrary::_get(const StringName &p_name, Variant &r_ret) const { + + String name = p_name; + int idx = name.get_slicec('/', 1).to_int(); + ERR_FAIL_COND_V(!item_map.has(idx), false); + String what = name.get_slicec('/', 2); + + if (what == "name") + r_ret = get_item_name(idx); + else if (what == "mesh") + r_ret = get_item_mesh(idx); + else if (what == "shape") + r_ret = get_item_shape(idx); + else if (what == "navmesh") + r_ret = get_item_navmesh(idx); + else if (what == "preview") + r_ret = get_item_preview(idx); else return false; return true; } -void MeshLibrary::_get_property_list( List<PropertyInfo> *p_list) const { +void MeshLibrary::_get_property_list(List<PropertyInfo> *p_list) const { - for(Map<int,Item>::Element *E=item_map.front();E;E=E->next()) { + for (Map<int, Item>::Element *E = item_map.front(); E; E = E->next()) { - String name="item/"+itos(E->key())+"/"; - p_list->push_back( PropertyInfo(Variant::STRING,name+"name")); - p_list->push_back( PropertyInfo(Variant::OBJECT,name+"mesh",PROPERTY_HINT_RESOURCE_TYPE,"Mesh")); - p_list->push_back( PropertyInfo(Variant::OBJECT,name+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape")); - p_list->push_back( PropertyInfo(Variant::OBJECT,name+"navmesh",PROPERTY_HINT_RESOURCE_TYPE,"NavigationMesh")); - p_list->push_back( PropertyInfo(Variant::OBJECT,name+"preview",PROPERTY_HINT_RESOURCE_TYPE,"Texture",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_EDITOR_HELPER)); + String name = "item/" + itos(E->key()) + "/"; + p_list->push_back(PropertyInfo(Variant::STRING, name + "name")); + p_list->push_back(PropertyInfo(Variant::OBJECT, name + "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh")); + p_list->push_back(PropertyInfo(Variant::OBJECT, name + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape")); + p_list->push_back(PropertyInfo(Variant::OBJECT, name + "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh")); + p_list->push_back(PropertyInfo(Variant::OBJECT, name + "preview", PROPERTY_HINT_RESOURCE_TYPE, "Texture", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_EDITOR_HELPER)); } } - - void MeshLibrary::create_item(int p_item) { - ERR_FAIL_COND(p_item<0); + ERR_FAIL_COND(p_item < 0); ERR_FAIL_COND(item_map.has(p_item)); - item_map[p_item]=Item(); + item_map[p_item] = Item(); _change_notify(); } -void MeshLibrary::set_item_name(int p_item,const String& p_name) { +void MeshLibrary::set_item_name(int p_item, const String &p_name) { ERR_FAIL_COND(!item_map.has(p_item)); - item_map[p_item].name=p_name; + item_map[p_item].name = p_name; emit_changed(); _change_notify(); - } -void MeshLibrary::set_item_mesh(int p_item,const Ref<Mesh>& p_mesh) { +void MeshLibrary::set_item_mesh(int p_item, const Ref<Mesh> &p_mesh) { ERR_FAIL_COND(!item_map.has(p_item)); - item_map[p_item].mesh=p_mesh; + item_map[p_item].mesh = p_mesh; notify_change_to_owners(); emit_changed(); _change_notify(); - - } -void MeshLibrary::set_item_shape(int p_item,const Ref<Shape>& p_shape) { +void MeshLibrary::set_item_shape(int p_item, const Ref<Shape> &p_shape) { ERR_FAIL_COND(!item_map.has(p_item)); - item_map[p_item].shape=p_shape; + item_map[p_item].shape = p_shape; _change_notify(); notify_change_to_owners(); emit_changed(); _change_notify(); - } - -void MeshLibrary::set_item_navmesh(int p_item,const Ref<NavigationMesh>& p_navmesh) { +void MeshLibrary::set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh) { ERR_FAIL_COND(!item_map.has(p_item)); - item_map[p_item].navmesh=p_navmesh; + item_map[p_item].navmesh = p_navmesh; _change_notify(); notify_change_to_owners(); emit_changed(); _change_notify(); - } -void MeshLibrary::set_item_preview(int p_item,const Ref<Texture>& p_preview) { +void MeshLibrary::set_item_preview(int p_item, const Ref<Texture> &p_preview) { ERR_FAIL_COND(!item_map.has(p_item)); - item_map[p_item].preview=p_preview; + item_map[p_item].preview = p_preview; emit_changed(); _change_notify(); - } String MeshLibrary::get_item_name(int p_item) const { - ERR_FAIL_COND_V(!item_map.has(p_item),""); + ERR_FAIL_COND_V(!item_map.has(p_item), ""); return item_map[p_item].name; - } Ref<Mesh> MeshLibrary::get_item_mesh(int p_item) const { - ERR_FAIL_COND_V(!item_map.has(p_item),Ref<Mesh>()); + ERR_FAIL_COND_V(!item_map.has(p_item), Ref<Mesh>()); return item_map[p_item].mesh; - } Ref<Shape> MeshLibrary::get_item_shape(int p_item) const { - ERR_FAIL_COND_V(!item_map.has(p_item),Ref<Shape>()); + ERR_FAIL_COND_V(!item_map.has(p_item), Ref<Shape>()); return item_map[p_item].shape; } Ref<NavigationMesh> MeshLibrary::get_item_navmesh(int p_item) const { - ERR_FAIL_COND_V(!item_map.has(p_item),Ref<NavigationMesh>()); + ERR_FAIL_COND_V(!item_map.has(p_item), Ref<NavigationMesh>()); return item_map[p_item].navmesh; } - Ref<Texture> MeshLibrary::get_item_preview(int p_item) const { - ERR_FAIL_COND_V(!item_map.has(p_item),Ref<Texture>()); + ERR_FAIL_COND_V(!item_map.has(p_item), Ref<Texture>()); return item_map[p_item].preview; } bool MeshLibrary::has_item(int p_item) const { - return item_map.has(p_item) ; + return item_map.has(p_item); } void MeshLibrary::remove_item(int p_item) { @@ -198,7 +184,6 @@ void MeshLibrary::remove_item(int p_item) { notify_change_to_owners(); _change_notify(); emit_changed(); - } void MeshLibrary::clear() { @@ -213,20 +198,20 @@ Vector<int> MeshLibrary::get_item_list() const { Vector<int> ret; ret.resize(item_map.size()); - int idx=0; - for(Map<int,Item>::Element *E=item_map.front();E;E=E->next()) { + int idx = 0; + for (Map<int, Item>::Element *E = item_map.front(); E; E = E->next()) { - ret[idx++]=E->key(); + ret[idx++] = E->key(); } return ret; } -int MeshLibrary::find_item_name(const String& p_name) const { +int MeshLibrary::find_item_name(const String &p_name) const { - for(Map<int,Item>::Element *E=item_map.front();E;E=E->next()) { + for (Map<int, Item>::Element *E = item_map.front(); E; E = E->next()) { - if (E->get().name==p_name) + if (E->get().name == p_name) return E->key(); } return -1; @@ -237,33 +222,27 @@ int MeshLibrary::get_last_unused_item_id() const { if (!item_map.size()) return 0; else - return item_map.back()->key()+1; + return item_map.back()->key() + 1; } - - void MeshLibrary::_bind_methods() { - ClassDB::bind_method(D_METHOD("create_item","id"),&MeshLibrary::create_item); - ClassDB::bind_method(D_METHOD("set_item_name","id","name"),&MeshLibrary::set_item_name); - ClassDB::bind_method(D_METHOD("set_item_mesh","id","mesh:Mesh"),&MeshLibrary::set_item_mesh); - ClassDB::bind_method(D_METHOD("set_item_navmesh","id","navmesh:NavigationMesh"),&MeshLibrary::set_item_navmesh); - ClassDB::bind_method(D_METHOD("set_item_shape","id","shape:Shape"),&MeshLibrary::set_item_shape); - ClassDB::bind_method(D_METHOD("get_item_name","id"),&MeshLibrary::get_item_name); - ClassDB::bind_method(D_METHOD("get_item_mesh:Mesh","id"),&MeshLibrary::get_item_mesh); - ClassDB::bind_method(D_METHOD("get_item_navmesh:NavigationMesh","id"),&MeshLibrary::get_item_navmesh); - ClassDB::bind_method(D_METHOD("get_item_shape:Shape","id"),&MeshLibrary::get_item_shape); - ClassDB::bind_method(D_METHOD("remove_item","id"),&MeshLibrary::remove_item); - ClassDB::bind_method(D_METHOD("clear"),&MeshLibrary::clear); - ClassDB::bind_method(D_METHOD("get_item_list"),&MeshLibrary::get_item_list); - ClassDB::bind_method(D_METHOD("get_last_unused_item_id"),&MeshLibrary::get_last_unused_item_id); + ClassDB::bind_method(D_METHOD("create_item", "id"), &MeshLibrary::create_item); + ClassDB::bind_method(D_METHOD("set_item_name", "id", "name"), &MeshLibrary::set_item_name); + ClassDB::bind_method(D_METHOD("set_item_mesh", "id", "mesh:Mesh"), &MeshLibrary::set_item_mesh); + ClassDB::bind_method(D_METHOD("set_item_navmesh", "id", "navmesh:NavigationMesh"), &MeshLibrary::set_item_navmesh); + ClassDB::bind_method(D_METHOD("set_item_shape", "id", "shape:Shape"), &MeshLibrary::set_item_shape); + ClassDB::bind_method(D_METHOD("get_item_name", "id"), &MeshLibrary::get_item_name); + ClassDB::bind_method(D_METHOD("get_item_mesh:Mesh", "id"), &MeshLibrary::get_item_mesh); + ClassDB::bind_method(D_METHOD("get_item_navmesh:NavigationMesh", "id"), &MeshLibrary::get_item_navmesh); + ClassDB::bind_method(D_METHOD("get_item_shape:Shape", "id"), &MeshLibrary::get_item_shape); + ClassDB::bind_method(D_METHOD("remove_item", "id"), &MeshLibrary::remove_item); + ClassDB::bind_method(D_METHOD("clear"), &MeshLibrary::clear); + ClassDB::bind_method(D_METHOD("get_item_list"), &MeshLibrary::get_item_list); + ClassDB::bind_method(D_METHOD("get_last_unused_item_id"), &MeshLibrary::get_last_unused_item_id); } MeshLibrary::MeshLibrary() { - - } MeshLibrary::~MeshLibrary() { - - } diff --git a/scene/resources/mesh_library.h b/scene/resources/mesh_library.h index bb8012d3ff..5f4a695c56 100644 --- a/scene/resources/mesh_library.h +++ b/scene/resources/mesh_library.h @@ -29,15 +29,15 @@ #ifndef GRID_THEME_H #define GRID_THEME_H -#include "resource.h" -#include "mesh.h" -#include "shape.h" #include "map.h" +#include "mesh.h" +#include "resource.h" #include "scene/3d/navigation_mesh.h" +#include "shape.h" class MeshLibrary : public Resource { - GDCLASS(MeshLibrary,Resource); + GDCLASS(MeshLibrary, Resource); RES_BASE_EXTENSION("gt"); struct Item { @@ -48,24 +48,22 @@ class MeshLibrary : public Resource { Ref<NavigationMesh> navmesh; }; - Map<int,Item> item_map; + Map<int, Item> item_map; protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); -public: - +public: void create_item(int p_item); - void set_item_name(int p_item,const String& p_name); - void set_item_mesh(int p_item,const Ref<Mesh>& p_mesh); - void set_item_navmesh(int p_item, const Ref<NavigationMesh>& p_navmesh); - void set_item_shape(int p_item,const Ref<Shape>& p_shape); - void set_item_preview(int p_item,const Ref<Texture>& p_preview); + void set_item_name(int p_item, const String &p_name); + void set_item_mesh(int p_item, const Ref<Mesh> &p_mesh); + void set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh); + void set_item_shape(int p_item, const Ref<Shape> &p_shape); + void set_item_preview(int p_item, const Ref<Texture> &p_preview); String get_item_name(int p_item) const; Ref<Mesh> get_item_mesh(int p_item) const; Ref<NavigationMesh> get_item_navmesh(int p_item) const; @@ -77,7 +75,7 @@ public: void clear(); - int find_item_name(const String& p_name) const; + int find_item_name(const String &p_name) const; Vector<int> get_item_list() const; int get_last_unused_item_id() const; diff --git a/scene/resources/multimesh.cpp b/scene/resources/multimesh.cpp index 69ef3f18a6..6202109cd1 100644 --- a/scene/resources/multimesh.cpp +++ b/scene/resources/multimesh.cpp @@ -29,232 +29,201 @@ #include "multimesh.h" #include "servers/visual_server.h" - - -void MultiMesh::_set_transform_array(const PoolVector<Vector3>& p_array) { +void MultiMesh::_set_transform_array(const PoolVector<Vector3> &p_array) { int instance_count = get_instance_count(); PoolVector<Vector3> xforms = p_array; - int len=xforms.size(); - ERR_FAIL_COND((len/4) != instance_count); - if (len==0) + int len = xforms.size(); + ERR_FAIL_COND((len / 4) != instance_count); + if (len == 0) return; PoolVector<Vector3>::Read r = xforms.read(); - for(int i=0;i<len/4;i++) { + for (int i = 0; i < len / 4; i++) { Transform t; - t.basis[0]=r[i*4+0]; - t.basis[1]=r[i*4+1]; - t.basis[2]=r[i*4+2]; - t.origin=r[i*4+3]; + t.basis[0] = r[i * 4 + 0]; + t.basis[1] = r[i * 4 + 1]; + t.basis[2] = r[i * 4 + 2]; + t.origin = r[i * 4 + 3]; - set_instance_transform(i,t); + set_instance_transform(i, t); } - } PoolVector<Vector3> MultiMesh::_get_transform_array() const { int instance_count = get_instance_count(); - if (instance_count==0) + if (instance_count == 0) return PoolVector<Vector3>(); PoolVector<Vector3> xforms; - xforms.resize(instance_count*4); + xforms.resize(instance_count * 4); PoolVector<Vector3>::Write w = xforms.write(); - for(int i=0;i<instance_count;i++) { + for (int i = 0; i < instance_count; i++) { - Transform t=get_instance_transform(i); - w[i*4+0]=t.basis[0]; - w[i*4+1]=t.basis[1]; - w[i*4+2]=t.basis[2]; - w[i*4+3]=t.origin; + Transform t = get_instance_transform(i); + w[i * 4 + 0] = t.basis[0]; + w[i * 4 + 1] = t.basis[1]; + w[i * 4 + 2] = t.basis[2]; + w[i * 4 + 3] = t.origin; } return xforms; - } - -void MultiMesh::_set_color_array(const PoolVector<Color>& p_array) { +void MultiMesh::_set_color_array(const PoolVector<Color> &p_array) { int instance_count = get_instance_count(); PoolVector<Color> colors = p_array; - int len=colors.size(); + int len = colors.size(); ERR_FAIL_COND(len != instance_count); - if (len==0) + if (len == 0) return; PoolVector<Color>::Read r = colors.read(); - for(int i=0;i<len;i++) { + for (int i = 0; i < len; i++) { - set_instance_color(i,r[i]); + set_instance_color(i, r[i]); } - } PoolVector<Color> MultiMesh::_get_color_array() const { int instance_count = get_instance_count(); - if (instance_count==0) + if (instance_count == 0) return PoolVector<Color>(); PoolVector<Color> colors; colors.resize(instance_count); - for(int i=0;i<instance_count;i++) { + for (int i = 0; i < instance_count; i++) { - colors.set(i,get_instance_color(i)); + colors.set(i, get_instance_color(i)); } return colors; - } +void MultiMesh::set_mesh(const Ref<Mesh> &p_mesh) { - - -void MultiMesh::set_mesh(const Ref<Mesh>& p_mesh) { - - mesh=p_mesh; + mesh = p_mesh; if (!mesh.is_null()) - VisualServer::get_singleton()->multimesh_set_mesh(multimesh,mesh->get_rid()); + VisualServer::get_singleton()->multimesh_set_mesh(multimesh, mesh->get_rid()); else - VisualServer::get_singleton()->multimesh_set_mesh(multimesh,RID()); - + VisualServer::get_singleton()->multimesh_set_mesh(multimesh, RID()); } Ref<Mesh> MultiMesh::get_mesh() const { return mesh; - } void MultiMesh::set_instance_count(int p_count) { - VisualServer::get_singleton()->multimesh_allocate(multimesh,p_count,VS::MultimeshTransformFormat(transform_format),VS::MultimeshColorFormat(color_format)); - + VisualServer::get_singleton()->multimesh_allocate(multimesh, p_count, VS::MultimeshTransformFormat(transform_format), VS::MultimeshColorFormat(color_format)); } int MultiMesh::get_instance_count() const { return VisualServer::get_singleton()->multimesh_get_instance_count(multimesh); - } -void MultiMesh::set_instance_transform(int p_instance, const Transform& p_transform) { - - VisualServer::get_singleton()->multimesh_instance_set_transform(multimesh,p_instance,p_transform); - +void MultiMesh::set_instance_transform(int p_instance, const Transform &p_transform) { + VisualServer::get_singleton()->multimesh_instance_set_transform(multimesh, p_instance, p_transform); } Transform MultiMesh::get_instance_transform(int p_instance) const { - return VisualServer::get_singleton()->multimesh_instance_get_transform(multimesh,p_instance); - + return VisualServer::get_singleton()->multimesh_instance_get_transform(multimesh, p_instance); } -void MultiMesh::set_instance_color(int p_instance, const Color& p_color) { - - - VisualServer::get_singleton()->multimesh_instance_set_color(multimesh,p_instance,p_color); +void MultiMesh::set_instance_color(int p_instance, const Color &p_color) { + VisualServer::get_singleton()->multimesh_instance_set_color(multimesh, p_instance, p_color); } Color MultiMesh::get_instance_color(int p_instance) const { - return VisualServer::get_singleton()->multimesh_instance_get_color(multimesh,p_instance); - + return VisualServer::get_singleton()->multimesh_instance_get_color(multimesh, p_instance); } - Rect3 MultiMesh::get_aabb() const { return VisualServer::get_singleton()->multimesh_get_aabb(multimesh); - } - RID MultiMesh::get_rid() const { return multimesh; - } - void MultiMesh::set_color_format(ColorFormat p_color_format) { - color_format=p_color_format; + color_format = p_color_format; } -MultiMesh::ColorFormat MultiMesh::get_color_format() const{ +MultiMesh::ColorFormat MultiMesh::get_color_format() const { return color_format; } -void MultiMesh::set_transform_format(TransformFormat p_transform_format){ +void MultiMesh::set_transform_format(TransformFormat p_transform_format) { - transform_format=p_transform_format; + transform_format = p_transform_format; } -MultiMesh::TransformFormat MultiMesh::get_transform_format() const{ +MultiMesh::TransformFormat MultiMesh::get_transform_format() const { return transform_format; } - void MultiMesh::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_mesh","mesh:Mesh"),&MultiMesh::set_mesh); - ClassDB::bind_method(D_METHOD("get_mesh:Mesh"),&MultiMesh::get_mesh); - ClassDB::bind_method(D_METHOD("set_color_format","format"),&MultiMesh::set_color_format); - ClassDB::bind_method(D_METHOD("get_color_format"),&MultiMesh::get_color_format); - ClassDB::bind_method(D_METHOD("set_transform_format","format"),&MultiMesh::set_transform_format); - ClassDB::bind_method(D_METHOD("get_transform_format"),&MultiMesh::get_transform_format); - - ClassDB::bind_method(D_METHOD("set_instance_count","count"),&MultiMesh::set_instance_count); - ClassDB::bind_method(D_METHOD("get_instance_count"),&MultiMesh::get_instance_count); - ClassDB::bind_method(D_METHOD("set_instance_transform","instance","transform"),&MultiMesh::set_instance_transform); - ClassDB::bind_method(D_METHOD("get_instance_transform","instance"),&MultiMesh::get_instance_transform); - ClassDB::bind_method(D_METHOD("set_instance_color","instance","color"),&MultiMesh::set_instance_color); - ClassDB::bind_method(D_METHOD("get_instance_color","instance"),&MultiMesh::get_instance_color); - ClassDB::bind_method(D_METHOD("get_aabb"),&MultiMesh::get_aabb); - - - ClassDB::bind_method(D_METHOD("_set_transform_array"),&MultiMesh::_set_transform_array); - ClassDB::bind_method(D_METHOD("_get_transform_array"),&MultiMesh::_get_transform_array); - ClassDB::bind_method(D_METHOD("_set_color_array"),&MultiMesh::_set_color_array); - ClassDB::bind_method(D_METHOD("_get_color_array"),&MultiMesh::_get_color_array); - - - ADD_PROPERTY(PropertyInfo(Variant::INT,"color_format",PROPERTY_HINT_ENUM,"None,Byte,Float"), "set_color_format", "get_color_format"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"transform_format",PROPERTY_HINT_ENUM,"2D,3D"), "set_transform_format", "get_transform_format"); - ADD_PROPERTY(PropertyInfo(Variant::INT,"instance_count",PROPERTY_HINT_RANGE,"0,16384,1"), "set_instance_count", "get_instance_count"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"mesh",PROPERTY_HINT_RESOURCE_TYPE,"Mesh"), "set_mesh", "get_mesh"); - ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY,"transform_array",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_transform_array", "_get_transform_array"); - ADD_PROPERTY(PropertyInfo(Variant::POOL_COLOR_ARRAY,"color_array",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_color_array", "_get_color_array"); - - - - BIND_CONSTANT( TRANSFORM_2D ); - BIND_CONSTANT( TRANSFORM_3D ); - BIND_CONSTANT( COLOR_NONE ); - BIND_CONSTANT( COLOR_8BIT ); - BIND_CONSTANT( COLOR_FLOAT ); - + ClassDB::bind_method(D_METHOD("set_mesh", "mesh:Mesh"), &MultiMesh::set_mesh); + ClassDB::bind_method(D_METHOD("get_mesh:Mesh"), &MultiMesh::get_mesh); + ClassDB::bind_method(D_METHOD("set_color_format", "format"), &MultiMesh::set_color_format); + ClassDB::bind_method(D_METHOD("get_color_format"), &MultiMesh::get_color_format); + ClassDB::bind_method(D_METHOD("set_transform_format", "format"), &MultiMesh::set_transform_format); + ClassDB::bind_method(D_METHOD("get_transform_format"), &MultiMesh::get_transform_format); + + ClassDB::bind_method(D_METHOD("set_instance_count", "count"), &MultiMesh::set_instance_count); + ClassDB::bind_method(D_METHOD("get_instance_count"), &MultiMesh::get_instance_count); + ClassDB::bind_method(D_METHOD("set_instance_transform", "instance", "transform"), &MultiMesh::set_instance_transform); + ClassDB::bind_method(D_METHOD("get_instance_transform", "instance"), &MultiMesh::get_instance_transform); + ClassDB::bind_method(D_METHOD("set_instance_color", "instance", "color"), &MultiMesh::set_instance_color); + ClassDB::bind_method(D_METHOD("get_instance_color", "instance"), &MultiMesh::get_instance_color); + ClassDB::bind_method(D_METHOD("get_aabb"), &MultiMesh::get_aabb); + + ClassDB::bind_method(D_METHOD("_set_transform_array"), &MultiMesh::_set_transform_array); + ClassDB::bind_method(D_METHOD("_get_transform_array"), &MultiMesh::_get_transform_array); + ClassDB::bind_method(D_METHOD("_set_color_array"), &MultiMesh::_set_color_array); + ClassDB::bind_method(D_METHOD("_get_color_array"), &MultiMesh::_get_color_array); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "color_format", PROPERTY_HINT_ENUM, "None,Byte,Float"), "set_color_format", "get_color_format"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "transform_format", PROPERTY_HINT_ENUM, "2D,3D"), "set_transform_format", "get_transform_format"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "instance_count", PROPERTY_HINT_RANGE, "0,16384,1"), "set_instance_count", "get_instance_count"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "transform_array", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_transform_array", "_get_transform_array"); + ADD_PROPERTY(PropertyInfo(Variant::POOL_COLOR_ARRAY, "color_array", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_color_array", "_get_color_array"); + + BIND_CONSTANT(TRANSFORM_2D); + BIND_CONSTANT(TRANSFORM_3D); + BIND_CONSTANT(COLOR_NONE); + BIND_CONSTANT(COLOR_8BIT); + BIND_CONSTANT(COLOR_FLOAT); } MultiMesh::MultiMesh() { multimesh = VisualServer::get_singleton()->multimesh_create(); - color_format=COLOR_NONE; - transform_format=TRANSFORM_2D; + color_format = COLOR_NONE; + transform_format = TRANSFORM_2D; } MultiMesh::~MultiMesh() { diff --git a/scene/resources/multimesh.h b/scene/resources/multimesh.h index c86b33adcf..1ecf76142a 100644 --- a/scene/resources/multimesh.h +++ b/scene/resources/multimesh.h @@ -34,10 +34,10 @@ class MultiMesh : public Resource { - GDCLASS( MultiMesh, Resource ); + GDCLASS(MultiMesh, Resource); RES_BASE_EXTENSION("mmsh"); -public: +public: enum TransformFormat { TRANSFORM_2D = VS::MULTIMESH_TRANSFORM_2D, TRANSFORM_3D = VS::MULTIMESH_TRANSFORM_3D @@ -48,26 +48,24 @@ public: COLOR_8BIT = VS::MULTIMESH_COLOR_8BIT, COLOR_FLOAT = VS::MULTIMESH_COLOR_FLOAT, }; + private: Ref<Mesh> mesh; RID multimesh; TransformFormat transform_format; ColorFormat color_format; - protected: - static void _bind_methods(); - void _set_transform_array(const PoolVector<Vector3>& p_array); + void _set_transform_array(const PoolVector<Vector3> &p_array); PoolVector<Vector3> _get_transform_array() const; - void _set_color_array(const PoolVector<Color>& p_array); + void _set_color_array(const PoolVector<Color> &p_array); PoolVector<Color> _get_color_array() const; public: - - void set_mesh(const Ref<Mesh>& p_mesh); + void set_mesh(const Ref<Mesh> &p_mesh); Ref<Mesh> get_mesh() const; void set_color_format(ColorFormat p_color_format); @@ -79,10 +77,10 @@ public: void set_instance_count(int p_count); int get_instance_count() const; - void set_instance_transform(int p_instance, const Transform& p_transform); + void set_instance_transform(int p_instance, const Transform &p_transform); Transform get_instance_transform(int p_instance) const; - void set_instance_color(int p_instance, const Color& p_color); + void set_instance_color(int p_instance, const Color &p_color); Color get_instance_color(int p_instance) const; virtual Rect3 get_aabb() const; @@ -91,11 +89,9 @@ public: MultiMesh(); ~MultiMesh(); - }; - -VARIANT_ENUM_CAST( MultiMesh::TransformFormat ); -VARIANT_ENUM_CAST( MultiMesh::ColorFormat); +VARIANT_ENUM_CAST(MultiMesh::TransformFormat); +VARIANT_ENUM_CAST(MultiMesh::ColorFormat); #endif // MULTI_MESH_H diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp index 5e3347687a..0c2f07aa4a 100644 --- a/scene/resources/packed_scene.cpp +++ b/scene/resources/packed_scene.cpp @@ -27,234 +27,227 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "packed_scene.h" +#include "core/core_string_names.h" #include "global_config.h" #include "io/resource_loader.h" +#include "scene/2d/node_2d.h" #include "scene/3d/spatial.h" #include "scene/gui/control.h" -#include "scene/2d/node_2d.h" #include "scene/main/instance_placeholder.h" -#include "core/core_string_names.h" #define PACK_VERSION 2 bool SceneState::can_instance() const { - return nodes.size()>0; + return nodes.size() > 0; } - Node *SceneState::instance(GenEditState p_edit_state) const { // nodes where instancing failed (because something is missing) - List<Node*> stray_instances; + List<Node *> stray_instances; -#define NODE_FROM_ID(p_name,p_id)\ - Node *p_name;\ - if (p_id&FLAG_ID_IS_PATH) {\ - NodePath np=node_paths[p_id&FLAG_MASK];\ - p_name=ret_nodes[0]->_get_node(np);\ - } else {\ - ERR_FAIL_INDEX_V(p_id&FLAG_MASK,nc,NULL);\ - p_name=ret_nodes[p_id&FLAG_MASK];\ +#define NODE_FROM_ID(p_name, p_id) \ + Node *p_name; \ + if (p_id & FLAG_ID_IS_PATH) { \ + NodePath np = node_paths[p_id & FLAG_MASK]; \ + p_name = ret_nodes[0]->_get_node(np); \ + } else { \ + ERR_FAIL_INDEX_V(p_id &FLAG_MASK, nc, NULL); \ + p_name = ret_nodes[p_id & FLAG_MASK]; \ } int nc = nodes.size(); - ERR_FAIL_COND_V(nc==0,NULL); + ERR_FAIL_COND_V(nc == 0, NULL); - const StringName*snames=NULL; - int sname_count=names.size(); + const StringName *snames = NULL; + int sname_count = names.size(); if (sname_count) - snames=&names[0]; + snames = &names[0]; - const Variant*props=NULL; - int prop_count=variants.size(); + const Variant *props = NULL; + int prop_count = variants.size(); if (prop_count) - props=&variants[0]; + props = &variants[0]; //Vector<Variant> properties; const NodeData *nd = &nodes[0]; - Node **ret_nodes=(Node**)alloca( sizeof(Node*)*nc ); + Node **ret_nodes = (Node **)alloca(sizeof(Node *) * nc); - bool gen_node_path_cache=p_edit_state!=GEN_EDIT_STATE_DISABLED && node_path_cache.empty(); + bool gen_node_path_cache = p_edit_state != GEN_EDIT_STATE_DISABLED && node_path_cache.empty(); - Map<Ref<Resource>,Ref<Resource> > resources_local_to_scene; + Map<Ref<Resource>, Ref<Resource> > resources_local_to_scene; - for(int i=0;i<nc;i++) { + for (int i = 0; i < nc; i++) { - const NodeData &n=nd[i]; + const NodeData &n = nd[i]; - Node *parent=NULL; + Node *parent = NULL; - if (i>0) { + if (i > 0) { - NODE_FROM_ID(nparent,n.parent); + NODE_FROM_ID(nparent, n.parent); #ifdef DEBUG_ENABLED - if (!nparent && n.parent&FLAG_ID_IS_PATH) { - - WARN_PRINT(String("Parent path '"+String(node_paths[n.parent&FLAG_MASK])+"' for node '"+String(snames[n.name])+"' has vanished when instancing: '"+get_path()+"'.").ascii().get_data()); + if (!nparent && n.parent & FLAG_ID_IS_PATH) { + WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instancing: '" + get_path() + "'.").ascii().get_data()); } #endif - parent=nparent; + parent = nparent; } - Node *node=NULL; - + Node *node = NULL; - if (i==0 && base_scene_idx>=0) { + if (i == 0 && base_scene_idx >= 0) { //scene inheritance on root node - //print_line("scene inherit"); - Ref<PackedScene> sdata = props[ base_scene_idx ]; - ERR_FAIL_COND_V( !sdata.is_valid(), NULL); - node = sdata->instance(p_edit_state==GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); //only main gets main edit state - ERR_FAIL_COND_V(!node,NULL); - if (p_edit_state!=GEN_EDIT_STATE_DISABLED) { + //print_line("scene inherit"); + Ref<PackedScene> sdata = props[base_scene_idx]; + ERR_FAIL_COND_V(!sdata.is_valid(), NULL); + node = sdata->instance(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); //only main gets main edit state + ERR_FAIL_COND_V(!node, NULL); + if (p_edit_state != GEN_EDIT_STATE_DISABLED) { node->set_scene_inherited_state(sdata->get_state()); } - } else if (n.instance>=0) { + } else if (n.instance >= 0) { //instance a scene into this node - //print_line("instance"); - if (n.instance&FLAG_INSTANCE_IS_PLACEHOLDER) { + //print_line("instance"); + if (n.instance & FLAG_INSTANCE_IS_PLACEHOLDER) { - String path = props[n.instance&FLAG_MASK]; + String path = props[n.instance & FLAG_MASK]; if (disable_placeholders) { - Ref<PackedScene> sdata = ResourceLoader::load(path,"PackedScene"); - ERR_FAIL_COND_V( !sdata.is_valid(), NULL); - node = sdata->instance(p_edit_state==GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); - ERR_FAIL_COND_V(!node,NULL); + Ref<PackedScene> sdata = ResourceLoader::load(path, "PackedScene"); + ERR_FAIL_COND_V(!sdata.is_valid(), NULL); + node = sdata->instance(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); + ERR_FAIL_COND_V(!node, NULL); } else { - InstancePlaceholder *ip = memnew( InstancePlaceholder ); + InstancePlaceholder *ip = memnew(InstancePlaceholder); ip->set_instance_path(path); - node=ip; + node = ip; } node->set_scene_instance_load_placeholder(true); } else { - Ref<PackedScene> sdata = props[ n.instance&FLAG_MASK ]; - ERR_FAIL_COND_V( !sdata.is_valid(), NULL); - node = sdata->instance(p_edit_state==GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); - ERR_FAIL_COND_V(!node,NULL); - + Ref<PackedScene> sdata = props[n.instance & FLAG_MASK]; + ERR_FAIL_COND_V(!sdata.is_valid(), NULL); + node = sdata->instance(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); + ERR_FAIL_COND_V(!node, NULL); } - } else if (n.type==TYPE_INSTANCED) { + } else if (n.type == TYPE_INSTANCED) { //print_line("instanced"); //get the node from somewhere, it likely already exists from another instance if (parent) { - node=parent->_get_child_by_name(snames[n.name]); + node = parent->_get_child_by_name(snames[n.name]); #ifdef DEBUG_ENABLED if (!node) { - WARN_PRINT(String("Node '"+String(ret_nodes[0]->get_path_to(parent))+"/"+String(snames[n.name])+"' was modified from inside a instance, but it has vanished.").ascii().get_data()); + WARN_PRINT(String("Node '" + String(ret_nodes[0]->get_path_to(parent)) + "/" + String(snames[n.name]) + "' was modified from inside a instance, but it has vanished.").ascii().get_data()); } #endif } } else if (ClassDB::is_class_enabled(snames[n.type])) { - //print_line("created"); + //print_line("created"); //node belongs to this scene and must be created - Object * obj = ClassDB::instance(snames[ n.type ]); + Object *obj = ClassDB::instance(snames[n.type]); if (!obj || !obj->cast_to<Node>()) { if (obj) { memdelete(obj); - obj=NULL; + obj = NULL; } - WARN_PRINT(String("Warning node of type "+snames[n.type].operator String()+" does not exist.").ascii().get_data()); - if (n.parent>=0 && n.parent<nc && ret_nodes[n.parent]) { + WARN_PRINT(String("Warning node of type " + snames[n.type].operator String() + " does not exist.").ascii().get_data()); + if (n.parent >= 0 && n.parent < nc && ret_nodes[n.parent]) { if (ret_nodes[n.parent]->cast_to<Spatial>()) { - obj = memnew( Spatial ); + obj = memnew(Spatial); } else if (ret_nodes[n.parent]->cast_to<Control>()) { - obj = memnew( Control ); + obj = memnew(Control); } else if (ret_nodes[n.parent]->cast_to<Node2D>()) { - obj = memnew( Node2D ); + obj = memnew(Node2D); } } if (!obj) { - obj = memnew( Node ); + obj = memnew(Node); } } node = obj->cast_to<Node>(); } else { - print_line("wtf class is disabled for: "+itos(n.type)); - print_line("name: "+String(snames[n.type])); + print_line("wtf class is disabled for: " + itos(n.type)); + print_line("name: " + String(snames[n.type])); } - if (node) { // may not have found the node (part of instanced scene and removed) // if found all is good, otherwise ignore //properties - int nprop_count=n.properties.size(); + int nprop_count = n.properties.size(); if (nprop_count) { - const NodeData::Property* nprops=&n.properties[0]; + const NodeData::Property *nprops = &n.properties[0]; - for(int j=0;j<nprop_count;j++) { + for (int j = 0; j < nprop_count; j++) { bool valid; - ERR_FAIL_INDEX_V( nprops[j].name, sname_count, NULL ); - ERR_FAIL_INDEX_V( nprops[j].value, prop_count, NULL ); - + ERR_FAIL_INDEX_V(nprops[j].name, sname_count, NULL); + ERR_FAIL_INDEX_V(nprops[j].value, prop_count, NULL); - if (snames[ nprops[j].name ]==CoreStringNames::get_singleton()->_script) { + if (snames[nprops[j].name] == CoreStringNames::get_singleton()->_script) { //work around to avoid old script variables from disappearing, should be the proper fix to: //https://github.com/godotengine/godot/issues/2958 //store old state - List<Pair<StringName,Variant> > old_state; + List<Pair<StringName, Variant> > old_state; if (node->get_script_instance()) { node->get_script_instance()->get_property_state(old_state); } - node->set(snames[ nprops[j].name ],props[ nprops[j].value ],&valid); + node->set(snames[nprops[j].name], props[nprops[j].value], &valid); //restore old state for new script, if exists - for (List<Pair<StringName,Variant> >::Element *E=old_state.front();E;E=E->next()) { - node->set(E->get().first,E->get().second); + for (List<Pair<StringName, Variant> >::Element *E = old_state.front(); E; E = E->next()) { + node->set(E->get().first, E->get().second); } } else { - Variant value = props[ nprops[j].value ]; + Variant value = props[nprops[j].value]; - if (value.get_type()==Variant::OBJECT) { + if (value.get_type() == Variant::OBJECT) { //handle resources that are local to scene by duplicating them if needed Ref<Resource> res = value; if (res.is_valid()) { if (res->is_local_to_scene()) { - Map<Ref<Resource>,Ref<Resource> >::Element *E=resources_local_to_scene.find(res); + Map<Ref<Resource>, Ref<Resource> >::Element *E = resources_local_to_scene.find(res); if (E) { - value=E->get(); + value = E->get(); } else { - Node *base = i==0?node:ret_nodes[0]; + Node *base = i == 0 ? node : ret_nodes[0]; - if (p_edit_state==GEN_EDIT_STATE_MAIN) { + if (p_edit_state == GEN_EDIT_STATE_MAIN) { - res->local_scene=base; - resources_local_to_scene[res]=res; + res->local_scene = base; + resources_local_to_scene[res] = res; } else { - Node *base = i==0?node:ret_nodes[0]; - Ref<Resource> local_dupe = res->duplicate_for_local_scene(base,resources_local_to_scene); - resources_local_to_scene[res]=local_dupe; - res=local_dupe; - value=local_dupe; + Node *base = i == 0 ? node : ret_nodes[0]; + Ref<Resource> local_dupe = res->duplicate_for_local_scene(base, resources_local_to_scene); + resources_local_to_scene[res] = local_dupe; + res = local_dupe; + value = local_dupe; } res->setup_local_to_scene(); - } //must make a copy, because this res is local to scene } } } - node->set(snames[ nprops[j].name ],value,&valid); + node->set(snames[nprops[j].name], value, &valid); } } } @@ -262,60 +255,56 @@ Node *SceneState::instance(GenEditState p_edit_state) const { //name //groups - for(int j=0;j<n.groups.size();j++) { + for (int j = 0; j < n.groups.size(); j++) { - ERR_FAIL_INDEX_V( n.groups[j], sname_count, NULL ); - node->add_to_group( snames[ n.groups[j] ], true ); + ERR_FAIL_INDEX_V(n.groups[j], sname_count, NULL); + node->add_to_group(snames[n.groups[j]], true); } - if (n.instance>=0 || n.type!=TYPE_INSTANCED || i==0) { + if (n.instance >= 0 || n.type != TYPE_INSTANCED || i == 0) { //if node was not part of instance, must set it's name, parenthood and ownership - if (i>0) { + if (i > 0) { if (parent) { - parent->_add_child_nocheck(node,snames[n.name]); + parent->_add_child_nocheck(node, snames[n.name]); } else { //it may be possible that an instanced scene has changed //and the node has nowhere to go anymore stray_instances.push_back(node); //can't be added, go to stray list } } else { - node->_set_name_nocheck( snames[ n.name ] ); + node->_set_name_nocheck(snames[n.name]); } } - if (n.owner>=0) { + if (n.owner >= 0) { - NODE_FROM_ID(owner,n.owner); + NODE_FROM_ID(owner, n.owner); if (owner) node->_set_owner_nocheck(owner); } - - } - - ret_nodes[i]=node; + ret_nodes[i] = node; if (node && gen_node_path_cache && ret_nodes[0]) { NodePath n = ret_nodes[0]->get_path_to(node); - node_path_cache[n]=i; + node_path_cache[n] = i; } } - //do connections int cc = connections.size(); const ConnectionData *cdata = connections.ptr(); - for(int i=0;i<cc;i++) { + for (int i = 0; i < cc; i++) { - const ConnectionData &c=cdata[i]; + const ConnectionData &c = cdata[i]; //ERR_FAIL_INDEX_V( c.from, nc, NULL ); //ERR_FAIL_INDEX_V( c.to, nc, NULL ); - NODE_FROM_ID(cfrom,c.from); - NODE_FROM_ID(cto,c.to); + NODE_FROM_ID(cfrom, c.from); + NODE_FROM_ID(cto, c.to); if (!cfrom || !cto) continue; @@ -323,56 +312,52 @@ Node *SceneState::instance(GenEditState p_edit_state) const { Vector<Variant> binds; if (c.binds.size()) { binds.resize(c.binds.size()); - for(int j=0;j<c.binds.size();j++) - binds[j]=props[ c.binds[j] ]; + for (int j = 0; j < c.binds.size(); j++) + binds[j] = props[c.binds[j]]; } - - cfrom->connect( snames[ c.signal], cto, snames[ c.method], binds,CONNECT_PERSIST|c.flags ); + cfrom->connect(snames[c.signal], cto, snames[c.method], binds, CONNECT_PERSIST | c.flags); } //Node *s = ret_nodes[0]; //remove nodes that could not be added, likely as a result that - while(stray_instances.size()) { + while (stray_instances.size()) { memdelete(stray_instances.front()->get()); stray_instances.pop_front(); } - for(int i=0;i<editable_instances.size();i++) { + for (int i = 0; i < editable_instances.size(); i++) { Node *ei = ret_nodes[0]->_get_node(editable_instances[i]); if (ei) { - ret_nodes[0]->set_editable_instance(ei,true); + ret_nodes[0]->set_editable_instance(ei, true); } } return ret_nodes[0]; - } - -static int _nm_get_string(const String& p_string, Map<StringName,int> &name_map) { +static int _nm_get_string(const String &p_string, Map<StringName, int> &name_map) { if (name_map.has(p_string)) return name_map[p_string]; int idx = name_map.size(); - name_map[p_string]=idx; + name_map[p_string] = idx; return idx; } -static int _vm_get_variant(const Variant& p_variant, HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map) { +static int _vm_get_variant(const Variant &p_variant, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map) { if (variant_map.has(p_variant)) return variant_map[p_variant]; int idx = variant_map.size(); - variant_map[p_variant]=idx; + variant_map[p_variant] = idx; return idx; } -Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map) { - +Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map) { // this function handles all the work related to properly packing scenes, be it // instanced or inherited. @@ -380,18 +365,18 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S // document it. if you fail to understand something, please ask! //discard nodes that do not belong to be processed - if (p_node!=p_owner && p_node->get_owner()!=p_owner && !p_owner->is_editable_instance(p_node->get_owner())) + if (p_node != p_owner && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) return OK; // save the child instanced scenes that are chosen as editable, so they can be restored // upon load back - if (p_node!=p_owner && p_node->get_filename()!=String() && p_owner->is_editable_instance(p_node)) + if (p_node != p_owner && p_node->get_filename() != String() && p_owner->is_editable_instance(p_node)) editable_instances.push_back(p_owner->get_path_to(p_node)); NodeData nd; - nd.name=_nm_get_string(p_node->get_name(),name_map); - nd.instance=-1; //not instanced by default + nd.name = _nm_get_string(p_node->get_name(), name_map); + nd.instance = -1; //not instanced by default // if this node is part of an instanced scene or sub-instanced scene // we need to get the corresponding instance states. @@ -400,34 +385,34 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S List<PackState> pack_state_stack; - bool instanced_by_owner=true; + bool instanced_by_owner = true; { - Node *n=p_node; + Node *n = p_node; - while(n) { + while (n) { - if (n==p_owner) { + if (n == p_owner) { Ref<SceneState> state = n->get_scene_inherited_state(); if (state.is_valid()) { int node = state->find_node_by_path(n->get_path_to(p_node)); - if (node>=0) { + if (node >= 0) { //this one has state for this node, save PackState ps; - ps.node=node; - ps.state=state; + ps.node = node; + ps.state = state; pack_state_stack.push_back(ps); - instanced_by_owner=false; + instanced_by_owner = false; } } - if (p_node->get_filename()!=String() && p_node->get_owner()==p_owner && instanced_by_owner) { + if (p_node->get_filename() != String() && p_node->get_owner() == p_owner && instanced_by_owner) { if (p_node->get_scene_instance_load_placeholder()) { //it's a placeholder, use the placeholder path - nd.instance=_vm_get_variant(p_node->get_filename(),variant_map); - nd.instance|=FLAG_INSTANCE_IS_PLACEHOLDER; + nd.instance = _vm_get_variant(p_node->get_filename(), variant_map); + nd.instance |= FLAG_INSTANCE_IS_PLACEHOLDER; } else { //must instance ourselves Ref<PackedScene> instance = ResourceLoader::load(p_node->get_filename()); @@ -435,27 +420,26 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S return ERR_CANT_OPEN; } - nd.instance=_vm_get_variant(instance,variant_map); + nd.instance = _vm_get_variant(instance, variant_map); } } - n=NULL; + n = NULL; } else { - if (n->get_filename()!=String()) { + if (n->get_filename() != String()) { //is an instance Ref<SceneState> state = n->get_scene_instance_state(); if (state.is_valid()) { int node = state->find_node_by_path(n->get_path_to(p_node)); - if (node>=0) { + if (node >= 0) { //this one has state for this node, save PackState ps; - ps.node=node; - ps.state=state; + ps.node = node; + ps.state = state; pack_state_stack.push_back(ps); } } - } - n=n->get_owner(); + n = n->get_owner(); } } } @@ -520,16 +504,14 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S List<PropertyInfo> plist; p_node->get_property_list(&plist); - for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { - + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) { continue; } String name = E->get().name; - Variant value = p_node->get( E->get().name ); - + Variant value = p_node->get(E->get().name); bool isdefault = ((E->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO) && value.is_zero()) || ((E->get().usage & PROPERTY_USAGE_STORE_IF_NONONE) && value.is_one()); @@ -539,8 +521,6 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S } */ - - //print_line("PASSED!"); //print_line("at: "+String(p_node->get_name())+"::"+name+": - nz: "+itos(E->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO)+" no: "+itos(E->get().usage&PROPERTY_USAGE_STORE_IF_NONONE)); //print_line("value: "+String(value)+" is zero: "+itos(value.is_zero())+" is one" +itos(value.is_one())); @@ -551,37 +531,36 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S // only save what has been changed // only save changed properties in instance - if (E->get().usage & PROPERTY_USAGE_NO_INSTANCE_STATE || E->get().name=="__meta__") { + if (E->get().usage & PROPERTY_USAGE_NO_INSTANCE_STATE || E->get().name == "__meta__") { //property has requested that no instance state is saved, sorry //also, meta won't be overriden or saved continue; } - bool exists=false; + bool exists = false; Variant original; - for (List<PackState>::Element *F=pack_state_stack.back();F;F=F->prev()) { + for (List<PackState>::Element *F = pack_state_stack.back(); F; F = F->prev()) { //check all levels of pack to see if the property exists somewhere - const PackState &ps=F->get(); + const PackState &ps = F->get(); - original = ps.state->get_property_value(ps.node,E->get().name,exists); + original = ps.state->get_property_value(ps.node, E->get().name, exists); if (exists) { break; } } - if (exists) { //check if already exists and did not change - if (value.get_type()==Variant::REAL && original.get_type()==Variant::REAL) { + if (value.get_type() == Variant::REAL && original.get_type() == Variant::REAL) { //this must be done because, as some scenes save as text, there might be a tiny difference in floats due to numerical error float a = value; float b = original; - if (Math::abs(a-b)<CMP_EPSILON) + if (Math::abs(a - b) < CMP_EPSILON) continue; - } else if (bool(Variant::evaluate(Variant::OP_EQUAL,value,original))) { + } else if (bool(Variant::evaluate(Variant::OP_EQUAL, value, original))) { continue; } @@ -593,8 +572,7 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S continue; } - - } else { + } else { if (isdefault) { //it's the default value, no point in saving it @@ -603,20 +581,18 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S } NodeData::Property prop; - prop.name=_nm_get_string( name,name_map); - prop.value=_vm_get_variant( value, variant_map); + prop.name = _nm_get_string(name, name_map); + prop.value = _vm_get_variant(value, variant_map); nd.properties.push_back(prop); - } - // save the groups this node is into // discard groups that come from the original scene List<Node::GroupInfo> groups; p_node->get_groups(&groups); - for(List<Node::GroupInfo>::Element *E=groups.front();E;E=E->next()) { - Node::GroupInfo &gi=E->get(); + for (List<Node::GroupInfo>::Element *E = groups.front(); E; E = E->next()) { + Node::GroupInfo &gi = E->get(); if (!gi.persistent) continue; @@ -625,12 +601,12 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S continue; //group was instanced, don't add here */ - bool skip=false; - for (List<PackState>::Element *F=pack_state_stack.front();F;F=F->next()) { + bool skip = false; + for (List<PackState>::Element *F = pack_state_stack.front(); F; F = F->next()) { //check all levels of pack to see if the group was added somewhere - const PackState &ps=F->get(); - if (ps.state->is_node_in_group(ps.node,gi.name)) { - skip=true; + const PackState &ps = F->get(); + if (ps.state->is_node_in_group(ps.node, gi.name)) { + skip = true; break; } } @@ -638,24 +614,23 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S if (skip) continue; - nd.groups.push_back(_nm_get_string(gi.name,name_map)); + nd.groups.push_back(_nm_get_string(gi.name, name_map)); } - // save the right owner // for the saved scene root this is -1 // for nodes of the saved scene this is 0 // for nodes of instanced scenes this is >0 - if (p_node==p_owner) { + if (p_node == p_owner) { //saved scene root - nd.owner=-1; - } else if (p_node->get_owner()==p_owner) { + nd.owner = -1; + } else if (p_node->get_owner() == p_owner) { //part of saved scene - nd.owner=0; + nd.owner = 0; } else { - nd.owner=-1; + nd.owner = -1; #if 0 // this is pointless, if this was instanced by something else, // the owner will already be set. @@ -677,22 +652,19 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S } #endif - - } // Save the right type. If this node was created by an instance // then flag that the node should not be created but reused if (pack_state_stack.empty()) { //this node is not part of an instancing process, so save the type - nd.type=_nm_get_string(p_node->get_class(),name_map); + nd.type = _nm_get_string(p_node->get_class(), name_map); } else { // this node is part of an instanced process, so do not save the type. // instead, save that it was instanced - nd.type=TYPE_INSTANCED; + nd.type = TYPE_INSTANCED; } - // determine whether to save this node or not // if this node is part of an instanced sub-scene, we can skip storing it if basically // no properties changed and no groups were added to it. @@ -700,59 +672,54 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S // that hold changes bool save_node = nd.properties.size() || nd.groups.size(); // some local properties or groups exist - save_node = save_node || p_node==p_owner; // owner is always saved - save_node = save_node || (p_node->get_owner()==p_owner && instanced_by_owner); //part of scene and not instanced - + save_node = save_node || p_node == p_owner; // owner is always saved + save_node = save_node || (p_node->get_owner() == p_owner && instanced_by_owner); //part of scene and not instanced int idx = nodes.size(); - int parent_node=NO_PARENT_SAVED; + int parent_node = NO_PARENT_SAVED; if (save_node) { //don't save the node if nothing and subscene - node_map[p_node]=idx; + node_map[p_node] = idx; //ok validate parent node - if (p_parent_idx==NO_PARENT_SAVED) { + if (p_parent_idx == NO_PARENT_SAVED) { int sidx; if (nodepath_map.has(p_node->get_parent())) { - sidx=nodepath_map[p_node->get_parent()]; + sidx = nodepath_map[p_node->get_parent()]; } else { - sidx=nodepath_map.size(); - nodepath_map[p_node->get_parent()]=sidx; + sidx = nodepath_map.size(); + nodepath_map[p_node->get_parent()] = sidx; } - nd.parent=FLAG_ID_IS_PATH|sidx; + nd.parent = FLAG_ID_IS_PATH | sidx; } else { - nd.parent=p_parent_idx; + nd.parent = p_parent_idx; } - parent_node=idx; + parent_node = idx; nodes.push_back(nd); - } + for (int i = 0; i < p_node->get_child_count(); i++) { - for(int i=0;i<p_node->get_child_count();i++) { - - Node *c=p_node->get_child(i); - Error err = _parse_node(p_owner,c,parent_node,name_map,variant_map,node_map,nodepath_map); + Node *c = p_node->get_child(i); + Error err = _parse_node(p_owner, c, parent_node, name_map, variant_map, node_map, nodepath_map); if (err) return err; } return OK; - } -Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map) { +Error SceneState::_parse_connections(Node *p_owner, Node *p_node, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map) { - if (p_node!=p_owner && p_node->get_owner() && p_node->get_owner()!=p_owner && !p_owner->is_editable_instance(p_node->get_owner())) + if (p_node != p_owner && p_node->get_owner() && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) return OK; - List<MethodInfo> _signals; p_node->get_signal_list(&_signals); _signals.sort(); @@ -760,27 +727,24 @@ Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName, //ERR_FAIL_COND_V( !node_map.has(p_node), ERR_BUG); //NodeData &nd = nodes[node_map[p_node]]; - - for(List<MethodInfo>::Element *E=_signals.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = _signals.front(); E; E = E->next()) { List<Node::Connection> conns; - p_node->get_signal_connection_list(E->get().name,&conns); + p_node->get_signal_connection_list(E->get().name, &conns); conns.sort(); - for(List<Node::Connection>::Element *F=conns.front();F;F=F->next()) { + for (List<Node::Connection>::Element *F = conns.front(); F; F = F->next()) { const Node::Connection &c = F->get(); - if (!(c.flags&CONNECT_PERSIST)) //only persistent connections get saved + if (!(c.flags & CONNECT_PERSIST)) //only persistent connections get saved continue; // only connections that originate or end into main saved scene are saved // everything else is discarded - - Node *target=c.target->cast_to<Node>(); - + Node *target = c.target->cast_to<Node>(); if (!target) { continue; @@ -791,150 +755,139 @@ Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName, ERR_CONTINUE(!common_parent); - if (common_parent!=p_owner && common_parent->get_filename()==String()) { - common_parent=common_parent->get_owner(); + if (common_parent != p_owner && common_parent->get_filename() == String()) { + common_parent = common_parent->get_owner(); } - bool exists=false; + bool exists = false; //go through ownership chain to see if this exists - while(common_parent) { - - + while (common_parent) { Ref<SceneState> ps; - if (common_parent==p_owner) - ps=common_parent->get_scene_inherited_state(); + if (common_parent == p_owner) + ps = common_parent->get_scene_inherited_state(); else - ps=common_parent->get_scene_instance_state(); - + ps = common_parent->get_scene_instance_state(); if (ps.is_valid()) { NodePath signal_from = common_parent->get_path_to(p_node); NodePath signal_to = common_parent->get_path_to(target); - if (ps->has_connection(signal_from,c.signal,signal_to,c.method)) { - exists=true; + if (ps->has_connection(signal_from, c.signal, signal_to, c.method)) { + exists = true; break; } - } - if (common_parent==p_owner) + if (common_parent == p_owner) break; else - common_parent=common_parent->get_owner(); + common_parent = common_parent->get_owner(); } if (exists) { //already exists (comes from instance or inheritance), so don't save continue; } - - { - Node *nl=p_node; + Node *nl = p_node; - bool exists=false; + bool exists = false; - while(nl) { + while (nl) { - if (nl==p_owner) { + if (nl == p_owner) { Ref<SceneState> state = nl->get_scene_inherited_state(); if (state.is_valid()) { int from_node = state->find_node_by_path(nl->get_path_to(p_node)); int to_node = state->find_node_by_path(nl->get_path_to(target)); - if (from_node>=0 && to_node>=0) { + if (from_node >= 0 && to_node >= 0) { //this one has state for this node, save - if (state->is_connection(from_node,c.signal,to_node,c.method)) { - exists=true; + if (state->is_connection(from_node, c.signal, to_node, c.method)) { + exists = true; break; } } } - nl=NULL; + nl = NULL; } else { - if (nl->get_filename()!=String()) { + if (nl->get_filename() != String()) { //is an instance Ref<SceneState> state = nl->get_scene_instance_state(); if (state.is_valid()) { int from_node = state->find_node_by_path(nl->get_path_to(p_node)); int to_node = state->find_node_by_path(nl->get_path_to(target)); - if (from_node>=0 && to_node>=0) { + if (from_node >= 0 && to_node >= 0) { //this one has state for this node, save - if (state->is_connection(from_node,c.signal,to_node,c.method)) { - exists=true; + if (state->is_connection(from_node, c.signal, to_node, c.method)) { + exists = true; break; } } } - } - nl=nl->get_owner(); + nl = nl->get_owner(); } } if (exists) { continue; } - } - int src_id; if (node_map.has(p_node)) { - src_id=node_map[p_node]; + src_id = node_map[p_node]; } else { if (nodepath_map.has(p_node)) { - src_id=FLAG_ID_IS_PATH|nodepath_map[p_node]; + src_id = FLAG_ID_IS_PATH | nodepath_map[p_node]; } else { - int sidx=nodepath_map.size(); - nodepath_map[p_node]=sidx; - src_id=FLAG_ID_IS_PATH|sidx; + int sidx = nodepath_map.size(); + nodepath_map[p_node] = sidx; + src_id = FLAG_ID_IS_PATH | sidx; } } - - int target_id; if (node_map.has(target)) { - target_id=node_map[target]; + target_id = node_map[target]; } else { if (nodepath_map.has(target)) { - target_id=FLAG_ID_IS_PATH|nodepath_map[target]; + target_id = FLAG_ID_IS_PATH | nodepath_map[target]; } else { - int sidx=nodepath_map.size(); - nodepath_map[target]=sidx; - target_id=FLAG_ID_IS_PATH|sidx; + int sidx = nodepath_map.size(); + nodepath_map[target] = sidx; + target_id = FLAG_ID_IS_PATH | sidx; } } ConnectionData cd; - cd.from=src_id; - cd.to=target_id; - cd.method=_nm_get_string(c.method,name_map); - cd.signal=_nm_get_string(c.signal,name_map); - cd.flags=c.flags; - for(int i=0;i<c.binds.size();i++) { - - cd.binds.push_back( _vm_get_variant(c.binds[i],variant_map)); + cd.from = src_id; + cd.to = target_id; + cd.method = _nm_get_string(c.method, name_map); + cd.signal = _nm_get_string(c.signal, name_map); + cd.flags = c.flags; + for (int i = 0; i < c.binds.size(); i++) { + + cd.binds.push_back(_vm_get_variant(c.binds[i], variant_map)); } connections.push_back(cd); } } - for(int i=0;i<p_node->get_child_count();i++) { + for (int i = 0; i < p_node->get_child_count(); i++) { - Node *c=p_node->get_child(i); - Error err = _parse_connections(p_owner,c,name_map,variant_map,node_map,nodepath_map); + Node *c = p_node->get_child(i); + Error err = _parse_connections(p_owner, c, name_map, variant_map, node_map, nodepath_map); if (err) return err; } @@ -942,19 +895,17 @@ Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName, return OK; } - Error SceneState::pack(Node *p_scene) { - ERR_FAIL_NULL_V( p_scene, ERR_INVALID_PARAMETER ); - + ERR_FAIL_NULL_V(p_scene, ERR_INVALID_PARAMETER); clear(); Node *scene = p_scene; - Map<StringName,int> name_map; - HashMap<Variant,int,VariantHasher,VariantComparator> variant_map; - Map<Node*,int> node_map; - Map<Node*,int> nodepath_map; + Map<StringName, int> name_map; + HashMap<Variant, int, VariantHasher, VariantComparator> variant_map; + Map<Node *, int> node_map; + Map<Node *, int> nodepath_map; //if using scene inheritance, pack the scene it inherits from if (scene->get_scene_inherited_state().is_valid()) { @@ -962,19 +913,18 @@ Error SceneState::pack(Node *p_scene) { Ref<PackedScene> instance = ResourceLoader::load(path); if (instance.is_valid()) { - base_scene_idx=_vm_get_variant(instance,variant_map); + base_scene_idx = _vm_get_variant(instance, variant_map); } } //instanced, only direct sub-scnes are supported of course - - Error err = _parse_node(scene,scene,-1,name_map,variant_map,node_map,nodepath_map); + Error err = _parse_node(scene, scene, -1, name_map, variant_map, node_map, nodepath_map); if (err) { clear(); ERR_FAIL_V(err); } - err = _parse_connections(scene,scene,name_map,variant_map,node_map,nodepath_map); + err = _parse_connections(scene, scene, name_map, variant_map, node_map, nodepath_map); if (err) { clear(); ERR_FAIL_V(err); @@ -982,35 +932,34 @@ Error SceneState::pack(Node *p_scene) { names.resize(name_map.size()); - for(Map<StringName,int>::Element *E=name_map.front();E;E=E->next()) { + for (Map<StringName, int>::Element *E = name_map.front(); E; E = E->next()) { - names[E->get()]=E->key(); + names[E->get()] = E->key(); } variants.resize(variant_map.size()); - const Variant *K=NULL; - while((K=variant_map.next(K))) { + const Variant *K = NULL; + while ((K = variant_map.next(K))) { int idx = variant_map[*K]; - variants[idx]=*K; + variants[idx] = *K; } node_paths.resize(nodepath_map.size()); - for(Map<Node*,int>::Element *E=nodepath_map.front();E;E=E->next()) { + for (Map<Node *, int>::Element *E = nodepath_map.front(); E; E = E->next()) { - node_paths[E->get()]=scene->get_path_to(E->key()); + node_paths[E->get()] = scene->get_path_to(E->key()); } - return OK; } void SceneState::set_path(const String &p_path) { - path=p_path; + path = p_path; } -String SceneState::get_path() const{ +String SceneState::get_path() const { return path; } @@ -1024,13 +973,12 @@ void SceneState::clear() { node_path_cache.clear(); node_paths.clear(); editable_instances.clear(); - base_scene_idx=-1; - + base_scene_idx = -1; } Ref<SceneState> SceneState::_get_base_scene_state() const { - if (base_scene_idx>=0) { + if (base_scene_idx >= 0) { Ref<PackedScene> ps = variants[base_scene_idx]; if (ps.is_valid()) { @@ -1041,15 +989,15 @@ Ref<SceneState> SceneState::_get_base_scene_state() const { return Ref<SceneState>(); } -int SceneState::find_node_by_path(const NodePath& p_node) const { +int SceneState::find_node_by_path(const NodePath &p_node) const { if (!node_path_cache.has(p_node)) { if (_get_base_scene_state().is_valid()) { int idx = _get_base_scene_state()->find_node_by_path(p_node); - if (idx>=0) { + if (idx >= 0) { if (!base_scene_node_remap.has(idx)) { int ridx = nodes.size() + base_scene_node_remap.size(); - base_scene_node_remap[ridx]=idx; + base_scene_node_remap[ridx] = idx; } return base_scene_node_remap[idx]; @@ -1065,27 +1013,26 @@ int SceneState::find_node_by_path(const NodePath& p_node) const { //the node in the instanced scene, as a property may be missing //from the local one int idx = _get_base_scene_state()->find_node_by_path(p_node); - base_scene_node_remap[nid]=idx; - + base_scene_node_remap[nid] = idx; } return nid; } -Variant SceneState::get_property_value(int p_node, const StringName& p_property, bool &found) const { +Variant SceneState::get_property_value(int p_node, const StringName &p_property, bool &found) const { - found=false; + found = false; - ERR_FAIL_COND_V(p_node<0,Variant()); + ERR_FAIL_COND_V(p_node < 0, Variant()); - if (p_node<nodes.size()) { + if (p_node < nodes.size()) { //find in built-in nodes int pc = nodes[p_node].properties.size(); - const StringName* namep = names.ptr(); + const StringName *namep = names.ptr(); - const NodeData::Property *p=nodes[p_node].properties.ptr(); - for(int i=0;i<pc;i++) { - if (p_property==namep[p[i].name]) { - found=true; + const NodeData::Property *p = nodes[p_node].properties.ptr(); + for (int i = 0; i < pc; i++) { + if (p_property == namep[p[i].name]) { + found = true; return variants[p[i].value]; } } @@ -1094,61 +1041,61 @@ Variant SceneState::get_property_value(int p_node, const StringName& p_property, //property not found, try on instance if (base_scene_node_remap.has(p_node)) { - return _get_base_scene_state()->get_property_value(base_scene_node_remap[p_node],p_property,found); + return _get_base_scene_state()->get_property_value(base_scene_node_remap[p_node], p_property, found); } return Variant(); } -bool SceneState::is_node_in_group(int p_node,const StringName& p_group) const { +bool SceneState::is_node_in_group(int p_node, const StringName &p_group) const { - ERR_FAIL_COND_V(p_node<0,false); + ERR_FAIL_COND_V(p_node < 0, false); - if (p_node<nodes.size()) { - const StringName* namep = names.ptr(); - for(int i=0;i<nodes[p_node].groups.size();i++) { - if (namep[nodes[p_node].groups[i]]==p_group) + if (p_node < nodes.size()) { + const StringName *namep = names.ptr(); + for (int i = 0; i < nodes[p_node].groups.size(); i++) { + if (namep[nodes[p_node].groups[i]] == p_group) return true; } } if (base_scene_node_remap.has(p_node)) { - return _get_base_scene_state()->is_node_in_group(base_scene_node_remap[p_node],p_group); + return _get_base_scene_state()->is_node_in_group(base_scene_node_remap[p_node], p_group); } return false; } -bool SceneState::disable_placeholders=false; +bool SceneState::disable_placeholders = false; void SceneState::set_disable_placeholders(bool p_disable) { - disable_placeholders=p_disable; + disable_placeholders = p_disable; } -bool SceneState::is_connection(int p_node,const StringName& p_signal,int p_to_node,const StringName& p_to_method) const { +bool SceneState::is_connection(int p_node, const StringName &p_signal, int p_to_node, const StringName &p_to_method) const { - ERR_FAIL_COND_V(p_node<0,false); - ERR_FAIL_COND_V(p_to_node<0,false); + ERR_FAIL_COND_V(p_node < 0, false); + ERR_FAIL_COND_V(p_to_node < 0, false); - if (p_node<nodes.size() && p_to_node<nodes.size()) { + if (p_node < nodes.size() && p_to_node < nodes.size()) { - int signal_idx=-1; - int method_idx=-1; - for(int i=0;i<names.size();i++) { - if (names[i]==p_signal) { - signal_idx=i; - } else if (names[i]==p_to_method) { - method_idx=i; + int signal_idx = -1; + int method_idx = -1; + for (int i = 0; i < names.size(); i++) { + if (names[i] == p_signal) { + signal_idx = i; + } else if (names[i] == p_to_method) { + method_idx = i; } } - if (signal_idx>=0 && method_idx>=0) { + if (signal_idx >= 0 && method_idx >= 0) { //signal and method strings are stored.. - for(int i=0;i<connections.size();i++) { + for (int i = 0; i < connections.size(); i++) { - if (connections[i].from==p_node && connections[i].to==p_to_node && connections[i].signal==signal_idx && connections[i].method==method_idx) { + if (connections[i].from == p_node && connections[i].to == p_to_node && connections[i].signal == signal_idx && connections[i].method == method_idx) { return true; } @@ -1157,30 +1104,27 @@ bool SceneState::is_connection(int p_node,const StringName& p_signal,int p_to_no } if (base_scene_node_remap.has(p_node) && base_scene_node_remap.has(p_to_node)) { - return _get_base_scene_state()->is_connection(base_scene_node_remap[p_node],p_signal,base_scene_node_remap[p_to_node],p_to_method); + return _get_base_scene_state()->is_connection(base_scene_node_remap[p_node], p_signal, base_scene_node_remap[p_to_node], p_to_method); } return false; - } +void SceneState::set_bundled_scene(const Dictionary &d) { -void SceneState::set_bundled_scene(const Dictionary& d) { - - - ERR_FAIL_COND( !d.has("names")); - ERR_FAIL_COND( !d.has("variants")); - ERR_FAIL_COND( !d.has("node_count")); - ERR_FAIL_COND( !d.has("nodes")); - ERR_FAIL_COND( !d.has("conn_count")); - ERR_FAIL_COND( !d.has("conns")); + ERR_FAIL_COND(!d.has("names")); + ERR_FAIL_COND(!d.has("variants")); + ERR_FAIL_COND(!d.has("node_count")); + ERR_FAIL_COND(!d.has("nodes")); + ERR_FAIL_COND(!d.has("conn_count")); + ERR_FAIL_COND(!d.has("conns")); //ERR_FAIL_COND( !d.has("path")); - int version=1; + int version = 1; if (d.has("version")) - version=d["version"]; + version = d["version"]; - if (version>PACK_VERSION) { + if (version > PACK_VERSION) { ERR_EXPLAIN("Save format version too new!"); ERR_FAIL(); } @@ -1190,19 +1134,19 @@ void SceneState::set_bundled_scene(const Dictionary& d) { int namecount = snames.size(); names.resize(namecount); - PoolVector<String>::Read r =snames.read(); - for(int i=0;i<names.size();i++) - names[i]=r[i]; + PoolVector<String>::Read r = snames.read(); + for (int i = 0; i < names.size(); i++) + names[i] = r[i]; } Array svariants = d["variants"]; if (svariants.size()) { - int varcount=svariants.size(); + int varcount = svariants.size(); variants.resize(varcount); - for(int i=0;i<varcount;i++) { + for (int i = 0; i < varcount; i++) { - variants[i]=svariants[i]; + variants[i] = svariants[i]; } } else { @@ -1210,83 +1154,80 @@ void SceneState::set_bundled_scene(const Dictionary& d) { } nodes.resize(d["node_count"]); - int nc=nodes.size(); + int nc = nodes.size(); if (nc) { PoolVector<int> snodes = d["nodes"]; PoolVector<int>::Read r = snodes.read(); - int idx=0; - for(int i=0;i<nc;i++) { + int idx = 0; + for (int i = 0; i < nc; i++) { NodeData &nd = nodes[i]; - nd.parent=r[idx++]; - nd.owner=r[idx++]; - nd.type=r[idx++]; - nd.name=r[idx++]; - nd.instance=r[idx++]; + nd.parent = r[idx++]; + nd.owner = r[idx++]; + nd.type = r[idx++]; + nd.name = r[idx++]; + nd.instance = r[idx++]; nd.properties.resize(r[idx++]); - for(int j=0;j<nd.properties.size();j++) { + for (int j = 0; j < nd.properties.size(); j++) { - nd.properties[j].name=r[idx++]; - nd.properties[j].value=r[idx++]; + nd.properties[j].name = r[idx++]; + nd.properties[j].value = r[idx++]; } nd.groups.resize(r[idx++]); - for(int j=0;j<nd.groups.size();j++) { + for (int j = 0; j < nd.groups.size(); j++) { - nd.groups[j]=r[idx++]; + nd.groups[j] = r[idx++]; } } - } connections.resize(d["conn_count"]); - int cc=connections.size(); + int cc = connections.size(); if (cc) { PoolVector<int> sconns = d["conns"]; PoolVector<int>::Read r = sconns.read(); - int idx=0; - for(int i=0;i<cc;i++) { + int idx = 0; + for (int i = 0; i < cc; i++) { ConnectionData &cd = connections[i]; - cd.from=r[idx++]; - cd.to=r[idx++]; - cd.signal=r[idx++]; - cd.method=r[idx++]; - cd.flags=r[idx++]; + cd.from = r[idx++]; + cd.to = r[idx++]; + cd.signal = r[idx++]; + cd.method = r[idx++]; + cd.flags = r[idx++]; cd.binds.resize(r[idx++]); - for(int j=0;j<cd.binds.size();j++) { + for (int j = 0; j < cd.binds.size(); j++) { - cd.binds[j]=r[idx++]; + cd.binds[j] = r[idx++]; } } - } Array np; if (d.has("node_paths")) { - np=d["node_paths"]; + np = d["node_paths"]; } node_paths.resize(np.size()); - for(int i=0;i<np.size();i++) { - node_paths[i]=np[i]; + for (int i = 0; i < np.size(); i++) { + node_paths[i] = np[i]; } Array ei; if (d.has("editable_instances")) { - ei=d["editable_instances"]; + ei = d["editable_instances"]; } if (d.has("base_scene")) { - base_scene_idx=d["base_scene"]; + base_scene_idx = d["base_scene"]; } editable_instances.resize(ei.size()); - for(int i=0;i<editable_instances.size();i++) { - editable_instances[i]=ei[i]; + for (int i = 0; i < editable_instances.size(); i++) { + editable_instances[i] = ei[i]; } //path=d["path"]; - } Dictionary SceneState::get_bundled_scene() const { @@ -1296,85 +1237,82 @@ Dictionary SceneState::get_bundled_scene() const { if (names.size()) { - PoolVector<String>::Write r=rnames.write(); + PoolVector<String>::Write r = rnames.write(); - for(int i=0;i<names.size();i++) - r[i]=names[i]; + for (int i = 0; i < names.size(); i++) + r[i] = names[i]; } Dictionary d; - d["names"]=rnames; - d["variants"]=variants; + d["names"] = rnames; + d["variants"] = variants; Vector<int> rnodes; - d["node_count"]=nodes.size(); + d["node_count"] = nodes.size(); - for(int i=0;i<nodes.size();i++) { + for (int i = 0; i < nodes.size(); i++) { - const NodeData &nd=nodes[i]; + const NodeData &nd = nodes[i]; rnodes.push_back(nd.parent); rnodes.push_back(nd.owner); rnodes.push_back(nd.type); rnodes.push_back(nd.name); rnodes.push_back(nd.instance); rnodes.push_back(nd.properties.size()); - for(int j=0;j<nd.properties.size();j++) { + for (int j = 0; j < nd.properties.size(); j++) { rnodes.push_back(nd.properties[j].name); rnodes.push_back(nd.properties[j].value); } rnodes.push_back(nd.groups.size()); - for(int j=0;j<nd.groups.size();j++) { + for (int j = 0; j < nd.groups.size(); j++) { rnodes.push_back(nd.groups[j]); } } - d["nodes"]=rnodes; + d["nodes"] = rnodes; Vector<int> rconns; - d["conn_count"]=connections.size(); + d["conn_count"] = connections.size(); - for(int i=0;i<connections.size();i++) { + for (int i = 0; i < connections.size(); i++) { - const ConnectionData &cd=connections[i]; + const ConnectionData &cd = connections[i]; rconns.push_back(cd.from); rconns.push_back(cd.to); rconns.push_back(cd.signal); rconns.push_back(cd.method); rconns.push_back(cd.flags); rconns.push_back(cd.binds.size()); - for(int j=0;j<cd.binds.size();j++) + for (int j = 0; j < cd.binds.size(); j++) rconns.push_back(cd.binds[j]); - } - d["conns"]=rconns; + d["conns"] = rconns; Array rnode_paths; rnode_paths.resize(node_paths.size()); - for(int i=0;i<node_paths.size();i++) { - rnode_paths[i]=node_paths[i]; + for (int i = 0; i < node_paths.size(); i++) { + rnode_paths[i] = node_paths[i]; } - d["node_paths"]=rnode_paths; + d["node_paths"] = rnode_paths; Array reditable_instances; reditable_instances.resize(editable_instances.size()); - for(int i=0;i<editable_instances.size();i++) { - reditable_instances[i]=editable_instances[i]; + for (int i = 0; i < editable_instances.size(); i++) { + reditable_instances[i] = editable_instances[i]; } - d["editable_instances"]=reditable_instances; - if (base_scene_idx>=0) { - d["base_scene"]=base_scene_idx; + d["editable_instances"] = reditable_instances; + if (base_scene_idx >= 0) { + d["base_scene"] = base_scene_idx; } - d["version"]=PACK_VERSION; + d["version"] = PACK_VERSION; //d["path"]=path; return d; - - } int SceneState::get_node_count() const { @@ -1384,76 +1322,68 @@ int SceneState::get_node_count() const { StringName SceneState::get_node_type(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),StringName()); - if (nodes[p_idx].type==TYPE_INSTANCED) + ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName()); + if (nodes[p_idx].type == TYPE_INSTANCED) return StringName(); return names[nodes[p_idx].type]; } StringName SceneState::get_node_name(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),StringName()); + ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName()); return names[nodes[p_idx].name]; } - bool SceneState::is_node_instance_placeholder(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),false); - - return nodes[p_idx].instance>=0 && nodes[p_idx].instance&FLAG_INSTANCE_IS_PLACEHOLDER; + ERR_FAIL_INDEX_V(p_idx, nodes.size(), false); + return nodes[p_idx].instance >= 0 && nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER; } Ref<PackedScene> SceneState::get_node_instance(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),Ref<PackedScene>()); + ERR_FAIL_INDEX_V(p_idx, nodes.size(), Ref<PackedScene>()); - if (nodes[p_idx].instance>=0) { - if (nodes[p_idx].instance&FLAG_INSTANCE_IS_PLACEHOLDER) + if (nodes[p_idx].instance >= 0) { + if (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER) return Ref<PackedScene>(); else - return variants[nodes[p_idx].instance&FLAG_MASK]; - } else if (nodes[p_idx].parent<0 || nodes[p_idx].parent==NO_PARENT_SAVED) { + return variants[nodes[p_idx].instance & FLAG_MASK]; + } else if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) { - if (base_scene_idx>=0) { + if (base_scene_idx >= 0) { return variants[base_scene_idx]; } } - - return Ref<PackedScene>(); - - } String SceneState::get_node_instance_placeholder(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),String()); + ERR_FAIL_INDEX_V(p_idx, nodes.size(), String()); - if (nodes[p_idx].instance>=0 && nodes[p_idx].instance&FLAG_INSTANCE_IS_PLACEHOLDER) { - return variants[nodes[p_idx].instance&FLAG_MASK]; + if (nodes[p_idx].instance >= 0 && nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER) { + return variants[nodes[p_idx].instance & FLAG_MASK]; } return String(); - } -Vector<StringName> SceneState::get_node_groups(int p_idx) const{ - ERR_FAIL_INDEX_V(p_idx,nodes.size(),Vector<StringName>()); +Vector<StringName> SceneState::get_node_groups(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, nodes.size(), Vector<StringName>()); Vector<StringName> groups; - for(int i=0;i<nodes[p_idx].groups.size();i++) { + for (int i = 0; i < nodes[p_idx].groups.size(); i++) { groups.push_back(names[nodes[p_idx].groups[i]]); } return groups; } +NodePath SceneState::get_node_path(int p_idx, bool p_for_parent) const { -NodePath SceneState::get_node_path(int p_idx,bool p_for_parent) const { + ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath()); - ERR_FAIL_INDEX_V(p_idx,nodes.size(),NodePath()); - - if (nodes[p_idx].parent<0 || nodes[p_idx].parent==NO_PARENT_SAVED) { + if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) { if (p_for_parent) { return NodePath(); } else { @@ -1463,67 +1393,63 @@ NodePath SceneState::get_node_path(int p_idx,bool p_for_parent) const { Vector<StringName> sub_path; NodePath base_path; - int nidx=p_idx; - while(true) { - if (nodes[nidx].parent==NO_PARENT_SAVED || nodes[nidx].parent<0) { + int nidx = p_idx; + while (true) { + if (nodes[nidx].parent == NO_PARENT_SAVED || nodes[nidx].parent < 0) { - sub_path.insert(0,"."); + sub_path.insert(0, "."); break; } - if (!p_for_parent || p_idx!=nidx) { - sub_path.insert(0,names[nodes[nidx].name]); + if (!p_for_parent || p_idx != nidx) { + sub_path.insert(0, names[nodes[nidx].name]); } - if (nodes[nidx].parent&FLAG_ID_IS_PATH) { - base_path=node_paths[nodes[nidx].parent&FLAG_MASK]; + if (nodes[nidx].parent & FLAG_ID_IS_PATH) { + base_path = node_paths[nodes[nidx].parent & FLAG_MASK]; break; } else { - nidx=nodes[nidx].parent&FLAG_MASK; + nidx = nodes[nidx].parent & FLAG_MASK; } } - for(int i=base_path.get_name_count()-1;i>=0;i--) { - sub_path.insert(0,base_path.get_name(i)); + for (int i = base_path.get_name_count() - 1; i >= 0; i--) { + sub_path.insert(0, base_path.get_name(i)); } if (sub_path.empty()) { return NodePath("."); } - return NodePath(sub_path,false); - + return NodePath(sub_path, false); } int SceneState::get_node_property_count(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),-1); + ERR_FAIL_INDEX_V(p_idx, nodes.size(), -1); return nodes[p_idx].properties.size(); - } -StringName SceneState::get_node_property_name(int p_idx,int p_prop) const{ - ERR_FAIL_INDEX_V(p_idx,nodes.size(),StringName()); - ERR_FAIL_INDEX_V(p_prop,nodes[p_idx].properties.size(),StringName()); +StringName SceneState::get_node_property_name(int p_idx, int p_prop) const { + ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName()); + ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), StringName()); return names[nodes[p_idx].properties[p_prop].name]; - } -Variant SceneState::get_node_property_value(int p_idx,int p_prop) const{ - ERR_FAIL_INDEX_V(p_idx,nodes.size(),Variant()); - ERR_FAIL_INDEX_V(p_prop,nodes[p_idx].properties.size(),Variant()); +Variant SceneState::get_node_property_value(int p_idx, int p_prop) const { + ERR_FAIL_INDEX_V(p_idx, nodes.size(), Variant()); + ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), Variant()); return variants[nodes[p_idx].properties[p_prop].value]; } - NodePath SceneState::get_node_owner_path(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,nodes.size(),NodePath()); - if (nodes[p_idx].owner<0 || nodes[p_idx].owner==NO_PARENT_SAVED) + ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath()); + if (nodes[p_idx].owner < 0 || nodes[p_idx].owner == NO_PARENT_SAVED) return NodePath(); //root likely - if (nodes[p_idx].owner&FLAG_ID_IS_PATH) { - return node_paths[nodes[p_idx].owner&FLAG_MASK]; + if (nodes[p_idx].owner & FLAG_ID_IS_PATH) { + return node_paths[nodes[p_idx].owner & FLAG_MASK]; } else { - return get_node_path(nodes[p_idx].owner&FLAG_MASK); + return get_node_path(nodes[p_idx].owner & FLAG_MASK); } } @@ -1531,82 +1457,77 @@ int SceneState::get_connection_count() const { return connections.size(); } -NodePath SceneState::get_connection_source(int p_idx) const{ +NodePath SceneState::get_connection_source(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,connections.size(),NodePath()); - if (connections[p_idx].from&FLAG_ID_IS_PATH) { - return node_paths[connections[p_idx].from&FLAG_MASK]; + ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath()); + if (connections[p_idx].from & FLAG_ID_IS_PATH) { + return node_paths[connections[p_idx].from & FLAG_MASK]; } else { - return get_node_path(connections[p_idx].from&FLAG_MASK); + return get_node_path(connections[p_idx].from & FLAG_MASK); } - } -StringName SceneState::get_connection_signal(int p_idx) const{ +StringName SceneState::get_connection_signal(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,connections.size(),StringName()); + ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName()); return names[connections[p_idx].signal]; - } -NodePath SceneState::get_connection_target(int p_idx) const{ +NodePath SceneState::get_connection_target(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,connections.size(),NodePath()); - if (connections[p_idx].to&FLAG_ID_IS_PATH) { - return node_paths[connections[p_idx].to&FLAG_MASK]; + ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath()); + if (connections[p_idx].to & FLAG_ID_IS_PATH) { + return node_paths[connections[p_idx].to & FLAG_MASK]; } else { - return get_node_path(connections[p_idx].to&FLAG_MASK); + return get_node_path(connections[p_idx].to & FLAG_MASK); } - } -StringName SceneState::get_connection_method(int p_idx) const{ +StringName SceneState::get_connection_method(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,connections.size(),StringName()); + ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName()); return names[connections[p_idx].method]; - } +int SceneState::get_connection_flags(int p_idx) const { -int SceneState::get_connection_flags(int p_idx) const{ - - ERR_FAIL_INDEX_V(p_idx,connections.size(),-1); + ERR_FAIL_INDEX_V(p_idx, connections.size(), -1); return connections[p_idx].flags; } Array SceneState::get_connection_binds(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,connections.size(),Array()); + ERR_FAIL_INDEX_V(p_idx, connections.size(), Array()); Array binds; - for(int i=0;i<connections[p_idx].binds.size();i++) { + for (int i = 0; i < connections[p_idx].binds.size(); i++) { binds.push_back(variants[connections[p_idx].binds[i]]); } return binds; } -bool SceneState::has_connection(const NodePath& p_node_from, const StringName& p_signal, const NodePath& p_node_to, const StringName& p_method) const { +bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method) const { - for(int i=0;i<connections.size();i++) { + for (int i = 0; i < connections.size(); i++) { const ConnectionData &c = connections[i]; NodePath np_from; - if (c.from&FLAG_ID_IS_PATH) { - np_from=node_paths[c.from&FLAG_MASK]; + if (c.from & FLAG_ID_IS_PATH) { + np_from = node_paths[c.from & FLAG_MASK]; } else { - np_from=get_node_path(c.from); + np_from = get_node_path(c.from); } NodePath np_to; - if (c.to&FLAG_ID_IS_PATH) { - np_to=node_paths[c.to&FLAG_MASK]; + if (c.to & FLAG_ID_IS_PATH) { + np_to = node_paths[c.to & FLAG_MASK]; } else { - np_to=get_node_path(c.to); + np_to = get_node_path(c.to); } - StringName sn_signal=names[c.signal]; - StringName sn_method=names[c.method]; + StringName sn_signal = names[c.signal]; + StringName sn_method = names[c.method]; - if (np_from==p_node_from && sn_signal==p_signal && np_to==p_node_to && sn_method==p_method) { + if (np_from == p_node_from && sn_signal == p_signal && np_to == p_node_to && sn_method == p_method) { return true; } } @@ -1619,88 +1540,86 @@ Vector<NodePath> SceneState::get_editable_instances() const { } //add -int SceneState::add_name(const StringName& p_name) { +int SceneState::add_name(const StringName &p_name) { names.push_back(p_name); - return names.size()-1; + return names.size() - 1; } -int SceneState::find_name(const StringName& p_name) const { +int SceneState::find_name(const StringName &p_name) const { - for(int i=0;i<names.size();i++) { - if (names[i]==p_name) + for (int i = 0; i < names.size(); i++) { + if (names[i] == p_name) return i; } return -1; } -int SceneState::add_value(const Variant& p_value) { +int SceneState::add_value(const Variant &p_value) { variants.push_back(p_value); - return variants.size()-1; + return variants.size() - 1; } -int SceneState::add_node_path(const NodePath& p_path){ +int SceneState::add_node_path(const NodePath &p_path) { node_paths.push_back(p_path); - return (node_paths.size()-1)|FLAG_ID_IS_PATH; + return (node_paths.size() - 1) | FLAG_ID_IS_PATH; } -int SceneState::add_node(int p_parent,int p_owner,int p_type,int p_name, int p_instance){ +int SceneState::add_node(int p_parent, int p_owner, int p_type, int p_name, int p_instance) { NodeData nd; - nd.parent=p_parent; - nd.owner=p_owner; - nd.type=p_type; - nd.name=p_name; - nd.instance=p_instance; + nd.parent = p_parent; + nd.owner = p_owner; + nd.type = p_type; + nd.name = p_name; + nd.instance = p_instance; nodes.push_back(nd); - return nodes.size()-1; + return nodes.size() - 1; } -void SceneState::add_node_property(int p_node,int p_name,int p_value){ +void SceneState::add_node_property(int p_node, int p_name, int p_value) { - ERR_FAIL_INDEX(p_node,nodes.size()); - ERR_FAIL_INDEX(p_name,names.size()); - ERR_FAIL_INDEX(p_value,variants.size()); + ERR_FAIL_INDEX(p_node, nodes.size()); + ERR_FAIL_INDEX(p_name, names.size()); + ERR_FAIL_INDEX(p_value, variants.size()); NodeData::Property prop; - prop.name=p_name; - prop.value=p_value; + prop.name = p_name; + prop.value = p_value; nodes[p_node].properties.push_back(prop); } -void SceneState::add_node_group(int p_node,int p_group){ +void SceneState::add_node_group(int p_node, int p_group) { - ERR_FAIL_INDEX(p_node,nodes.size()); - ERR_FAIL_INDEX(p_group,names.size()); + ERR_FAIL_INDEX(p_node, nodes.size()); + ERR_FAIL_INDEX(p_group, names.size()); nodes[p_node].groups.push_back(p_group); - } -void SceneState::set_base_scene(int p_idx){ +void SceneState::set_base_scene(int p_idx) { - ERR_FAIL_INDEX(p_idx,variants.size()); - base_scene_idx=p_idx; + ERR_FAIL_INDEX(p_idx, variants.size()); + base_scene_idx = p_idx; } -void SceneState::add_connection(int p_from,int p_to, int p_signal, int p_method, int p_flags,const Vector<int>& p_binds){ +void SceneState::add_connection(int p_from, int p_to, int p_signal, int p_method, int p_flags, const Vector<int> &p_binds) { - ERR_FAIL_INDEX(p_signal,names.size()); - ERR_FAIL_INDEX(p_method,names.size()); + ERR_FAIL_INDEX(p_signal, names.size()); + ERR_FAIL_INDEX(p_method, names.size()); - for(int i=0;i<p_binds.size();i++) { - ERR_FAIL_INDEX(p_binds[i],variants.size()); + for (int i = 0; i < p_binds.size(); i++) { + ERR_FAIL_INDEX(p_binds[i], variants.size()); } ConnectionData c; - c.from=p_from; - c.to=p_to; - c.signal=p_signal; - c.method=p_method; - c.flags=p_flags; - c.binds=p_binds; + c.from = p_from; + c.to = p_to; + c.signal = p_signal; + c.method = p_method; + c.flags = p_flags; + c.binds = p_binds; connections.push_back(c); - } -void SceneState::add_editable_instance(const NodePath& p_path){ +void SceneState::add_editable_instance(const NodePath &p_path) { editable_instances.push_back(p_path); } @@ -1710,7 +1629,7 @@ PoolVector<String> SceneState::_get_node_groups(int p_idx) const { Vector<StringName> groups = get_node_groups(p_idx); PoolVector<String> ret; - for(int i=0;i<groups.size();i++) + for (int i = 0; i < groups.size(); i++) ret.push_back(groups[i]); return ret; @@ -1720,43 +1639,40 @@ void SceneState::_bind_methods() { //unbuild API - ClassDB::bind_method(D_METHOD("get_node_count"),&SceneState::get_node_count); - ClassDB::bind_method(D_METHOD("get_node_type","idx"),&SceneState::get_node_type); - ClassDB::bind_method(D_METHOD("get_node_name","idx"),&SceneState::get_node_name); - ClassDB::bind_method(D_METHOD("get_node_path","idx","for_parent"),&SceneState::get_node_path,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("get_node_owner_path","idx"),&SceneState::get_node_owner_path); - ClassDB::bind_method(D_METHOD("is_node_instance_placeholder","idx"),&SceneState::is_node_instance_placeholder); - ClassDB::bind_method(D_METHOD("get_node_instance_placeholder","idx"),&SceneState::get_node_instance_placeholder); - ClassDB::bind_method(D_METHOD("get_node_instance:PackedScene","idx"),&SceneState::get_node_instance); - ClassDB::bind_method(D_METHOD("get_node_groups","idx"),&SceneState::_get_node_groups); - ClassDB::bind_method(D_METHOD("get_node_property_count","idx"),&SceneState::get_node_property_count); - ClassDB::bind_method(D_METHOD("get_node_property_name","idx","prop_idx"),&SceneState::get_node_property_name); - ClassDB::bind_method(D_METHOD("get_node_property_value","idx","prop_idx"),&SceneState::get_node_property_value); - ClassDB::bind_method(D_METHOD("get_connection_count"),&SceneState::get_connection_count); - ClassDB::bind_method(D_METHOD("get_connection_source","idx"),&SceneState::get_connection_source); - ClassDB::bind_method(D_METHOD("get_connection_signal","idx"),&SceneState::get_connection_signal); - ClassDB::bind_method(D_METHOD("get_connection_target","idx"),&SceneState::get_connection_target); - ClassDB::bind_method(D_METHOD("get_connection_method","idx"),&SceneState::get_connection_method); - ClassDB::bind_method(D_METHOD("get_connection_flags","idx"),&SceneState::get_connection_flags); - ClassDB::bind_method(D_METHOD("get_connection_binds","idx"),&SceneState::get_connection_binds); - - BIND_CONSTANT( GEN_EDIT_STATE_DISABLED ); - BIND_CONSTANT( GEN_EDIT_STATE_INSTANCE ); - BIND_CONSTANT( GEN_EDIT_STATE_MAIN ); + ClassDB::bind_method(D_METHOD("get_node_count"), &SceneState::get_node_count); + ClassDB::bind_method(D_METHOD("get_node_type", "idx"), &SceneState::get_node_type); + ClassDB::bind_method(D_METHOD("get_node_name", "idx"), &SceneState::get_node_name); + ClassDB::bind_method(D_METHOD("get_node_path", "idx", "for_parent"), &SceneState::get_node_path, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("get_node_owner_path", "idx"), &SceneState::get_node_owner_path); + ClassDB::bind_method(D_METHOD("is_node_instance_placeholder", "idx"), &SceneState::is_node_instance_placeholder); + ClassDB::bind_method(D_METHOD("get_node_instance_placeholder", "idx"), &SceneState::get_node_instance_placeholder); + ClassDB::bind_method(D_METHOD("get_node_instance:PackedScene", "idx"), &SceneState::get_node_instance); + ClassDB::bind_method(D_METHOD("get_node_groups", "idx"), &SceneState::_get_node_groups); + ClassDB::bind_method(D_METHOD("get_node_property_count", "idx"), &SceneState::get_node_property_count); + ClassDB::bind_method(D_METHOD("get_node_property_name", "idx", "prop_idx"), &SceneState::get_node_property_name); + ClassDB::bind_method(D_METHOD("get_node_property_value", "idx", "prop_idx"), &SceneState::get_node_property_value); + ClassDB::bind_method(D_METHOD("get_connection_count"), &SceneState::get_connection_count); + ClassDB::bind_method(D_METHOD("get_connection_source", "idx"), &SceneState::get_connection_source); + ClassDB::bind_method(D_METHOD("get_connection_signal", "idx"), &SceneState::get_connection_signal); + ClassDB::bind_method(D_METHOD("get_connection_target", "idx"), &SceneState::get_connection_target); + ClassDB::bind_method(D_METHOD("get_connection_method", "idx"), &SceneState::get_connection_method); + ClassDB::bind_method(D_METHOD("get_connection_flags", "idx"), &SceneState::get_connection_flags); + ClassDB::bind_method(D_METHOD("get_connection_binds", "idx"), &SceneState::get_connection_binds); + + BIND_CONSTANT(GEN_EDIT_STATE_DISABLED); + BIND_CONSTANT(GEN_EDIT_STATE_INSTANCE); + BIND_CONSTANT(GEN_EDIT_STATE_MAIN); } SceneState::SceneState() { - base_scene_idx=-1; - last_modified_time=0; + base_scene_idx = -1; + last_modified_time = 0; } - //////////////// - - -void PackedScene::_set_bundled_scene(const Dictionary& d) { +void PackedScene::_set_bundled_scene(const Dictionary &d) { state->set_bundled_scene(d); } @@ -1766,7 +1682,6 @@ Dictionary PackedScene::_get_bundled_scene() const { return state->get_bundled_scene(); } - Error PackedScene::pack(Node *p_scene) { return state->pack(p_scene); @@ -1785,9 +1700,9 @@ bool PackedScene::can_instance() const { Node *PackedScene::instance(GenEditState p_edit_state) const { #ifndef TOOLS_ENABLED - if (p_edit_state!=GEN_EDIT_STATE_DISABLED) { + if (p_edit_state != GEN_EDIT_STATE_DISABLED) { ERR_EXPLAIN("Edit state is only for editors, does not work without tools compiled"); - ERR_FAIL_COND_V(p_edit_state!=GEN_EDIT_STATE_DISABLED,NULL); + ERR_FAIL_COND_V(p_edit_state != GEN_EDIT_STATE_DISABLED, NULL); } #endif @@ -1795,14 +1710,13 @@ Node *PackedScene::instance(GenEditState p_edit_state) const { if (!s) return NULL; - if (p_edit_state!=GEN_EDIT_STATE_DISABLED) { + if (p_edit_state != GEN_EDIT_STATE_DISABLED) { s->set_scene_instance_state(state); } - if (get_path()!="" && get_path().find("::")==-1) + if (get_path() != "" && get_path().find("::") == -1) s->set_filename(get_path()); - s->notification(Node::NOTIFICATION_INSTANCED); return s; @@ -1810,17 +1724,16 @@ Node *PackedScene::instance(GenEditState p_edit_state) const { void PackedScene::replace_state(Ref<SceneState> p_by) { - state=p_by; + state = p_by; state->set_path(get_path()); #ifdef TOOLS_ENABLED state->set_last_modified_time(get_last_modified_time()); #endif - } void PackedScene::recreate_state() { - state = Ref<SceneState>( memnew( SceneState )); + state = Ref<SceneState>(memnew(SceneState)); state->set_path(get_path()); #ifdef TOOLS_ENABLED state->set_last_modified_time(get_last_modified_time()); @@ -1832,32 +1745,29 @@ Ref<SceneState> PackedScene::get_state() { return state; } -void PackedScene::set_path(const String& p_path,bool p_take_over) { +void PackedScene::set_path(const String &p_path, bool p_take_over) { state->set_path(p_path); - Resource::set_path(p_path,p_take_over); + Resource::set_path(p_path, p_take_over); } - void PackedScene::_bind_methods() { - ClassDB::bind_method(D_METHOD("pack","path:Node"),&PackedScene::pack); - ClassDB::bind_method(D_METHOD("instance:Node","edit_state"),&PackedScene::instance,DEFVAL(false)); - ClassDB::bind_method(D_METHOD("can_instance"),&PackedScene::can_instance); - ClassDB::bind_method(D_METHOD("_set_bundled_scene"),&PackedScene::_set_bundled_scene); - ClassDB::bind_method(D_METHOD("_get_bundled_scene"),&PackedScene::_get_bundled_scene); - ClassDB::bind_method(D_METHOD("get_state:SceneState"),&PackedScene::get_state); - - ADD_PROPERTY( PropertyInfo(Variant::DICTIONARY,"_bundled"),"_set_bundled_scene","_get_bundled_scene"); + ClassDB::bind_method(D_METHOD("pack", "path:Node"), &PackedScene::pack); + ClassDB::bind_method(D_METHOD("instance:Node", "edit_state"), &PackedScene::instance, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("can_instance"), &PackedScene::can_instance); + ClassDB::bind_method(D_METHOD("_set_bundled_scene"), &PackedScene::_set_bundled_scene); + ClassDB::bind_method(D_METHOD("_get_bundled_scene"), &PackedScene::_get_bundled_scene); + ClassDB::bind_method(D_METHOD("get_state:SceneState"), &PackedScene::get_state); - BIND_CONSTANT( GEN_EDIT_STATE_DISABLED ); - BIND_CONSTANT( GEN_EDIT_STATE_INSTANCE ); - BIND_CONSTANT( GEN_EDIT_STATE_MAIN ); + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_bundled"), "_set_bundled_scene", "_get_bundled_scene"); + BIND_CONSTANT(GEN_EDIT_STATE_DISABLED); + BIND_CONSTANT(GEN_EDIT_STATE_INSTANCE); + BIND_CONSTANT(GEN_EDIT_STATE_MAIN); } PackedScene::PackedScene() { - state = Ref<SceneState>( memnew( SceneState )); - + state = Ref<SceneState>(memnew(SceneState)); } diff --git a/scene/resources/packed_scene.h b/scene/resources/packed_scene.h index 4a3841abe9..5fa54413a8 100644 --- a/scene/resources/packed_scene.h +++ b/scene/resources/packed_scene.h @@ -32,23 +32,21 @@ #include "resource.h" #include "scene/main/node.h" - class SceneState : public Reference { - GDCLASS( SceneState, Reference ); - + GDCLASS(SceneState, Reference); Vector<StringName> names; Vector<Variant> variants; Vector<NodePath> node_paths; Vector<NodePath> editable_instances; - mutable HashMap<NodePath,int> node_path_cache; - mutable Map<int,int> base_scene_node_remap; + mutable HashMap<NodePath, int> node_path_cache; + mutable Map<int, int> base_scene_node_remap; int base_scene_idx; enum { - NO_PARENT_SAVED=0x7FFFFFFF, + NO_PARENT_SAVED = 0x7FFFFFFF, }; struct NodeData { @@ -67,13 +65,12 @@ class SceneState : public Reference { Vector<Property> properties; Vector<int> groups; - }; struct PackState { Ref<SceneState> state; int node; - PackState() { node=-1; } + PackState() { node = -1; } }; Vector<NodeData> nodes; @@ -90,9 +87,8 @@ class SceneState : public Reference { Vector<ConnectionData> connections; - - Error _parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map); - Error _parse_connections(Node *p_owner,Node *p_node, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map); + Error _parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map); + Error _parse_connections(Node *p_owner, Node *p_node, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map); String path; @@ -105,16 +101,14 @@ class SceneState : public Reference { PoolVector<String> _get_node_groups(int p_idx) const; protected: - static void _bind_methods(); public: - enum { - FLAG_ID_IS_PATH=(1<<30), - TYPE_INSTANCED=0x7FFFFFFF, - FLAG_INSTANCE_IS_PLACEHOLDER=(1<<30), - FLAG_MASK=(1<<24)-1, + FLAG_ID_IS_PATH = (1 << 30), + TYPE_INSTANCED = 0x7FFFFFFF, + FLAG_INSTANCE_IS_PLACEHOLDER = (1 << 30), + FLAG_MASK = (1 << 24) - 1, }; enum GenEditState { @@ -125,13 +119,12 @@ public: static void set_disable_placeholders(bool p_disable); - int find_node_by_path(const NodePath& p_node) const; - Variant get_property_value(int p_node,const StringName& p_property,bool &found) const; - bool is_node_in_group(int p_node,const StringName& p_group) const; - bool is_connection(int p_node,const StringName& p_signal,int p_to_node,const StringName& p_to_method) const; - + int find_node_by_path(const NodePath &p_node) const; + Variant get_property_value(int p_node, const StringName &p_property, bool &found) const; + bool is_node_in_group(int p_node, const StringName &p_group) const; + bool is_connection(int p_node, const StringName &p_signal, int p_to_node, const StringName &p_to_method) const; - void set_bundled_scene(const Dictionary& p_dictionary); + void set_bundled_scene(const Dictionary &p_dictionary); Dictionary get_bundled_scene() const; Error pack(Node *p_scene); @@ -144,13 +137,12 @@ public: bool can_instance() const; Node *instance(GenEditState p_edit_state) const; - //unbuild API int get_node_count() const; StringName get_node_type(int p_idx) const; StringName get_node_name(int p_idx) const; - NodePath get_node_path(int p_idx,bool p_for_parent=false) const; + NodePath get_node_path(int p_idx, bool p_for_parent = false) const; NodePath get_node_owner_path(int p_idx) const; Ref<PackedScene> get_node_instance(int p_idx) const; String get_node_instance_placeholder(int p_idx) const; @@ -158,8 +150,8 @@ public: Vector<StringName> get_node_groups(int p_idx) const; int get_node_property_count(int p_idx) const; - StringName get_node_property_name(int p_idx,int p_prop) const; - Variant get_node_property_value(int p_idx,int p_prop) const; + StringName get_node_property_name(int p_idx, int p_prop) const; + Variant get_node_property_value(int p_idx, int p_prop) const; int get_connection_count() const; NodePath get_connection_source(int p_idx) const; @@ -169,27 +161,26 @@ public: int get_connection_flags(int p_idx) const; Array get_connection_binds(int p_idx) const; - bool has_connection(const NodePath &p_node_from, const StringName& p_signal, const NodePath &p_node_to, const StringName& p_method) const; + bool has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method) const; Vector<NodePath> get_editable_instances() const; //build API - int add_name(const StringName& p_name); - int find_name(const StringName& p_name) const; - int add_value(const Variant& p_value); - int add_node_path(const NodePath& p_path); - int add_node(int p_parent,int p_owner,int p_type,int p_name, int p_instance); - void add_node_property(int p_node,int p_name,int p_value); - void add_node_group(int p_node,int p_group); + int add_name(const StringName &p_name); + int find_name(const StringName &p_name) const; + int add_value(const Variant &p_value); + int add_node_path(const NodePath &p_path); + int add_node(int p_parent, int p_owner, int p_type, int p_name, int p_instance); + void add_node_property(int p_node, int p_name, int p_value); + void add_node_group(int p_node, int p_group); void set_base_scene(int p_idx); - void add_connection(int p_from,int p_to, int p_signal, int p_method, int p_flags,const Vector<int>& p_binds); - void add_editable_instance(const NodePath& p_path); + void add_connection(int p_from, int p_to, int p_signal, int p_method, int p_flags, const Vector<int> &p_binds); + void add_editable_instance(const NodePath &p_path); - virtual void set_last_modified_time(uint64_t p_time) { last_modified_time=p_time; } + virtual void set_last_modified_time(uint64_t p_time) { last_modified_time = p_time; } uint64_t get_last_modified_time() const { return last_modified_time; } - SceneState(); }; @@ -197,20 +188,19 @@ VARIANT_ENUM_CAST(SceneState::GenEditState) class PackedScene : public Resource { - GDCLASS(PackedScene, Resource ); + GDCLASS(PackedScene, Resource); RES_BASE_EXTENSION("scn"); Ref<SceneState> state; - void _set_bundled_scene(const Dictionary& p_scene); + void _set_bundled_scene(const Dictionary &p_scene); Dictionary _get_bundled_scene() const; protected: - virtual bool editor_can_reload_from_file() { return false; } // this is handled by editor better static void _bind_methods(); -public: +public: enum GenEditState { GEN_EDIT_STATE_DISABLED, GEN_EDIT_STATE_INSTANCE, @@ -222,12 +212,12 @@ public: void clear(); bool can_instance() const; - Node *instance(GenEditState p_edit_state=GEN_EDIT_STATE_DISABLED) const; + Node *instance(GenEditState p_edit_state = GEN_EDIT_STATE_DISABLED) const; void recreate_state(); void replace_state(Ref<SceneState> p_by); - virtual void set_path(const String& p_path,bool p_take_over=false); + virtual void set_path(const String &p_path, bool p_take_over = false); #ifdef TOOLS_ENABLED virtual void set_last_modified_time(uint64_t p_time) { state->set_last_modified_time(p_time); } @@ -235,7 +225,6 @@ public: Ref<SceneState> get_state(); PackedScene(); - }; VARIANT_ENUM_CAST(PackedScene::GenEditState) diff --git a/scene/resources/plane_shape.cpp b/scene/resources/plane_shape.cpp index f1bb6d60c0..e3535b1a63 100644 --- a/scene/resources/plane_shape.cpp +++ b/scene/resources/plane_shape.cpp @@ -38,11 +38,11 @@ Vector<Vector3> PlaneShape::_gen_debug_mesh_lines() { Vector3 n1 = p.get_any_perpendicular_normal(); Vector3 n2 = p.normal.cross(n1).normalized(); - Vector3 pface[4]={ - p.normal*p.d+n1*10.0+n2*10.0, - p.normal*p.d+n1*10.0+n2*-10.0, - p.normal*p.d+n1*-10.0+n2*-10.0, - p.normal*p.d+n1*-10.0+n2*10.0, + Vector3 pface[4] = { + p.normal * p.d + n1 * 10.0 + n2 * 10.0, + p.normal * p.d + n1 * 10.0 + n2 * -10.0, + p.normal * p.d + n1 * -10.0 + n2 * -10.0, + p.normal * p.d + n1 * -10.0 + n2 * 10.0, }; points.push_back(pface[0]); @@ -53,20 +53,20 @@ Vector<Vector3> PlaneShape::_gen_debug_mesh_lines() { points.push_back(pface[3]); points.push_back(pface[3]); points.push_back(pface[0]); - points.push_back(p.normal*p.d); - points.push_back(p.normal*p.d+p.normal*3); + points.push_back(p.normal * p.d); + points.push_back(p.normal * p.d + p.normal * 3); return points; } void PlaneShape::_update_shape() { - PhysicsServer::get_singleton()->shape_set_data(get_shape(),plane); + PhysicsServer::get_singleton()->shape_set_data(get_shape(), plane); } void PlaneShape::set_plane(Plane p_plane) { - plane=p_plane; + plane = p_plane; _update_shape(); notify_change_to_owners(); _change_notify("plane"); @@ -77,17 +77,16 @@ Plane PlaneShape::get_plane() const { return plane; } - void PlaneShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_plane","plane"),&PlaneShape::set_plane); - ClassDB::bind_method(D_METHOD("get_plane"),&PlaneShape::get_plane); - - ADD_PROPERTY( PropertyInfo(Variant::PLANE,"plane"), "set_plane", "get_plane") ; + ClassDB::bind_method(D_METHOD("set_plane", "plane"), &PlaneShape::set_plane); + ClassDB::bind_method(D_METHOD("get_plane"), &PlaneShape::get_plane); + ADD_PROPERTY(PropertyInfo(Variant::PLANE, "plane"), "set_plane", "get_plane"); } -PlaneShape::PlaneShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_PLANE)) { +PlaneShape::PlaneShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_PLANE)) { - set_plane(Plane(0,1,0,0)); + set_plane(Plane(0, 1, 0, 0)); } diff --git a/scene/resources/plane_shape.h b/scene/resources/plane_shape.h index 88f3a04f05..899aad7e01 100644 --- a/scene/resources/plane_shape.h +++ b/scene/resources/plane_shape.h @@ -33,17 +33,16 @@ class PlaneShape : public Shape { - GDCLASS(PlaneShape,Shape); + GDCLASS(PlaneShape, Shape); Plane plane; protected: - static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); -public: +public: void set_plane(Plane p_plane); Plane get_plane() const; diff --git a/scene/resources/polygon_path_finder.cpp b/scene/resources/polygon_path_finder.cpp index 6dac8a9779..44ef828d02 100644 --- a/scene/resources/polygon_path_finder.cpp +++ b/scene/resources/polygon_path_finder.cpp @@ -29,107 +29,98 @@ #include "polygon_path_finder.h" #include "geometry.h" +bool PolygonPathFinder::_is_point_inside(const Vector2 &p_point) const { -bool PolygonPathFinder::_is_point_inside(const Vector2& p_point) const { + int crosses = 0; - int crosses=0; + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { - - - const Edge& e=E->get(); + const Edge &e = E->get(); Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; - - if (Geometry::segment_intersects_segment_2d(a,b,p_point,outside_point,NULL)) { + if (Geometry::segment_intersects_segment_2d(a, b, p_point, outside_point, NULL)) { crosses++; } } - return crosses&1; + return crosses & 1; } -void PolygonPathFinder::setup(const Vector<Vector2>& p_points, const Vector<int>& p_connections) { +void PolygonPathFinder::setup(const Vector<Vector2> &p_points, const Vector<int> &p_connections) { - - ERR_FAIL_COND(p_connections.size()&1); + ERR_FAIL_COND(p_connections.size() & 1); points.clear(); edges.clear(); //insert points - int point_count=p_points.size(); - points.resize(point_count+2); - bounds=Rect2(); + int point_count = p_points.size(); + points.resize(point_count + 2); + bounds = Rect2(); - for(int i=0;i<p_points.size();i++) { + for (int i = 0; i < p_points.size(); i++) { - points[i].pos=p_points[i]; - points[i].penalty=0; + points[i].pos = p_points[i]; + points[i].penalty = 0; - outside_point.x = i==0?p_points[0].x:(MAX( p_points[i].x, outside_point.x )); - outside_point.y = i==0?p_points[0].y:(MAX( p_points[i].y, outside_point.y )); + outside_point.x = i == 0 ? p_points[0].x : (MAX(p_points[i].x, outside_point.x)); + outside_point.y = i == 0 ? p_points[0].y : (MAX(p_points[i].y, outside_point.y)); - if (i==0) { - bounds.pos=points[i].pos; + if (i == 0) { + bounds.pos = points[i].pos; } else { bounds.expand_to(points[i].pos); } } - outside_point.x+=20.451+Math::randf()*10.2039; - outside_point.y+=21.193+Math::randf()*12.5412; + outside_point.x += 20.451 + Math::randf() * 10.2039; + outside_point.y += 21.193 + Math::randf() * 12.5412; //insert edges (which are also connetions) - for(int i=0;i<p_connections.size();i+=2) { + for (int i = 0; i < p_connections.size(); i += 2) { - Edge e(p_connections[i],p_connections[i+1]); - ERR_FAIL_INDEX(e.points[0],point_count); - ERR_FAIL_INDEX(e.points[1],point_count); - points[p_connections[i]].connections.insert(p_connections[i+1]); - points[p_connections[i+1]].connections.insert(p_connections[i]); + Edge e(p_connections[i], p_connections[i + 1]); + ERR_FAIL_INDEX(e.points[0], point_count); + ERR_FAIL_INDEX(e.points[1], point_count); + points[p_connections[i]].connections.insert(p_connections[i + 1]); + points[p_connections[i + 1]].connections.insert(p_connections[i]); edges.insert(e); } - //fill the remaining connections based on visibility - for(int i=0;i<point_count;i++) { + for (int i = 0; i < point_count; i++) { - for(int j=i+1;j<point_count;j++) { + for (int j = i + 1; j < point_count; j++) { - if (edges.has(Edge(i,j))) + if (edges.has(Edge(i, j))) continue; //if in edge ignore - Vector2 from=points[i].pos; - Vector2 to=points[j].pos; + Vector2 from = points[i].pos; + Vector2 to = points[j].pos; - if (!_is_point_inside(from*0.5+to*0.5)) //connection between points in inside space + if (!_is_point_inside(from * 0.5 + to * 0.5)) //connection between points in inside space continue; - bool valid=true; + bool valid = true; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - const Edge& e=E->get(); - if (e.points[0]==i || e.points[1]==i || e.points[0]==j || e.points[1]==j ) + const Edge &e = E->get(); + if (e.points[0] == i || e.points[1] == i || e.points[0] == j || e.points[1] == j) continue; - Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; - - if (Geometry::segment_intersects_segment_2d(a,b,from,to,NULL)) { - valid=false; + if (Geometry::segment_intersects_segment_2d(a, b, from, to, NULL)) { + valid = false; break; } - } if (valid) { @@ -140,92 +131,86 @@ void PolygonPathFinder::setup(const Vector<Vector2>& p_points, const Vector<int> } } - -Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector2& p_to) { +Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector2 &p_to) { Vector<Vector2> path; - Vector2 from=p_from; - Vector2 to=p_to; - Edge ignore_from_edge(-1,-1); - Edge ignore_to_edge(-1,-1); + Vector2 from = p_from; + Vector2 to = p_to; + Edge ignore_from_edge(-1, -1); + Edge ignore_to_edge(-1, -1); if (!_is_point_inside(from)) { - float closest_dist=1e20; + float closest_dist = 1e20; Vector2 closest_point; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - const Edge& e=E->get(); - Vector2 seg[2]={ + const Edge &e = E->get(); + Vector2 seg[2] = { points[e.points[0]].pos, points[e.points[1]].pos }; - - Vector2 closest = Geometry::get_closest_point_to_segment_2d(from,seg); + Vector2 closest = Geometry::get_closest_point_to_segment_2d(from, seg); float d = from.distance_squared_to(closest); - if (d<closest_dist) { - ignore_from_edge=E->get(); - closest_dist=d; - closest_point=closest; + if (d < closest_dist) { + ignore_from_edge = E->get(); + closest_dist = d; + closest_point = closest; } } - from=closest_point; + from = closest_point; }; - if (!_is_point_inside(to)) { - float closest_dist=1e20; + float closest_dist = 1e20; Vector2 closest_point; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - const Edge& e=E->get(); - Vector2 seg[2]={ + const Edge &e = E->get(); + Vector2 seg[2] = { points[e.points[0]].pos, points[e.points[1]].pos }; - - Vector2 closest = Geometry::get_closest_point_to_segment_2d(to,seg); + Vector2 closest = Geometry::get_closest_point_to_segment_2d(to, seg); float d = to.distance_squared_to(closest); - if (d<closest_dist) { - ignore_to_edge=E->get(); - closest_dist=d; - closest_point=closest; + if (d < closest_dist) { + ignore_to_edge = E->get(); + closest_dist = d; + closest_point = closest; } } - to=closest_point; + to = closest_point; }; //test direct connection { - bool can_see_eachother=true; + bool can_see_eachother = true; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - const Edge& e=E->get(); - if (e.points[0]==ignore_from_edge.points[0] && e.points[1]==ignore_from_edge.points[1]) + const Edge &e = E->get(); + if (e.points[0] == ignore_from_edge.points[0] && e.points[1] == ignore_from_edge.points[1]) continue; - if (e.points[0]==ignore_to_edge.points[0] && e.points[1]==ignore_to_edge.points[1]) + if (e.points[0] == ignore_to_edge.points[0] && e.points[1] == ignore_to_edge.points[1]) continue; Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; - - if (Geometry::segment_intersects_segment_2d(a,b,from,to,NULL)) { - can_see_eachother=false; + if (Geometry::segment_intersects_segment_2d(a, b, from, to, NULL)) { + can_see_eachother = false; break; } - } if (can_see_eachother) { @@ -238,85 +223,72 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector //add to graph - int aidx = points.size()-2; - int bidx = points.size()-1; - points[aidx].pos=from; - points[bidx].pos=to; - points[aidx].distance=0; - points[bidx].distance=0; - points[aidx].prev=-1; - points[bidx].prev=-1; - points[aidx].penalty=0; - points[bidx].penalty=0; - - - - for(int i=0;i<points.size()-2;i++) { - - - bool valid_a=true; - bool valid_b=true; - points[i].prev=-1; - points[i].distance=0; - - if (!_is_point_inside(from*0.5+points[i].pos*0.5)) { - valid_a=false; - + int aidx = points.size() - 2; + int bidx = points.size() - 1; + points[aidx].pos = from; + points[bidx].pos = to; + points[aidx].distance = 0; + points[bidx].distance = 0; + points[aidx].prev = -1; + points[bidx].prev = -1; + points[aidx].penalty = 0; + points[bidx].penalty = 0; + + for (int i = 0; i < points.size() - 2; i++) { + + bool valid_a = true; + bool valid_b = true; + points[i].prev = -1; + points[i].distance = 0; + + if (!_is_point_inside(from * 0.5 + points[i].pos * 0.5)) { + valid_a = false; } - - if (!_is_point_inside(to*0.5+points[i].pos*0.5)) { - valid_b=false; - + if (!_is_point_inside(to * 0.5 + points[i].pos * 0.5)) { + valid_b = false; } + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { - - const Edge& e=E->get(); + const Edge &e = E->get(); - if (e.points[0]==i || e.points[1]==i) + if (e.points[0] == i || e.points[1] == i) continue; - Vector2 a = points[e.points[0]].pos; Vector2 b = points[e.points[1]].pos; if (valid_a) { - if (e.points[0]!=ignore_from_edge.points[1] && - e.points[1]!=ignore_from_edge.points[1] && - e.points[0]!=ignore_from_edge.points[0] && - e.points[1]!=ignore_from_edge.points[0]) { - + if (e.points[0] != ignore_from_edge.points[1] && + e.points[1] != ignore_from_edge.points[1] && + e.points[0] != ignore_from_edge.points[0] && + e.points[1] != ignore_from_edge.points[0]) { - if (Geometry::segment_intersects_segment_2d(a,b,from,points[i].pos,NULL)) { - valid_a=false; + if (Geometry::segment_intersects_segment_2d(a, b, from, points[i].pos, NULL)) { + valid_a = false; } } } if (valid_b) { - if (e.points[0]!=ignore_to_edge.points[1] && - e.points[1]!=ignore_to_edge.points[1] && - e.points[0]!=ignore_to_edge.points[0] && - e.points[1]!=ignore_to_edge.points[0]) { - + if (e.points[0] != ignore_to_edge.points[1] && + e.points[1] != ignore_to_edge.points[1] && + e.points[0] != ignore_to_edge.points[0] && + e.points[1] != ignore_to_edge.points[0]) { - if (Geometry::segment_intersects_segment_2d(a,b,to,points[i].pos,NULL)) { - valid_b=false; + if (Geometry::segment_intersects_segment_2d(a, b, to, points[i].pos, NULL)) { + valid_b = false; } } } if (!valid_a && !valid_b) break; - - } - if (valid_a) { points[i].connections.insert(aidx); points[aidx].connections.insert(i); @@ -326,82 +298,76 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector points[i].connections.insert(bidx); points[bidx].connections.insert(i); } - } //solve graph Set<int> open_list; - points[aidx].distance=0; - points[aidx].prev=aidx; - for(Set<int>::Element *E=points[aidx].connections.front();E;E=E->next()) { + points[aidx].distance = 0; + points[aidx].prev = aidx; + for (Set<int>::Element *E = points[aidx].connections.front(); E; E = E->next()) { open_list.insert(E->get()); - points[E->get()].distance=from.distance_to(points[E->get()].pos); - points[E->get()].prev=aidx; - + points[E->get()].distance = from.distance_to(points[E->get()].pos); + points[E->get()].prev = aidx; } + bool found_route = false; - bool found_route=false; - - while(true) { + while (true) { - if (open_list.size()==0) { + if (open_list.size() == 0) { printf("open list empty\n"); break; } //check open list - int least_cost_point=-1; - float least_cost=1e30; + int least_cost_point = -1; + float least_cost = 1e30; //this could be faster (cache previous results) - for (Set<int>::Element *E=open_list.front();E;E=E->next()) { + for (Set<int>::Element *E = open_list.front(); E; E = E->next()) { - const Point& p =points[E->get()]; + const Point &p = points[E->get()]; float cost = p.distance; - cost+=p.pos.distance_to(to); - cost+=p.penalty; + cost += p.pos.distance_to(to); + cost += p.penalty; - if (cost<least_cost) { + if (cost < least_cost) { - least_cost_point=E->get(); - least_cost=cost; + least_cost_point = E->get(); + least_cost = cost; } } - Point &np = points[least_cost_point]; //open the neighbours for search - for(Set<int>::Element *E=np.connections.front();E;E=E->next()) { + for (Set<int>::Element *E = np.connections.front(); E; E = E->next()) { - Point& p =points[E->get()]; + Point &p = points[E->get()]; float distance = np.pos.distance_to(p.pos) + np.distance; - if (p.prev!=-1) { + if (p.prev != -1) { //oh this was visited already, can we win the cost? - if (p.distance>distance) { + if (p.distance > distance) { - p.prev=least_cost_point; //reasign previous - p.distance=distance; + p.prev = least_cost_point; //reasign previous + p.distance = distance; } } else { //add to open neighbours - p.prev=least_cost_point; - p.distance=distance; + p.prev = least_cost_point; + p.distance = distance; open_list.insert(E->get()); - if (E->get()==bidx) { + if (E->get() == bidx) { //oh my reached end! stop algorithm - found_route=true; + found_route = true; break; - } - } } @@ -415,186 +381,179 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector int at = bidx; path.push_back(points[at].pos); do { - at=points[at].prev; + at = points[at].prev; path.push_back(points[at].pos); - } while (at!=aidx); + } while (at != aidx); path.invert(); } - for(int i=0;i<points.size()-2;i++) { + for (int i = 0; i < points.size() - 2; i++) { points[i].connections.erase(aidx); points[i].connections.erase(bidx); - points[i].prev=-1; - points[i].distance=0; + points[i].prev = -1; + points[i].distance = 0; } points[aidx].connections.clear(); - points[aidx].prev=-1; - points[aidx].distance=0; + points[aidx].prev = -1; + points[aidx].distance = 0; points[bidx].connections.clear(); - points[bidx].prev=-1; - points[bidx].distance=0; + points[bidx].prev = -1; + points[bidx].distance = 0; return path; } -void PolygonPathFinder::_set_data(const Dictionary& p_data) { - +void PolygonPathFinder::_set_data(const Dictionary &p_data) { ERR_FAIL_COND(!p_data.has("points")); ERR_FAIL_COND(!p_data.has("connections")); ERR_FAIL_COND(!p_data.has("segments")); ERR_FAIL_COND(!p_data.has("bounds")); - PoolVector<Vector2> p=p_data["points"]; - Array c=p_data["connections"]; + PoolVector<Vector2> p = p_data["points"]; + Array c = p_data["connections"]; - ERR_FAIL_COND(c.size()!=p.size()); + ERR_FAIL_COND(c.size() != p.size()); if (c.size()) return; int pc = p.size(); - points.resize(pc+2); + points.resize(pc + 2); - PoolVector<Vector2>::Read pr=p.read(); - for(int i=0;i<pc;i++) { - points[i].pos=pr[i]; - PoolVector<int> con=c[i]; - PoolVector<int>::Read cr=con.read(); - int cc=con.size(); - for(int j=0;j<cc;j++) { + PoolVector<Vector2>::Read pr = p.read(); + for (int i = 0; i < pc; i++) { + points[i].pos = pr[i]; + PoolVector<int> con = c[i]; + PoolVector<int>::Read cr = con.read(); + int cc = con.size(); + for (int j = 0; j < cc; j++) { points[i].connections.insert(cr[j]); } - } if (p_data.has("penalties")) { - PoolVector<float> penalties=p_data["penalties"]; - if (penalties.size()==pc) { + PoolVector<float> penalties = p_data["penalties"]; + if (penalties.size() == pc) { PoolVector<float>::Read pr = penalties.read(); - for(int i=0;i<pc;i++) { - points[i].penalty=pr[i]; + for (int i = 0; i < pc; i++) { + points[i].penalty = pr[i]; } } } - PoolVector<int> segs=p_data["segments"]; - int sc=segs.size(); - ERR_FAIL_COND(sc&1); + PoolVector<int> segs = p_data["segments"]; + int sc = segs.size(); + ERR_FAIL_COND(sc & 1); PoolVector<int>::Read sr = segs.read(); - for(int i=0;i<sc;i+=2) { + for (int i = 0; i < sc; i += 2) { - Edge e(sr[i],sr[i+1]); + Edge e(sr[i], sr[i + 1]); edges.insert(e); } - bounds=p_data["bounds"]; - + bounds = p_data["bounds"]; } -Dictionary PolygonPathFinder::_get_data() const{ +Dictionary PolygonPathFinder::_get_data() const { Dictionary d; PoolVector<Vector2> p; PoolVector<int> ind; Array connections; - p.resize(points.size()-2); - connections.resize(points.size()-2); - ind.resize(edges.size()*2); + p.resize(points.size() - 2); + connections.resize(points.size() - 2); + ind.resize(edges.size() * 2); PoolVector<float> penalties; - penalties.resize(points.size()-2); + penalties.resize(points.size() - 2); { - PoolVector<Vector2>::Write wp=p.write(); - PoolVector<float>::Write pw=penalties.write(); + PoolVector<Vector2>::Write wp = p.write(); + PoolVector<float>::Write pw = penalties.write(); - for(int i=0;i<points.size()-2;i++) { - wp[i]=points[i].pos; - pw[i]=points[i].penalty; + for (int i = 0; i < points.size() - 2; i++) { + wp[i] = points[i].pos; + pw[i] = points[i].penalty; PoolVector<int> c; c.resize(points[i].connections.size()); { - PoolVector<int>::Write cw=c.write(); - int idx=0; - for (Set<int>::Element *E=points[i].connections.front();E;E=E->next()) { - cw[idx++]=E->get(); + PoolVector<int>::Write cw = c.write(); + int idx = 0; + for (Set<int>::Element *E = points[i].connections.front(); E; E = E->next()) { + cw[idx++] = E->get(); } } - connections[i]=c; + connections[i] = c; } } { - PoolVector<int>::Write iw=ind.write(); - int idx=0; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { - iw[idx++]=E->get().points[0]; - iw[idx++]=E->get().points[1]; + PoolVector<int>::Write iw = ind.write(); + int idx = 0; + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { + iw[idx++] = E->get().points[0]; + iw[idx++] = E->get().points[1]; } - } - d["bounds"]=bounds; - d["points"]=p; - d["penalties"]=penalties; - d["connections"]=connections; - d["segments"]=ind; + d["bounds"] = bounds; + d["points"] = p; + d["penalties"] = penalties; + d["connections"] = connections; + d["segments"] = ind; return d; - } -bool PolygonPathFinder::is_point_inside(const Vector2& p_point) const { +bool PolygonPathFinder::is_point_inside(const Vector2 &p_point) const { return _is_point_inside(p_point); } -Vector2 PolygonPathFinder::get_closest_point(const Vector2& p_point) const { +Vector2 PolygonPathFinder::get_closest_point(const Vector2 &p_point) const { - float closest_dist=1e20; + float closest_dist = 1e20; Vector2 closest_point; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { - const Edge& e=E->get(); - Vector2 seg[2]={ + const Edge &e = E->get(); + Vector2 seg[2] = { points[e.points[0]].pos, points[e.points[1]].pos }; - - Vector2 closest = Geometry::get_closest_point_to_segment_2d(p_point,seg); + Vector2 closest = Geometry::get_closest_point_to_segment_2d(p_point, seg); float d = p_point.distance_squared_to(closest); - if (d<closest_dist) { - closest_dist=d; - closest_point=closest; + if (d < closest_dist) { + closest_dist = d; + closest_point = closest; } } - ERR_FAIL_COND_V(closest_dist==1e20,Vector2()); + ERR_FAIL_COND_V(closest_dist == 1e20, Vector2()); return closest_point; } -Vector<Vector2> PolygonPathFinder::get_intersections(const Vector2& p_from, const Vector2& p_to) const { +Vector<Vector2> PolygonPathFinder::get_intersections(const Vector2 &p_from, const Vector2 &p_to) const { Vector<Vector2> inters; - for (Set<Edge>::Element *E=edges.front();E;E=E->next()) { + for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) { Vector2 a = points[E->get().points[0]].pos; Vector2 b = points[E->get().points[1]].pos; Vector2 res; - if (Geometry::segment_intersects_segment_2d(a,b,p_from,p_to,&res)) { + if (Geometry::segment_intersects_segment_2d(a, b, p_from, p_to, &res)) { inters.push_back(res); } } return inters; - } Rect2 PolygonPathFinder::get_bounds() const { @@ -602,40 +561,34 @@ Rect2 PolygonPathFinder::get_bounds() const { return bounds; } -void PolygonPathFinder::set_point_penalty(int p_point,float p_penalty) { +void PolygonPathFinder::set_point_penalty(int p_point, float p_penalty) { - ERR_FAIL_INDEX(p_point,points.size()-2); - points[p_point].penalty=p_penalty; + ERR_FAIL_INDEX(p_point, points.size() - 2); + points[p_point].penalty = p_penalty; } float PolygonPathFinder::get_point_penalty(int p_point) const { - ERR_FAIL_INDEX_V(p_point,points.size()-2,0); + ERR_FAIL_INDEX_V(p_point, points.size() - 2, 0); return points[p_point].penalty; - } - void PolygonPathFinder::_bind_methods() { - ClassDB::bind_method(D_METHOD("setup","points","connections"),&PolygonPathFinder::setup); - ClassDB::bind_method(D_METHOD("find_path","from","to"),&PolygonPathFinder::find_path); - ClassDB::bind_method(D_METHOD("get_intersections","from","to"),&PolygonPathFinder::get_intersections); - ClassDB::bind_method(D_METHOD("get_closest_point","point"),&PolygonPathFinder::get_closest_point); - ClassDB::bind_method(D_METHOD("is_point_inside","point"),&PolygonPathFinder::is_point_inside); - ClassDB::bind_method(D_METHOD("set_point_penalty","idx","penalty"),&PolygonPathFinder::set_point_penalty); - ClassDB::bind_method(D_METHOD("get_point_penalty","idx"),&PolygonPathFinder::get_point_penalty); + ClassDB::bind_method(D_METHOD("setup", "points", "connections"), &PolygonPathFinder::setup); + ClassDB::bind_method(D_METHOD("find_path", "from", "to"), &PolygonPathFinder::find_path); + ClassDB::bind_method(D_METHOD("get_intersections", "from", "to"), &PolygonPathFinder::get_intersections); + ClassDB::bind_method(D_METHOD("get_closest_point", "point"), &PolygonPathFinder::get_closest_point); + ClassDB::bind_method(D_METHOD("is_point_inside", "point"), &PolygonPathFinder::is_point_inside); + ClassDB::bind_method(D_METHOD("set_point_penalty", "idx", "penalty"), &PolygonPathFinder::set_point_penalty); + ClassDB::bind_method(D_METHOD("get_point_penalty", "idx"), &PolygonPathFinder::get_point_penalty); - ClassDB::bind_method(D_METHOD("get_bounds"),&PolygonPathFinder::get_bounds); - ClassDB::bind_method(D_METHOD("_set_data"),&PolygonPathFinder::_set_data); - ClassDB::bind_method(D_METHOD("_get_data"),&PolygonPathFinder::_get_data); - - ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_data","_get_data"); + ClassDB::bind_method(D_METHOD("get_bounds"), &PolygonPathFinder::get_bounds); + ClassDB::bind_method(D_METHOD("_set_data"), &PolygonPathFinder::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &PolygonPathFinder::_get_data); + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); } -PolygonPathFinder::PolygonPathFinder() -{ +PolygonPathFinder::PolygonPathFinder() { } - - diff --git a/scene/resources/polygon_path_finder.h b/scene/resources/polygon_path_finder.h index 58b8023843..cd2fea87d4 100644 --- a/scene/resources/polygon_path_finder.h +++ b/scene/resources/polygon_path_finder.h @@ -33,7 +33,7 @@ class PolygonPathFinder : public Resource { - GDCLASS(PolygonPathFinder,Resource); + GDCLASS(PolygonPathFinder, Resource); struct Point { Vector2 pos; @@ -47,18 +47,18 @@ class PolygonPathFinder : public Resource { int points[2]; - _FORCE_INLINE_ bool operator<(const Edge& p_edge) const { + _FORCE_INLINE_ bool operator<(const Edge &p_edge) const { - if (points[0]==p_edge.points[0]) - return points[1]<p_edge.points[1]; + if (points[0] == p_edge.points[0]) + return points[1] < p_edge.points[1]; else - return points[0]<p_edge.points[0]; + return points[0] < p_edge.points[0]; } - Edge(int a=0, int b=0) { + Edge(int a = 0, int b = 0) { - if (a>b) { - SWAP(a,b); + if (a > b) { + SWAP(a, b); } points[0] = a; points[1] = b; @@ -71,28 +71,26 @@ class PolygonPathFinder : public Resource { Vector<Point> points; Set<Edge> edges; - bool _is_point_inside(const Vector2& p_point) const; + bool _is_point_inside(const Vector2 &p_point) const; - void _set_data(const Dictionary& p_data); + void _set_data(const Dictionary &p_data); Dictionary _get_data() const; -protected: +protected: static void _bind_methods(); -public: +public: + void setup(const Vector<Vector2> &p_points, const Vector<int> &p_connections); + Vector<Vector2> find_path(const Vector2 &p_from, const Vector2 &p_to); - void setup(const Vector<Vector2>& p_points, const Vector<int>& p_connections); - Vector<Vector2> find_path(const Vector2& p_from, const Vector2& p_to); - - void set_point_penalty(int p_point,float p_penalty); + void set_point_penalty(int p_point, float p_penalty); float get_point_penalty(int p_point) const; - bool is_point_inside(const Vector2& p_point) const; - Vector2 get_closest_point(const Vector2& p_point) const; - Vector<Vector2> get_intersections(const Vector2& p_from, const Vector2& p_to) const; + bool is_point_inside(const Vector2 &p_point) const; + Vector2 get_closest_point(const Vector2 &p_point) const; + Vector<Vector2> get_intersections(const Vector2 &p_from, const Vector2 &p_to) const; Rect2 get_bounds() const; - PolygonPathFinder(); }; diff --git a/scene/resources/ray_shape.cpp b/scene/resources/ray_shape.cpp index 52ce736925..8187b8b3f1 100644 --- a/scene/resources/ray_shape.cpp +++ b/scene/resources/ray_shape.cpp @@ -34,20 +34,20 @@ Vector<Vector3> RayShape::_gen_debug_mesh_lines() { Vector<Vector3> points; points.push_back(Vector3()); - points.push_back(Vector3(0,0,get_length())); + points.push_back(Vector3(0, 0, get_length())); return points; } void RayShape::_update_shape() { - PhysicsServer::get_singleton()->shape_set_data(get_shape(),length); + PhysicsServer::get_singleton()->shape_set_data(get_shape(), length); emit_changed(); } void RayShape::set_length(float p_length) { - length=p_length; + length = p_length; _update_shape(); notify_change_to_owners(); } @@ -57,17 +57,16 @@ float RayShape::get_length() const { return length; } - void RayShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_length","length"),&RayShape::set_length); - ClassDB::bind_method(D_METHOD("get_length"),&RayShape::get_length); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"length",PROPERTY_HINT_RANGE,"0,4096,0.01"), "set_length", "get_length") ; + ClassDB::bind_method(D_METHOD("set_length", "length"), &RayShape::set_length); + ClassDB::bind_method(D_METHOD("get_length"), &RayShape::get_length); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_length", "get_length"); } -RayShape::RayShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_RAY)) { +RayShape::RayShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_RAY)) { set_length(1.0); } diff --git a/scene/resources/ray_shape.h b/scene/resources/ray_shape.h index 9ee59d5f91..f8dbf89e04 100644 --- a/scene/resources/ray_shape.h +++ b/scene/resources/ray_shape.h @@ -32,16 +32,15 @@ class RayShape : public Shape { - GDCLASS(RayShape,Shape); + GDCLASS(RayShape, Shape); float length; protected: - static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); -public: +public: void set_length(float p_length); float get_length() const; diff --git a/scene/resources/rectangle_shape_2d.cpp b/scene/resources/rectangle_shape_2d.cpp index 1161843a2b..06b5ac0316 100644 --- a/scene/resources/rectangle_shape_2d.cpp +++ b/scene/resources/rectangle_shape_2d.cpp @@ -32,14 +32,13 @@ #include "servers/visual_server.h" void RectangleShape2D::_update_shape() { - Physics2DServer::get_singleton()->shape_set_data(get_rid(),extents); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), extents); emit_changed(); } +void RectangleShape2D::set_extents(const Vector2 &p_extents) { -void RectangleShape2D::set_extents(const Vector2& p_extents) { - - extents=p_extents; + extents = p_extents; _update_shape(); } @@ -48,33 +47,27 @@ Vector2 RectangleShape2D::get_extents() const { return extents; } -void RectangleShape2D::draw(const RID& p_to_rid,const Color& p_color) { - - - VisualServer::get_singleton()->canvas_item_add_rect(p_to_rid,Rect2(-extents,extents*2.0),p_color); +void RectangleShape2D::draw(const RID &p_to_rid, const Color &p_color) { + VisualServer::get_singleton()->canvas_item_add_rect(p_to_rid, Rect2(-extents, extents * 2.0), p_color); } Rect2 RectangleShape2D::get_rect() const { - return Rect2(-extents,extents*2.0); - + return Rect2(-extents, extents * 2.0); } - void RectangleShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_extents","extents"),&RectangleShape2D::set_extents); - ClassDB::bind_method(D_METHOD("get_extents"),&RectangleShape2D::get_extents); - - - - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"extents"),"set_extents","get_extents") ; + ClassDB::bind_method(D_METHOD("set_extents", "extents"), &RectangleShape2D::set_extents); + ClassDB::bind_method(D_METHOD("get_extents"), &RectangleShape2D::get_extents); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "extents"), "set_extents", "get_extents"); } -RectangleShape2D::RectangleShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RECTANGLE)) { +RectangleShape2D::RectangleShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RECTANGLE)) { - extents=Vector2(10,10); + extents = Vector2(10, 10); _update_shape(); } diff --git a/scene/resources/rectangle_shape_2d.h b/scene/resources/rectangle_shape_2d.h index 6682b67de0..8de2f7580e 100644 --- a/scene/resources/rectangle_shape_2d.h +++ b/scene/resources/rectangle_shape_2d.h @@ -32,20 +32,20 @@ #include "scene/resources/shape_2d.h" class RectangleShape2D : public Shape2D { - GDCLASS( RectangleShape2D, Shape2D ); + GDCLASS(RectangleShape2D, Shape2D); Vector2 extents; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: - void set_extents(const Vector2& p_extents); +public: + void set_extents(const Vector2 &p_extents); Vector2 get_extents() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); - virtual Rect2 get_rect() const ; + virtual void draw(const RID &p_to_rid, const Color &p_color); + virtual Rect2 get_rect() const; RectangleShape2D(); }; diff --git a/scene/resources/room.cpp b/scene/resources/room.cpp index e677f92c31..9ec8914e2f 100644 --- a/scene/resources/room.cpp +++ b/scene/resources/room.cpp @@ -30,16 +30,14 @@ #include "servers/visual_server.h" - RID RoomBounds::get_rid() const { return area; } +void RoomBounds::set_geometry_hint(const PoolVector<Face3> &p_geometry_hint) { -void RoomBounds::set_geometry_hint(const PoolVector<Face3>& p_geometry_hint) { - - geometry_hint=p_geometry_hint; + geometry_hint = p_geometry_hint; } PoolVector<Face3> RoomBounds::get_geometry_hint() const { @@ -47,29 +45,21 @@ PoolVector<Face3> RoomBounds::get_geometry_hint() const { return geometry_hint; } - - void RoomBounds::_bind_methods() { - - ClassDB::bind_method(D_METHOD("set_geometry_hint","triangles"),&RoomBounds::set_geometry_hint); - ClassDB::bind_method(D_METHOD("get_geometry_hint"),&RoomBounds::get_geometry_hint); + ClassDB::bind_method(D_METHOD("set_geometry_hint", "triangles"), &RoomBounds::set_geometry_hint); + ClassDB::bind_method(D_METHOD("get_geometry_hint"), &RoomBounds::get_geometry_hint); //ADD_PROPERTY( PropertyInfo( Variant::DICTIONARY, "bounds"), "set_bounds","get_bounds") ; - ADD_PROPERTY( PropertyInfo( Variant::POOL_VECTOR3_ARRAY, "geometry_hint"),"set_geometry_hint","get_geometry_hint") ; - + ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "geometry_hint"), "set_geometry_hint", "get_geometry_hint"); } RoomBounds::RoomBounds() { - area=VisualServer::get_singleton()->room_create(); + area = VisualServer::get_singleton()->room_create(); } - RoomBounds::~RoomBounds() { VisualServer::get_singleton()->free(area); - } - - diff --git a/scene/resources/room.h b/scene/resources/room.h index 84d68e5718..c7db4b13d9 100644 --- a/scene/resources/room.h +++ b/scene/resources/room.h @@ -29,38 +29,31 @@ #ifndef ROOM_BOUNDS_H #define ROOM_BOUNDS_H -#include "resource.h" #include "bsp_tree.h" +#include "resource.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class RoomBounds : public Resource { - GDCLASS( RoomBounds, Resource ); + GDCLASS(RoomBounds, Resource); RES_BASE_EXTENSION("room"); RID area; PoolVector<Face3> geometry_hint; - protected: - static void _bind_methods(); public: - virtual RID get_rid() const; - - void set_geometry_hint(const PoolVector<Face3>& geometry_hint); + void set_geometry_hint(const PoolVector<Face3> &geometry_hint); PoolVector<Face3> get_geometry_hint() const; RoomBounds(); ~RoomBounds(); - }; - - #endif // ROOM_H diff --git a/scene/resources/scene_format_text.cpp b/scene/resources/scene_format_text.cpp index 3a254836a2..7162c9fc18 100644 --- a/scene/resources/scene_format_text.cpp +++ b/scene/resources/scene_format_text.cpp @@ -29,25 +29,22 @@ #include "scene_format_text.h" #include "global_config.h" -#include "version.h" #include "os/dir_access.h" +#include "version.h" //version 2: changed names for basis, rect3, poolvectors, etc. #define FORMAT_VERSION 2 -#include "version.h" #include "os/dir_access.h" +#include "version.h" -#define _printerr() ERR_PRINT(String(res_path+":"+itos(lines)+" - Parse Error: "+error_text).utf8().get_data()); - - - +#define _printerr() ERR_PRINT(String(res_path + ":" + itos(lines) + " - Parse Error: " + error_text).utf8().get_data()); /// -void ResourceInteractiveLoaderText::set_local_path(const String& p_local_path) { +void ResourceInteractiveLoaderText::set_local_path(const String &p_local_path) { - res_path=p_local_path; + res_path = p_local_path; } Ref<Resource> ResourceInteractiveLoaderText::get_resource() { @@ -55,47 +52,46 @@ Ref<Resource> ResourceInteractiveLoaderText::get_resource() { return resource; } -Error ResourceInteractiveLoaderText::_parse_sub_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str) { +Error ResourceInteractiveLoaderText::_parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { VariantParser::Token token; - VariantParser::get_token(p_stream,token,line,r_err_str); - if (token.type!=VariantParser::TK_NUMBER) { - r_err_str="Expected number (sub-resource index)"; + VariantParser::get_token(p_stream, token, line, r_err_str); + if (token.type != VariantParser::TK_NUMBER) { + r_err_str = "Expected number (sub-resource index)"; return ERR_PARSE_ERROR; } int index = token.value; - String path = local_path+"::"+itos(index); + String path = local_path + "::" + itos(index); if (!ignore_resource_parsing) { if (!ResourceCache::has(path)) { - r_err_str="Can't load cached sub-resource: "+path; + r_err_str = "Can't load cached sub-resource: " + path; return ERR_PARSE_ERROR; } - r_res=RES(ResourceCache::get(path)); + r_res = RES(ResourceCache::get(path)); } else { - r_res=RES(); + r_res = RES(); } - VariantParser::get_token(p_stream,token,line,r_err_str); - if (token.type!=VariantParser::TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + VariantParser::get_token(p_stream, token, line, r_err_str); + if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - return OK; } -Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str){ +Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { VariantParser::Token token; - VariantParser::get_token(p_stream,token,line,r_err_str); - if (token.type!=VariantParser::TK_NUMBER) { - r_err_str="Expected number (sub-resource index)"; + VariantParser::get_token(p_stream, token, line, r_err_str); + if (token.type != VariantParser::TK_NUMBER) { + r_err_str = "Expected number (sub-resource index)"; return ERR_PARSE_ERROR; } @@ -104,93 +100,88 @@ Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream* if (!ignore_resource_parsing) { if (!ext_resources.has(id)) { - r_err_str="Can't load cached ext-resource #"+itos(id); + r_err_str = "Can't load cached ext-resource #" + itos(id); return ERR_PARSE_ERROR; } String path = ext_resources[id].path; String type = ext_resources[id].type; - 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=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); - + path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path)); } - r_res=ResourceLoader::load(path,type); + r_res = ResourceLoader::load(path, type); if (r_res.is_null()) { - WARN_PRINT(String("Couldn't load external resource: "+path).utf8().get_data()); + WARN_PRINT(String("Couldn't load external resource: " + path).utf8().get_data()); } } else { - r_res=RES(); + r_res = RES(); } - VariantParser::get_token(p_stream,token,line,r_err_str); - if (token.type!=VariantParser::TK_PARENTHESIS_CLOSE) { - r_err_str="Expected ')'"; + VariantParser::get_token(p_stream, token, line, r_err_str); + if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) { + r_err_str = "Expected ')'"; return ERR_PARSE_ERROR; } - return OK; } - Error ResourceInteractiveLoaderText::poll() { - if (error!=OK) + if (error != OK) return error; - if (next_tag.name=="ext_resource") { - + if (next_tag.name == "ext_resource") { if (!next_tag.fields.has("path")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'path' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'path' in external resource tag"; _printerr(); return error; } if (!next_tag.fields.has("type")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'type' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'type' in external resource tag"; _printerr(); return error; } if (!next_tag.fields.has("id")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'id' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'id' in external resource tag"; _printerr(); return error; } - String path=next_tag.fields["path"]; - String type=next_tag.fields["type"]; - int index=next_tag.fields["id"]; + String path = next_tag.fields["path"]; + String type = next_tag.fields["type"]; + int index = next_tag.fields["id"]; - - 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=GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); + path = GlobalConfig::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()) { - error=ERR_FILE_CORRUPT; - error_text="[ext_resource] referenced nonexistent resource at: "+path; + error = ERR_FILE_CORRUPT; + error_text = "[ext_resource] referenced nonexistent resource at: " + path; _printerr(); return error; } else { - ResourceLoader::notify_dependency_error(local_path,path,type); + ResourceLoader::notify_dependency_error(local_path, path, type); } } else { @@ -198,11 +189,11 @@ Error ResourceInteractiveLoaderText::poll() { } ExtResource er; - er.path=path; - er.type=type; - ext_resources[index]=er; + er.path = path; + er.type = type; + ext_resources[index] = er; - error = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp); + error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (error) { _printerr(); @@ -211,138 +202,130 @@ Error ResourceInteractiveLoaderText::poll() { resource_current++; return error; - - } else if (next_tag.name=="sub_resource") { - + } else if (next_tag.name == "sub_resource") { if (!next_tag.fields.has("type")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'type' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'type' in external resource tag"; _printerr(); return error; } if (!next_tag.fields.has("id")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'index' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'index' in external resource tag"; _printerr(); return error; } - String type=next_tag.fields["type"]; - int id=next_tag.fields["id"]; - - String path = local_path+"::"+itos(id); + String type = next_tag.fields["type"]; + int id = next_tag.fields["id"]; + String path = local_path + "::" + itos(id); //bool exists=ResourceCache::has(path); Ref<Resource> res; - if ( !ResourceCache::has(path)) { //only if it doesn't exist + if (!ResourceCache::has(path)) { //only if it doesn't exist Object *obj = ClassDB::instance(type); if (!obj) { - error_text+="Can't create sub resource of type: "+type; + error_text += "Can't create sub resource of type: " + type; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } - Resource *r = obj->cast_to<Resource>(); if (!r) { - error_text+="Can't create sub resource of type, because not a resource: "+type; + error_text += "Can't create sub resource of type, because not a resource: " + type; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } - res=Ref<Resource>(r); + res = Ref<Resource>(r); resource_cache.push_back(res); res->set_path(path); - } resource_current++; - while(true) { + while (true) { String assign; Variant value; - error = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,&rp); + error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); if (error) { _printerr(); return error; } - if (assign!=String()) { + if (assign != String()) { if (res.is_valid()) { - res->set(assign,value); + res->set(assign, value); } //it's assignment - } else if (next_tag.name!=String()) { + } else if (next_tag.name != String()) { - error=OK; + error = OK; break; } else { - error=ERR_FILE_CORRUPT; - error_text="Premature end of file while parsing [sub_resource]"; + error = ERR_FILE_CORRUPT; + error_text = "Premature end of file while parsing [sub_resource]"; _printerr(); return error; } - - } return OK; - } else if (next_tag.name=="resource") { + } else if (next_tag.name == "resource") { if (is_scene) { - error_text+="found the 'resource' tag on a scene file!"; + error_text += "found the 'resource' tag on a scene file!"; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } Object *obj = ClassDB::instance(res_type); if (!obj) { - error_text+="Can't create sub resource of type: "+res_type; + error_text += "Can't create sub resource of type: " + res_type; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } - Resource *r = obj->cast_to<Resource>(); if (!r) { - error_text+="Can't create sub resource of type, because not a resource: "+res_type; + error_text += "Can't create sub resource of type, because not a resource: " + res_type; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } - resource=Ref<Resource>(r); + resource = Ref<Resource>(r); resource_current++; - while(true) { + while (true) { String assign; Variant value; - error = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,&rp); + error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); if (error) { - if (error!=ERR_FILE_EOF) { + if (error != ERR_FILE_EOF) { _printerr(); } else { if (!ResourceCache::has(res_path)) { @@ -352,31 +335,30 @@ Error ResourceInteractiveLoaderText::poll() { return error; } - if (assign!=String()) { - resource->set(assign,value); + if (assign != String()) { + resource->set(assign, value); //it's assignment - } else if (next_tag.name!=String()) { + } else if (next_tag.name != String()) { - error=ERR_FILE_CORRUPT; - error_text="Extra tag found when parsing main resource file"; + error = ERR_FILE_CORRUPT; + error_text = "Extra tag found when parsing main resource file"; _printerr(); return error; } else { - error=ERR_FILE_EOF; + error = ERR_FILE_EOF; return error; } - } return OK; - } else if (next_tag.name=="node") { + } else if (next_tag.name == "node") { if (!is_scene) { - error_text+="found the 'node' tag on a resource file!"; + error_text += "found the 'node' tag on a resource file!"; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } @@ -393,87 +375,84 @@ Error ResourceInteractiveLoaderText::poll() { */ - int parent=-1; - int owner=-1; - int type=-1; - int name=-1; - int instance=-1; + int parent = -1; + int owner = -1; + int type = -1; + int name = -1; + int instance = -1; //int base_scene=-1; if (next_tag.fields.has("name")) { - name=packed_scene->get_state()->add_name(next_tag.fields["name"]); + name = packed_scene->get_state()->add_name(next_tag.fields["name"]); } if (next_tag.fields.has("parent")) { NodePath np = next_tag.fields["parent"]; np.prepend_period(); //compatible to how it manages paths internally - parent=packed_scene->get_state()->add_node_path(np); + parent = packed_scene->get_state()->add_node_path(np); } - - if (next_tag.fields.has("type")) { - type=packed_scene->get_state()->add_name(next_tag.fields["type"]); + type = packed_scene->get_state()->add_name(next_tag.fields["type"]); } else { - type=SceneState::TYPE_INSTANCED; //no type? assume this was instanced + type = SceneState::TYPE_INSTANCED; //no type? assume this was instanced } - if (next_tag.fields.has("instance")) { - instance=packed_scene->get_state()->add_value(next_tag.fields["instance"]); + instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]); - if (packed_scene->get_state()->get_node_count()==0 && parent==-1) { + if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) { packed_scene->get_state()->set_base_scene(instance); - instance=-1; + instance = -1; } } if (next_tag.fields.has("instance_placeholder")) { - String path=next_tag.fields["instance_placeholder"]; + String path = next_tag.fields["instance_placeholder"]; int path_v = packed_scene->get_state()->add_value(path); - if (packed_scene->get_state()->get_node_count()==0) { - error=ERR_FILE_CORRUPT; - error_text="Instance Placeholder can't be used for inheritance."; + if (packed_scene->get_state()->get_node_count() == 0) { + error = ERR_FILE_CORRUPT; + error_text = "Instance Placeholder can't be used for inheritance."; _printerr(); return error; } - instance=path_v|SceneState::FLAG_INSTANCE_IS_PLACEHOLDER; + instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER; } if (next_tag.fields.has("owner")) { - owner=packed_scene->get_state()->add_node_path(next_tag.fields["owner"]); + owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"]); } else { - if (parent!=-1 && !(type==SceneState::TYPE_INSTANCED && instance==-1)) - owner=0; //if no owner, owner is root + if (parent != -1 && !(type == SceneState::TYPE_INSTANCED && instance == -1)) + owner = 0; //if no owner, owner is root } - int node_id = packed_scene->get_state()->add_node(parent,owner,type,name,instance); + int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance); if (next_tag.fields.has("groups")) { Array groups = next_tag.fields["groups"]; - for (int i=0;i<groups.size();i++) { - packed_scene->get_state()->add_node_group(node_id,packed_scene->get_state()->add_name(groups[i])); + for (int i = 0; i < groups.size(); i++) { + packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(groups[i])); } } - while(true) { + while (true) { String assign; Variant value; - error = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,&rp); + error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); if (error) { - if (error!=ERR_FILE_EOF) { + if (error != ERR_FILE_EOF) { _printerr(); } else { - resource=packed_scene; + resource = packed_scene; if (!ResourceCache::has(res_path)) { packed_scene->set_path(res_path); } @@ -481,57 +460,56 @@ Error ResourceInteractiveLoaderText::poll() { return error; } - if (assign!=String()) { + if (assign != String()) { int nameidx = packed_scene->get_state()->add_name(assign); int valueidx = packed_scene->get_state()->add_value(value); - packed_scene->get_state()->add_node_property(node_id,nameidx,valueidx); + packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx); //it's assignment - } else if (next_tag.name!=String()) { + } else if (next_tag.name != String()) { - error=OK; + error = OK; return error; } else { - resource=packed_scene; - error=ERR_FILE_EOF; + resource = packed_scene; + error = ERR_FILE_EOF; return error; } - } return OK; - } else if (next_tag.name=="connection") { + } else if (next_tag.name == "connection") { if (!is_scene) { - error_text+="found the 'connection' tag on a resource file!"; + error_text += "found the 'connection' tag on a resource file!"; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } if (!next_tag.fields.has("from")) { - error=ERR_FILE_CORRUPT; - error_text="missing 'from' field fron connection tag"; + error = ERR_FILE_CORRUPT; + error_text = "missing 'from' field fron connection tag"; return error; } if (!next_tag.fields.has("to")) { - error=ERR_FILE_CORRUPT; - error_text="missing 'to' field fron connection tag"; + error = ERR_FILE_CORRUPT; + error_text = "missing 'to' field fron connection tag"; return error; } if (!next_tag.fields.has("signal")) { - error=ERR_FILE_CORRUPT; - error_text="missing 'signal' field fron connection tag"; + error = ERR_FILE_CORRUPT; + error_text = "missing 'signal' field fron connection tag"; return error; } if (!next_tag.fields.has("method")) { - error=ERR_FILE_CORRUPT; - error_text="missing 'method' field fron connection tag"; + error = ERR_FILE_CORRUPT; + error_text = "missing 'method' field fron connection tag"; return error; } @@ -539,55 +517,54 @@ Error ResourceInteractiveLoaderText::poll() { NodePath to = next_tag.fields["to"]; StringName method = next_tag.fields["method"]; StringName signal = next_tag.fields["signal"]; - int flags=CONNECT_PERSIST; + int flags = CONNECT_PERSIST; Array binds; if (next_tag.fields.has("flags")) { - flags=next_tag.fields["flags"]; + flags = next_tag.fields["flags"]; } if (next_tag.fields.has("binds")) { - binds=next_tag.fields["binds"]; + binds = next_tag.fields["binds"]; } Vector<int> bind_ints; - for(int i=0;i<binds.size();i++) { - bind_ints.push_back( packed_scene->get_state()->add_value( binds[i] ) ); + for (int i = 0; i < binds.size(); i++) { + bind_ints.push_back(packed_scene->get_state()->add_value(binds[i])); } packed_scene->get_state()->add_connection( - packed_scene->get_state()->add_node_path(from.simplified()), - packed_scene->get_state()->add_node_path(to.simplified()), - packed_scene->get_state()->add_name(signal), - packed_scene->get_state()->add_name(method), - flags, - bind_ints - ); + packed_scene->get_state()->add_node_path(from.simplified()), + packed_scene->get_state()->add_node_path(to.simplified()), + packed_scene->get_state()->add_name(signal), + packed_scene->get_state()->add_name(method), + flags, + bind_ints); - error = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp); + error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (error) { - if (error!=ERR_FILE_EOF) { + if (error != ERR_FILE_EOF) { _printerr(); } else { - resource=packed_scene; + resource = packed_scene; } } return error; - } else if (next_tag.name=="editable") { + } else if (next_tag.name == "editable") { if (!is_scene) { - error_text+="found the 'editable' tag on a resource file!"; + error_text += "found the 'editable' tag on a resource file!"; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } if (!next_tag.fields.has("path")) { - error=ERR_FILE_CORRUPT; - error_text="missing 'path' field fron connection tag"; + error = ERR_FILE_CORRUPT; + error_text = "missing 'path' field fron connection tag"; _printerr(); return error; } @@ -596,13 +573,13 @@ Error ResourceInteractiveLoaderText::poll() { packed_scene->get_state()->add_editable_instance(path.simplified()); - error = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp); + error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (error) { - if (error!=ERR_FILE_EOF) { + if (error != ERR_FILE_EOF) { _printerr(); } else { - resource=packed_scene; + resource = packed_scene; } } @@ -610,9 +587,9 @@ Error ResourceInteractiveLoaderText::poll() { } else { - error_text+="Unknown tag in file: "+next_tag.name; + error_text += "Unknown tag in file: " + next_tag.name; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; return error; } @@ -625,7 +602,7 @@ int ResourceInteractiveLoaderText::get_stage() const { } int ResourceInteractiveLoaderText::get_stage_count() const { - return resources_total;//+ext_resources; + return resources_total; //+ext_resources; } ResourceInteractiveLoaderText::~ResourceInteractiveLoaderText() { @@ -633,89 +610,79 @@ ResourceInteractiveLoaderText::~ResourceInteractiveLoaderText() { memdelete(f); } -void ResourceInteractiveLoaderText::get_dependencies(FileAccess *f,List<String> *p_dependencies,bool p_add_types) { - +void ResourceInteractiveLoaderText::get_dependencies(FileAccess *f, List<String> *p_dependencies, bool p_add_types) { open(f); - ignore_resource_parsing=true; - ERR_FAIL_COND(error!=OK); + ignore_resource_parsing = true; + ERR_FAIL_COND(error != OK); - while(next_tag.name=="ext_resource") { + while (next_tag.name == "ext_resource") { if (!next_tag.fields.has("type")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'type' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'type' in external resource tag"; _printerr(); return; } if (!next_tag.fields.has("id")) { - error=ERR_FILE_CORRUPT; - error_text="Missing 'index' in external resource tag"; + error = ERR_FILE_CORRUPT; + error_text = "Missing 'index' in external resource tag"; _printerr(); return; } - String path=next_tag.fields["path"]; - String type=next_tag.fields["type"]; - + String path = next_tag.fields["path"]; + String type = next_tag.fields["type"]; - 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=GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); + path = GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path)); } - if (p_add_types) { - path+="::"+type; + path += "::" + type; } p_dependencies->push_back(path); - Error err = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp); + Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (err) { - print_line(error_text+" - "+itos(lines)); - error_text="Unexpected end of file"; + print_line(error_text + " - " + itos(lines)); + error_text = "Unexpected end of file"; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; } - - } } -Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path,const Map<String,String>& p_map) { - +Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) { - open(p_f,true); - ERR_FAIL_COND_V(error!=OK,error); - ignore_resource_parsing=true; + open(p_f, true); + ERR_FAIL_COND_V(error != OK, error); + ignore_resource_parsing = true; //FileAccess FileAccess *fw = NULL; - String base_path=local_path.get_base_dir(); - + String base_path = local_path.get_base_dir(); uint64_t tag_end = f->get_pos(); + while (true) { - while(true) { - + Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); - - Error err = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp); - - if (err!=OK) { + if (err != OK) { if (fw) { memdelete(fw); } - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } - if (next_tag.name!="ext_resource") { + if (next_tag.name != "ext_resource") { //nothing was done if (!fw) @@ -723,22 +690,21 @@ Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const break; - } else { if (!fw) { - fw=FileAccess::open(p_path+".depren",FileAccess::WRITE); + fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); if (is_scene) { - fw->store_line("[gd_scene load_steps="+itos(resources_total)+" format="+itos(FORMAT_VERSION)+"]\n"); + fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); } else { - fw->store_line("[gd_resource type=\""+res_type+"\" load_steps="+itos(resources_total)+" format="+itos(FORMAT_VERSION)+"]\n"); + fw->store_line("[gd_resource type=\"" + res_type + "\" load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); } } if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) { memdelete(fw); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } @@ -746,41 +712,38 @@ Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const int index = next_tag.fields["id"]; String type = next_tag.fields["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); } - fw->store_line("[ext_resource path=\""+path+"\" type=\""+type+"\" id="+itos(index)+"]"); + fw->store_line("[ext_resource path=\"" + path + "\" type=\"" + type + "\" id=" + itos(index) + "]"); tag_end = f->get_pos(); - } - } f->seek(tag_end); - 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); @@ -790,114 +753,101 @@ Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, 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; - } +void ResourceInteractiveLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) { -void ResourceInteractiveLoaderText::open(FileAccess *p_f,bool p_skip_first_tag) { - - error=OK; - - lines=1; - f=p_f; + error = OK; + lines = 1; + f = p_f; - stream.f=f; - is_scene=false; - ignore_resource_parsing=false; - resource_current=0; - + stream.f = f; + is_scene = false; + ignore_resource_parsing = false; + resource_current = 0; VariantParser::Tag tag; - Error err = VariantParser::parse_tag(&stream,lines,error_text,tag); + Error err = VariantParser::parse_tag(&stream, lines, error_text, tag); if (err) { - error=err; + error = err; _printerr(); return; } if (tag.fields.has("format")) { int fmt = tag.fields["format"]; - if (fmt>FORMAT_VERSION) { - error_text="Saved with newer format version"; + if (fmt > FORMAT_VERSION) { + error_text = "Saved with newer format version"; _printerr(); - error=ERR_PARSE_ERROR; + error = ERR_PARSE_ERROR; return; } } - - if (tag.name=="gd_scene") { - is_scene=true; + if (tag.name == "gd_scene") { + is_scene = true; packed_scene.instance(); - } else if (tag.name=="gd_resource") { + } else if (tag.name == "gd_resource") { if (!tag.fields.has("type")) { - error_text="Missing 'type' field in 'gd_resource' tag"; + error_text = "Missing 'type' field in 'gd_resource' tag"; _printerr(); - error=ERR_PARSE_ERROR; + error = ERR_PARSE_ERROR; return; } - res_type=tag.fields["type"]; + res_type = tag.fields["type"]; } else { - error_text="Unrecognized file type: "+tag.name; + error_text = "Unrecognized file type: " + tag.name; _printerr(); - error=ERR_PARSE_ERROR; + error = ERR_PARSE_ERROR; return; - } - - if (tag.fields.has("load_steps")) { - resources_total=tag.fields["load_steps"]; + resources_total = tag.fields["load_steps"]; } else { - resources_total=0; + resources_total = 0; } if (!p_skip_first_tag) { - err = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp); + err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (err) { - error_text="Unexpected end of file"; + error_text = "Unexpected end of file"; _printerr(); - error=ERR_FILE_CORRUPT; + error = ERR_FILE_CORRUPT; } } - rp.ext_func=_parse_ext_resources; - rp.sub_func=_parse_sub_resources; - rp.func=NULL; - rp.userdata=this; - + rp.ext_func = _parse_ext_resources; + rp.sub_func = _parse_sub_resources; + rp.func = NULL; + rp.userdata = this; } - - - String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) { - error=OK; - - lines=1; - f=p_f; + error = OK; - stream.f=f; + lines = 1; + f = p_f; - ignore_resource_parsing=true; + stream.f = f; + ignore_resource_parsing = true; VariantParser::Tag tag; - Error err = VariantParser::parse_tag(&stream,lines,error_text,tag); + Error err = VariantParser::parse_tag(&stream, lines, error_text, tag); if (err) { _printerr(); @@ -906,30 +856,26 @@ String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) { if (tag.fields.has("format")) { int fmt = tag.fields["format"]; - if (fmt>FORMAT_VERSION) { - error_text="Saved with newer format version"; + if (fmt > FORMAT_VERSION) { + error_text = "Saved with newer format version"; _printerr(); return ""; } } - if (tag.name=="gd_scene") + if (tag.name == "gd_scene") return "PackedScene"; - if (tag.name!="gd_resource") + if (tag.name != "gd_resource") return ""; - - if (!tag.fields.has("type")) { - error_text="Missing 'type' field in 'gd_resource' tag"; + error_text = "Missing 'type' field in 'gd_resource' tag"; _printerr(); return ""; } return tag.fields["type"]; - - } ///////////////////// @@ -937,110 +883,102 @@ String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) { Ref<ResourceInteractiveLoader> ResourceFormatLoaderText::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<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) ); ria->open(f); return ria; } -void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const { +void ResourceFormatLoaderText::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; } - if (p_type=="PackedScene") + if (p_type == "PackedScene") p_extensions->push_back("tscn"); else p_extensions->push_back("tres"); - } -void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("tscn"); p_extensions->push_back("tres"); } -bool ResourceFormatLoaderText::handles_type(const String& p_type) const{ +bool ResourceFormatLoaderText::handles_type(const String &p_type) const { return true; } -String ResourceFormatLoaderText::get_resource_type(const String &p_path) const{ - +String ResourceFormatLoaderText::get_resource_type(const String &p_path) const { - - String ext=p_path.get_extension().to_lower(); - if (ext=="tscn") + String ext = p_path.get_extension().to_lower(); + if (ext == "tscn") return "PackedScene"; - else if (ext!="tres") + else if (ext != "tres") return String(); //for anyhting else must test.. - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); if (!f) { return ""; //could not rwead } - Ref<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) ); String r = ria->recognize(f); return r; } +void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { -void ResourceFormatLoaderText::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<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) ); - ria->get_dependencies(f,p_dependencies,p_add_types); - - + ria->get_dependencies(f, p_dependencies, p_add_types); } -Error ResourceFormatLoaderText::rename_dependencies(const String &p_path,const Map<String,String>& p_map) { +Error ResourceFormatLoaderText::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<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText ); - ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path); - ria->res_path=ria->local_path; + Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText); + ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path); + ria->res_path = ria->local_path; //ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) ); - return ria->rename_dependencies(f,p_path,p_map); + return ria->rename_dependencies(f, p_path, p_map); } - /*****************************************************************************************************/ /*****************************************************************************************************/ /*****************************************************************************************************/ @@ -1052,28 +990,26 @@ Error ResourceFormatLoaderText::rename_dependencies(const String &p_path,const M /*****************************************************************************************************/ /*****************************************************************************************************/ +String ResourceFormatSaverTextInstance::_write_resources(void *ud, const RES &p_resource) { -String ResourceFormatSaverTextInstance::_write_resources(void *ud,const RES& p_resource) { - - ResourceFormatSaverTextInstance *rsi=(ResourceFormatSaverTextInstance*)ud; + ResourceFormatSaverTextInstance *rsi = (ResourceFormatSaverTextInstance *)ud; return rsi->_write_resource(p_resource); - } -String ResourceFormatSaverTextInstance::_write_resource(const RES& res) { +String ResourceFormatSaverTextInstance::_write_resource(const RES &res) { if (external_resources.has(res)) { - return "ExtResource( "+itos(external_resources[res]+1)+" )"; + return "ExtResource( " + itos(external_resources[res] + 1) + " )"; } else { if (internal_resources.has(res)) { - return "SubResource( "+itos(internal_resources[res])+" )"; - } else if (res->get_path().length() && res->get_path().find("::")==-1) { + return "SubResource( " + itos(internal_resources[res]) + " )"; + } else 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(); - return "Resource( \""+path+"\" )"; + String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path(); + return "Resource( \"" + path + "\" )"; } else { ERR_EXPLAIN("Resource was not pre cached for the resource section, bug?"); ERR_FAIL_V("null"); @@ -1084,21 +1020,19 @@ String ResourceFormatSaverTextInstance::_write_resource(const RES& res) { return "null"; } -void ResourceFormatSaverTextInstance::_find_resources(const Variant& p_variant,bool p_main) { - +void ResourceFormatSaverTextInstance::_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; } @@ -1107,45 +1041,45 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant& p_variant,b 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) { + if (pi.usage & PROPERTY_USAGE_STORAGE) { - 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); @@ -1153,62 +1087,60 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant& p_variant,b } break; default: {} } - } -static String _valprop(const String& p_name) { +static String _valprop(const String &p_name) { - if (p_name.find("\"")!=-1 || p_name.find("=")!=-1 || p_name.find(" ")!=-1) - return "\""+p_name.c_escape_multiline()+"\""; + if (p_name.find("\"") != -1 || p_name.find("=") != -1 || p_name.find(" ") != -1) + return "\"" + p_name.c_escape_multiline() + "\""; return p_name; } -Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { if (p_path.ends_with(".tscn")) { - packed_scene=p_resource; + packed_scene = p_resource; } 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 = GlobalConfig::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; } // save resources - _find_resources(p_resource,true); + _find_resources(p_resource, true); if (packed_scene.is_valid()) { //add instances to external resources if saving a packed scene - for(int i=0;i<packed_scene->get_state()->get_node_count();i++) { + for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) { if (packed_scene->get_state()->is_node_instance_placeholder(i)) continue; - Ref<PackedScene> instance=packed_scene->get_state()->get_node_instance(i); + Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i); if (instance.is_valid() && !external_resources.has(instance)) { int index = external_resources.size(); - external_resources[instance]=index; + external_resources[instance] = index; } } } - - ERR_FAIL_COND_V(err!=OK,err); + ERR_FAIL_COND_V(err != OK, err); { - String title=packed_scene.is_valid()?"[gd_scene ":"[gd_resource "; + String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource "; if (packed_scene.is_null()) - title+="type=\""+p_resource->get_class()+"\" "; - int load_steps=saved_resources.size()+external_resources.size(); + title += "type=\"" + p_resource->get_class() + "\" "; + int load_steps = saved_resources.size() + external_resources.size(); /* if (packed_scene.is_valid()) { load_steps+=packed_scene->get_node_count(); @@ -1216,29 +1148,28 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re //no, better to not use load steps from nodes, no point to that */ - if (load_steps>1) { - title+="load_steps="+itos(load_steps)+" "; + if (load_steps > 1) { + title += "load_steps=" + itos(load_steps) + " "; } - title+="format="+itos(FORMAT_VERSION)+""; + title += "format=" + itos(FORMAT_VERSION) + ""; //title+="engine_version=\""+itos(VERSION_MAJOR)+"."+itos(VERSION_MINOR)+"\""; f->store_string(title); f->store_line("]\n"); //one empty line } - Vector<RES> sorted_er; sorted_er.resize(external_resources.size()); - 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()) { - sorted_er[E->get()]=E->key(); + sorted_er[E->get()] = E->key(); } - for(int i=0;i<sorted_er.size();i++) { + for (int i = 0; i < sorted_er.size(); i++) { String p = sorted_er[i]->get_path(); - f->store_string("[ext_resource path=\""+p+"\" type=\""+sorted_er[i]->get_save_class()+"\" id="+itos(i+1)+"]\n"); //bundled + f->store_string("[ext_resource path=\"" + p + "\" type=\"" + sorted_er[i]->get_save_class() + "\" id=" + itos(i + 1) + "]\n"); //bundled } if (external_resources.size()) @@ -1246,12 +1177,12 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re 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 { @@ -1261,11 +1192,11 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re } } - 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); if (main && packed_scene.is_valid()) break; //save as a scene @@ -1273,11 +1204,11 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re if (main) { f->store_line("[resource]\n"); } else { - String line="[sub_resource "; - if (res->get_subindex()==0) { - int new_subindex=1; + String line = "[sub_resource "; + 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); @@ -1285,97 +1216,87 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re } int idx = res->get_subindex(); - line+="type=\""+res->get_class()+"\" id="+itos(idx); - f->store_line(line+"]\n"); + line += "type=\"" + res->get_class() + "\" id=" + itos(idx); + f->store_line(line + "]\n"); if (takeover_paths) { - res->set_path(p_path+"::"+itos(idx),true); + res->set_path(p_path + "::" + itos(idx), true); } - internal_resources[res]=idx; + internal_resources[res] = idx; #ifdef TOOLS_ENABLED res->set_edited(false); #endif - - } - 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()) { - + 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) { + if (PE->get().usage & PROPERTY_USAGE_STORAGE) { 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; - if (PE->get().type==Variant::OBJECT && value.is_zero() && !(PE->get().usage&PROPERTY_USAGE_STORE_IF_NULL)) + if (PE->get().type == Variant::OBJECT && value.is_zero() && !(PE->get().usage & PROPERTY_USAGE_STORE_IF_NULL)) continue; String vars; - VariantWriter::write_to_string(value,vars,_write_resources,this); - f->store_string(_valprop(name)+" = "+vars+"\n"); + VariantWriter::write_to_string(value, vars, _write_resources, this); + f->store_string(_valprop(name) + " = " + vars + "\n"); } - - } f->store_string("\n"); - } if (packed_scene.is_valid()) { //if this is a scene, save nodes and connections! Ref<SceneState> state = packed_scene->get_state(); - for(int i=0;i<state->get_node_count();i++) { + for (int i = 0; i < state->get_node_count(); i++) { StringName type = state->get_node_type(i); StringName name = state->get_node_name(i); - NodePath path = state->get_node_path(i,true); + NodePath path = state->get_node_path(i, true); NodePath owner = state->get_node_owner_path(i); Ref<PackedScene> instance = state->get_node_instance(i); String instance_placeholder = state->get_node_instance_placeholder(i); Vector<StringName> groups = state->get_node_groups(i); - - - String header="[node"; - header+=" name=\""+String(name)+"\""; - if (type!=StringName()) { - header+=" type=\""+String(type)+"\""; + String header = "[node"; + header += " name=\"" + String(name) + "\""; + if (type != StringName()) { + header += " type=\"" + String(type) + "\""; } - if (path!=NodePath()) { - header+=" parent=\""+String(path.simplified())+"\""; + if (path != NodePath()) { + header += " parent=\"" + String(path.simplified()) + "\""; } - if (owner!=NodePath() && owner!=NodePath(".")) { - header+=" owner=\""+String(owner.simplified())+"\""; + if (owner != NodePath() && owner != NodePath(".")) { + header += " owner=\"" + String(owner.simplified()) + "\""; } if (groups.size()) { - String sgroups=" groups=[\n"; - for(int j=0;j<groups.size();j++) { - sgroups+="\""+String(groups[j]).c_escape()+"\",\n"; + String sgroups = " groups=[\n"; + for (int j = 0; j < groups.size(); j++) { + sgroups += "\"" + String(groups[j]).c_escape() + "\",\n"; } - sgroups+="]"; - header+=sgroups; + sgroups += "]"; + header += sgroups; } f->store_string(header); - if (instance_placeholder!=String()) { + if (instance_placeholder != String()) { String vars; f->store_string(" instance_placeholder="); - VariantWriter::write_to_string(instance_placeholder,vars,_write_resources,this); + VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this); f->store_string(vars); } @@ -1383,47 +1304,44 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re String vars; f->store_string(" instance="); - VariantWriter::write_to_string(instance,vars,_write_resources,this); + VariantWriter::write_to_string(instance, vars, _write_resources, this); f->store_string(vars); - } f->store_line("]\n"); - for(int j=0;j<state->get_node_property_count(i);j++) { + for (int j = 0; j < state->get_node_property_count(i); j++) { String vars; - VariantWriter::write_to_string(state->get_node_property_value(i,j),vars,_write_resources,this); + VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this); - f->store_string(_valprop(String(state->get_node_property_name(i,j)))+" = "+vars+"\n"); + f->store_string(_valprop(String(state->get_node_property_name(i, j))) + " = " + vars + "\n"); } if (state->get_node_property_count(i)) { //add space f->store_line(String()); } - } - for(int i=0;i<state->get_connection_count();i++) { + for (int i = 0; i < state->get_connection_count(); i++) { - String connstr="[connection"; - connstr+=" signal=\""+String(state->get_connection_signal(i))+"\""; - connstr+=" from=\""+String(state->get_connection_source(i).simplified())+"\""; - connstr+=" to=\""+String(state->get_connection_target(i).simplified())+"\""; - connstr+=" method=\""+String(state->get_connection_method(i))+"\""; + String connstr = "[connection"; + connstr += " signal=\"" + String(state->get_connection_signal(i)) + "\""; + connstr += " from=\"" + String(state->get_connection_source(i).simplified()) + "\""; + connstr += " to=\"" + String(state->get_connection_target(i).simplified()) + "\""; + connstr += " method=\"" + String(state->get_connection_method(i)) + "\""; int flags = state->get_connection_flags(i); - if (flags!=Object::CONNECT_PERSIST) { - connstr+=" flags="+itos(flags); + if (flags != Object::CONNECT_PERSIST) { + connstr += " flags=" + itos(flags); } - Array binds=state->get_connection_binds(i); + Array binds = state->get_connection_binds(i); f->store_string(connstr); if (binds.size()) { String vars; - VariantWriter::write_to_string(binds,vars,_write_resources,this); - f->store_string(" binds= "+vars); - + VariantWriter::write_to_string(binds, vars, _write_resources, this); + f->store_string(" binds= " + vars); } f->store_line("]\n"); @@ -1432,12 +1350,12 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re f->store_line(String()); Vector<NodePath> editable_instances = state->get_editable_instances(); - for(int i=0;i<editable_instances.size();i++) { - f->store_line("[editable path=\""+editable_instances[i].operator String()+"\"]"); + for (int i = 0; i < editable_instances.size(); i++) { + f->store_line("[editable path=\"" + editable_instances[i].operator String() + "\"]"); } } - 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; } @@ -1448,34 +1366,29 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re return OK; } +Error ResourceFormatSaverText::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { - -Error ResourceFormatSaverText::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { - - if (p_path.ends_with(".sct") && p_resource->get_class()!="PackedScene") { + if (p_path.ends_with(".sct") && p_resource->get_class() != "PackedScene") { return ERR_FILE_UNRECOGNIZED; } ResourceFormatSaverTextInstance saver; - return saver.save(p_path,p_resource,p_flags); - + return saver.save(p_path, p_resource, p_flags); } -bool ResourceFormatSaverText::recognize(const RES& p_resource) const { - +bool ResourceFormatSaverText::recognize(const RES &p_resource) const { return true; // all recognized! } -void ResourceFormatSaverText::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { +void ResourceFormatSaverText::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { - if (p_resource->get_class()=="PackedScene") + if (p_resource->get_class() == "PackedScene") p_extensions->push_back("tscn"); //text scene else p_extensions->push_back("tres"); //text resource - } -ResourceFormatSaverText* ResourceFormatSaverText::singleton=NULL; +ResourceFormatSaverText *ResourceFormatSaverText::singleton = NULL; ResourceFormatSaverText::ResourceFormatSaverText() { - singleton=this; + singleton = this; } diff --git a/scene/resources/scene_format_text.h b/scene/resources/scene_format_text.h index ce18f6a702..99e7de6232 100644 --- a/scene/resources/scene_format_text.h +++ b/scene/resources/scene_format_text.h @@ -35,8 +35,6 @@ #include "scene/resources/packed_scene.h" #include "variant_parser.h" - - class ResourceInteractiveLoaderText : public ResourceInteractiveLoader { String local_path; @@ -52,7 +50,6 @@ class ResourceInteractiveLoaderText : public ResourceInteractiveLoader { String type; }; - bool is_scene; String res_type; @@ -60,7 +57,7 @@ class ResourceInteractiveLoaderText : public ResourceInteractiveLoader { //Map<String,String> remaps; - Map<int,ExtResource> ext_resources; + Map<int, ExtResource> ext_resources; int resources_total; int resource_current; @@ -70,22 +67,20 @@ class ResourceInteractiveLoaderText : public ResourceInteractiveLoader { mutable int lines; - Map<String,String> remaps; + Map<String, String> remaps; //void _printerr(); - static Error _parse_sub_resources(void* p_self, VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText*>(p_self)->_parse_sub_resource(p_stream,r_res,line,r_err_str); } - static Error _parse_ext_resources(void* p_self, VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText*>(p_self)->_parse_ext_resource(p_stream,r_res,line,r_err_str); } + static Error _parse_sub_resources(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText *>(p_self)->_parse_sub_resource(p_stream, r_res, line, r_err_str); } + static Error _parse_ext_resources(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText *>(p_self)->_parse_ext_resource(p_stream, r_res, line, r_err_str); } - Error _parse_sub_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str); - Error _parse_ext_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str); + Error _parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); + Error _parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); VariantParser::ResourceParser rp; - Ref<PackedScene> packed_scene; - -friend class ResourceFormatLoaderText; + friend class ResourceFormatLoaderText; List<RES> resource_cache; Error error; @@ -93,41 +88,32 @@ friend class ResourceFormatLoaderText; 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; virtual int get_stage_count() const; - void open(FileAccess *p_f, bool p_skip_first_tag=false); + void open(FileAccess *p_f, bool p_skip_first_tag = false); 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); ~ResourceInteractiveLoaderText(); - }; - - class ResourceFormatLoaderText : 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 rename_dependencies(const String &p_path,const Map<String,String>& p_map); - - + 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); }; - -class ResourceFormatSaverTextInstance { +class ResourceFormatSaverTextInstance { String local_path; @@ -140,31 +126,26 @@ class ResourceFormatSaverTextInstance { FileAccess *f; Set<RES> resource_set; List<RES> saved_resources; - Map<RES,int> external_resources; - Map<RES,int> internal_resources; - - void _find_resources(const Variant& p_variant,bool p_main=false); + Map<RES, int> external_resources; + Map<RES, int> internal_resources; - static String _write_resources(void *ud,const RES& p_resource); - String _write_resource(const RES& res); + void _find_resources(const Variant &p_variant, bool p_main = false); + static String _write_resources(void *ud, const RES &p_resource); + String _write_resource(const RES &res); 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 ResourceFormatSaverText : public ResourceFormatSaver { public: - static ResourceFormatSaverText* 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 ResourceFormatSaverText *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; ResourceFormatSaverText(); }; - #endif // SCENE_FORMAT_TEXT_H diff --git a/scene/resources/segment_shape_2d.cpp b/scene/resources/segment_shape_2d.cpp index fbe1efe5d1..7a1114f895 100644 --- a/scene/resources/segment_shape_2d.cpp +++ b/scene/resources/segment_shape_2d.cpp @@ -34,138 +34,119 @@ void SegmentShape2D::_update_shape() { Rect2 r; - r.pos=a; - r.size=b; - Physics2DServer::get_singleton()->shape_set_data(get_rid(),r); + r.pos = a; + r.size = b; + Physics2DServer::get_singleton()->shape_set_data(get_rid(), r); emit_changed(); - } -void SegmentShape2D::set_a(const Vector2& p_a) { +void SegmentShape2D::set_a(const Vector2 &p_a) { - a=p_a; + a = p_a; _update_shape(); - } Vector2 SegmentShape2D::get_a() const { return a; } -void SegmentShape2D::set_b(const Vector2& p_b) { +void SegmentShape2D::set_b(const Vector2 &p_b) { - b=p_b; + b = p_b; _update_shape(); - } Vector2 SegmentShape2D::get_b() const { return b; } -void SegmentShape2D::draw(const RID& p_to_rid,const Color& p_color) { +void SegmentShape2D::draw(const RID &p_to_rid, const Color &p_color) { - VisualServer::get_singleton()->canvas_item_add_line(p_to_rid,a,b,p_color,3); + VisualServer::get_singleton()->canvas_item_add_line(p_to_rid, a, b, p_color, 3); } -Rect2 SegmentShape2D::get_rect() const{ +Rect2 SegmentShape2D::get_rect() const { Rect2 rect; - rect.pos=a; + rect.pos = a; rect.expand_to(b); return rect; - } - - - void SegmentShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_a","a"),&SegmentShape2D::set_a); - ClassDB::bind_method(D_METHOD("get_a"),&SegmentShape2D::get_a); - - ClassDB::bind_method(D_METHOD("set_b","b"),&SegmentShape2D::set_b); - ClassDB::bind_method(D_METHOD("get_b"),&SegmentShape2D::get_b); - + ClassDB::bind_method(D_METHOD("set_a", "a"), &SegmentShape2D::set_a); + ClassDB::bind_method(D_METHOD("get_a"), &SegmentShape2D::get_a); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"a"),"set_a","get_a") ; - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"b"),"set_b","get_b") ; + ClassDB::bind_method(D_METHOD("set_b", "b"), &SegmentShape2D::set_b); + ClassDB::bind_method(D_METHOD("get_b"), &SegmentShape2D::get_b); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "a"), "set_a", "get_a"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "b"), "set_b", "get_b"); } -SegmentShape2D::SegmentShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_SEGMENT)) { +SegmentShape2D::SegmentShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_SEGMENT)) { - a=Vector2(); - b=Vector2(0,10); + a = Vector2(); + b = Vector2(0, 10); _update_shape(); } - //////////////////////////////////////////////////////////// - void RayShape2D::_update_shape() { - Physics2DServer::get_singleton()->shape_set_data(get_rid(),length); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), length); emit_changed(); - } +void RayShape2D::draw(const RID &p_to_rid, const Color &p_color) { -void RayShape2D::draw(const RID& p_to_rid,const Color& p_color) { - - - Vector2 tip = Vector2(0,get_length()); - VS::get_singleton()->canvas_item_add_line(p_to_rid,Vector2(),tip,p_color,3); + Vector2 tip = Vector2(0, get_length()); + VS::get_singleton()->canvas_item_add_line(p_to_rid, Vector2(), tip, p_color, 3); Vector<Vector2> pts; - float tsize=4; - pts.push_back(tip+Vector2(0,tsize)); - pts.push_back(tip+Vector2(0.707*tsize,0)); - pts.push_back(tip+Vector2(-0.707*tsize,0)); + float tsize = 4; + pts.push_back(tip + Vector2(0, tsize)); + pts.push_back(tip + Vector2(0.707 * tsize, 0)); + pts.push_back(tip + Vector2(-0.707 * tsize, 0)); Vector<Color> cols; - for(int i=0;i<3;i++) + for (int i = 0; i < 3; i++) cols.push_back(p_color); - VS::get_singleton()->canvas_item_add_primitive(p_to_rid,pts,cols,Vector<Point2>(),RID()); - - - + VS::get_singleton()->canvas_item_add_primitive(p_to_rid, pts, cols, Vector<Point2>(), RID()); } Rect2 RayShape2D::get_rect() const { Rect2 rect; - rect.pos=Vector2(); - rect.expand_to(Vector2(0,length)); - rect=rect.grow(0.707*4); + rect.pos = Vector2(); + rect.expand_to(Vector2(0, length)); + rect = rect.grow(0.707 * 4); return rect; } - void RayShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_length","length"),&RayShape2D::set_length); - ClassDB::bind_method(D_METHOD("get_length"),&RayShape2D::get_length); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"length"),"set_length","get_length") ; + ClassDB::bind_method(D_METHOD("set_length", "length"), &RayShape2D::set_length); + ClassDB::bind_method(D_METHOD("get_length"), &RayShape2D::get_length); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "length"), "set_length", "get_length"); } void RayShape2D::set_length(real_t p_length) { - length=p_length; + length = p_length; _update_shape(); } real_t RayShape2D::get_length() const { return length; - - } -RayShape2D::RayShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RAY)) { +RayShape2D::RayShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RAY)) { - length=20; + length = 20; _update_shape(); } diff --git a/scene/resources/segment_shape_2d.h b/scene/resources/segment_shape_2d.h index 775bdabe9d..e58ce6be60 100644 --- a/scene/resources/segment_shape_2d.h +++ b/scene/resources/segment_shape_2d.h @@ -32,49 +32,46 @@ #include "scene/resources/shape_2d.h" class SegmentShape2D : public Shape2D { - GDCLASS( SegmentShape2D, Shape2D ); + GDCLASS(SegmentShape2D, Shape2D); Vector2 a; Vector2 b; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: - void set_a(const Vector2& p_a); - void set_b(const Vector2& p_b); +public: + void set_a(const Vector2 &p_a); + void set_b(const Vector2 &p_b); Vector2 get_a() const; Vector2 get_b() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); + virtual void draw(const RID &p_to_rid, const Color &p_color); virtual Rect2 get_rect() const; SegmentShape2D(); }; - class RayShape2D : public Shape2D { - GDCLASS( RayShape2D, Shape2D ); - + GDCLASS(RayShape2D, Shape2D); real_t length; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: +public: void set_length(real_t p_length); real_t get_length() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); + virtual void draw(const RID &p_to_rid, const Color &p_color); virtual Rect2 get_rect() const; RayShape2D(); }; - #endif // SEGMENT_SHAPE_2D_H diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp index 375a9a1cb0..fd058a4a6f 100644 --- a/scene/resources/shader.cpp +++ b/scene/resources/shader.cpp @@ -27,50 +27,45 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "shader.h" -#include "servers/visual_server.h" -#include "texture.h" #include "os/file_access.h" #include "scene/scene_string_names.h" - - +#include "servers/visual_server.h" +#include "texture.h" Shader::Mode Shader::get_mode() const { return mode; } -void Shader::set_code(const String& p_code) { +void Shader::set_code(const String &p_code) { - VisualServer::get_singleton()->shader_set_code(shader,p_code); - params_cache_dirty=true; + VisualServer::get_singleton()->shader_set_code(shader, p_code); + params_cache_dirty = true; emit_signal(SceneStringNames::get_singleton()->changed); } - String Shader::get_code() const { return VisualServer::get_singleton()->shader_get_code(shader); } - void Shader::get_param_list(List<PropertyInfo> *p_params) const { - List<PropertyInfo> local; - VisualServer::get_singleton()->shader_get_param_list(shader,&local); + VisualServer::get_singleton()->shader_get_param_list(shader, &local); params_cache.clear(); - params_cache_dirty=false; + params_cache_dirty = false; - for(List<PropertyInfo>::Element *E=local.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = local.front(); E; E = E->next()) { - PropertyInfo pi=E->get(); - pi.name="shader_param/"+pi.name; - params_cache[pi.name]=E->get().name; + PropertyInfo pi = E->get(); + pi.name = "shader_param/" + pi.name; + params_cache[pi.name] = E->get().name; if (p_params) { //small little hack - if (pi.type==Variant::_RID) - pi.type=Variant::OBJECT; + if (pi.type == Variant::_RID) + pi.type = Variant::OBJECT; p_params->push_back(pi); } } @@ -81,19 +76,18 @@ RID Shader::get_rid() const { return shader; } - -void Shader::set_default_texture_param(const StringName& p_param,const Ref<Texture>& p_texture) { +void Shader::set_default_texture_param(const StringName &p_param, const Ref<Texture> &p_texture) { if (p_texture.is_valid()) { - default_textures[p_param]=p_texture; - VS::get_singleton()->shader_set_default_texture_param(shader,p_param,p_texture->get_rid()); + default_textures[p_param] = p_texture; + VS::get_singleton()->shader_set_default_texture_param(shader, p_param, p_texture->get_rid()); } else { default_textures.erase(p_param); - VS::get_singleton()->shader_set_default_texture_param(shader,p_param,RID()); + VS::get_singleton()->shader_set_default_texture_param(shader, p_param, RID()); } } -Ref<Texture> Shader::get_default_texture_param(const StringName& p_param) const{ +Ref<Texture> Shader::get_default_texture_param(const StringName &p_param) const { if (default_textures.has(p_param)) return default_textures[p_param]; @@ -101,52 +95,47 @@ Ref<Texture> Shader::get_default_texture_param(const StringName& p_param) const{ return Ref<Texture>(); } -void Shader::get_default_texture_param_list(List<StringName>* r_textures) const{ +void Shader::get_default_texture_param_list(List<StringName> *r_textures) const { - for(const Map<StringName,Ref<Texture> >::Element *E=default_textures.front();E;E=E->next()) { + for (const Map<StringName, Ref<Texture> >::Element *E = default_textures.front(); E; E = E->next()) { r_textures->push_back(E->key()); } - } -bool Shader::has_param(const StringName& p_param) const { +bool Shader::has_param(const StringName &p_param) const { return params_cache.has(p_param); } void Shader::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_mode"),&Shader::get_mode); + ClassDB::bind_method(D_METHOD("get_mode"), &Shader::get_mode); - ClassDB::bind_method(D_METHOD("set_code","code"),&Shader::set_code); - ClassDB::bind_method(D_METHOD("get_code"),&Shader::get_code); + ClassDB::bind_method(D_METHOD("set_code", "code"), &Shader::set_code); + ClassDB::bind_method(D_METHOD("get_code"), &Shader::get_code); - ClassDB::bind_method(D_METHOD("set_default_texture_param","param","texture:Texture"),&Shader::set_default_texture_param); - ClassDB::bind_method(D_METHOD("get_default_texture_param:Texture","param"),&Shader::get_default_texture_param); + ClassDB::bind_method(D_METHOD("set_default_texture_param", "param", "texture:Texture"), &Shader::set_default_texture_param); + ClassDB::bind_method(D_METHOD("get_default_texture_param:Texture", "param"), &Shader::get_default_texture_param); - ClassDB::bind_method(D_METHOD("has_param","name"),&Shader::has_param); + ClassDB::bind_method(D_METHOD("has_param", "name"), &Shader::has_param); //ClassDB::bind_method(D_METHOD("get_param_list"),&Shader::get_fragment_code); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_code", "get_code"); - ADD_PROPERTY( PropertyInfo(Variant::STRING, "code",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "set_code", "get_code") ; - - BIND_CONSTANT( MODE_SPATIAL); - BIND_CONSTANT( MODE_CANVAS_ITEM ); - BIND_CONSTANT( MODE_PARTICLES ); - + BIND_CONSTANT(MODE_SPATIAL); + BIND_CONSTANT(MODE_CANVAS_ITEM); + BIND_CONSTANT(MODE_PARTICLES); } Shader::Shader(Mode p_mode) { - mode=p_mode; + mode = p_mode; shader = VisualServer::get_singleton()->shader_create(VS::ShaderMode(p_mode)); - params_cache_dirty=true; + params_cache_dirty = true; } Shader::~Shader() { VisualServer::get_singleton()->free(shader); } - - diff --git a/scene/resources/shader.h b/scene/resources/shader.h index 59d7601d98..b7fa349dfe 100644 --- a/scene/resources/shader.h +++ b/scene/resources/shader.h @@ -29,14 +29,14 @@ #ifndef SHADER_H #define SHADER_H -#include "resource.h" #include "io/resource_loader.h" +#include "resource.h" #include "scene/resources/texture.h" class Shader : public Resource { - GDCLASS(Shader,Resource); - OBJ_SAVE_TYPE( Shader ); + GDCLASS(Shader, Resource); + OBJ_SAVE_TYPE(Shader); RES_BASE_EXTENSION("shd"); public: @@ -47,6 +47,7 @@ public: MODE_PARTICLES, MODE_MAX }; + private: RID shader; Mode mode; @@ -55,37 +56,31 @@ private: // shaders keep a list of ShaderMaterial -> VisualServer name translations, to make // convertion fast and save memory. mutable bool params_cache_dirty; - mutable Map<StringName,StringName> params_cache; //map a shader param to a material param.. - Map<StringName,Ref<Texture> > default_textures; - - + mutable Map<StringName, StringName> params_cache; //map a shader param to a material param.. + Map<StringName, Ref<Texture> > default_textures; protected: - - - static void _bind_methods(); -public: - +public: //void set_mode(Mode p_mode); Mode get_mode() const; - void set_code( const String& p_code); + void set_code(const String &p_code); String get_code() const; void get_param_list(List<PropertyInfo> *p_params) const; - bool has_param(const StringName& p_param) const; + bool has_param(const StringName &p_param) const; - void set_default_texture_param(const StringName& p_param, const Ref<Texture> &p_texture); - Ref<Texture> get_default_texture_param(const StringName& p_param) const; - void get_default_texture_param_list(List<StringName>* r_textures) const; + void set_default_texture_param(const StringName &p_param, const Ref<Texture> &p_texture); + Ref<Texture> get_default_texture_param(const StringName &p_param) const; + void get_default_texture_param_list(List<StringName> *r_textures) const; - _FORCE_INLINE_ StringName remap_param(const StringName& p_param) const { + _FORCE_INLINE_ StringName remap_param(const StringName &p_param) const { if (params_cache_dirty) get_param_list(NULL); - const Map<StringName,StringName>::Element *E=params_cache.find(p_param); + const Map<StringName, StringName>::Element *E = params_cache.find(p_param); if (E) return E->get(); return StringName(); @@ -95,38 +90,35 @@ public: Shader(Mode p_mode); ~Shader(); - }; -VARIANT_ENUM_CAST( Shader::Mode ); +VARIANT_ENUM_CAST(Shader::Mode); class SpatialShader : public Shader { - GDCLASS(SpatialShader,Shader); + GDCLASS(SpatialShader, Shader); public: - - SpatialShader() : Shader(MODE_SPATIAL) {}; + SpatialShader() + : Shader(MODE_SPATIAL){}; }; class CanvasItemShader : public Shader { - GDCLASS(CanvasItemShader,Shader); + GDCLASS(CanvasItemShader, Shader); public: - - CanvasItemShader() : Shader(MODE_CANVAS_ITEM) {}; + CanvasItemShader() + : Shader(MODE_CANVAS_ITEM){}; }; - class ParticlesShader : public Shader { - GDCLASS(ParticlesShader,Shader); + GDCLASS(ParticlesShader, Shader); public: - - ParticlesShader() : Shader(MODE_PARTICLES) {}; + ParticlesShader() + : Shader(MODE_PARTICLES){}; }; - #endif // SHADER_H diff --git a/scene/resources/shader_graph.cpp b/scene/resources/shader_graph.cpp index c21feb0bf5..49e987727d 100644 --- a/scene/resources/shader_graph.cpp +++ b/scene/resources/shader_graph.cpp @@ -397,7 +397,6 @@ void ShaderGraph::_bind_methods() { ADD_SIGNAL(MethodInfo("updated")); - #if 0 ClassDB::bind_method(D_METHOD("node_add"),&ShaderGraph::node_add ); ClassDB::bind_method(D_METHOD("node_remove"),&ShaderGraph::node_remove ); @@ -2076,32 +2075,32 @@ void ShaderGraph::_add_node_code(ShaderType p_type,Node *p_node,const Vector<Str const char *typestr[4]={"float","vec3","mat4","texture"}; -#define OUTNAME(id,slot) (String(typestr[get_node_output_slot_type(get_mode(),p_type,p_node->type,slot)])+" "+("nd"+itos(id)+"sl"+itos(slot))) -#define OUTVAR(id,slot) ("nd"+itos(id)+"sl"+itos(slot)) -#define DEF_VEC(slot)\ - if (p_inputs[slot].ends_with("def")){\ - Vector3 v = p_node->defaults[slot];\ - code+=String(typestr[1])+" "+p_inputs[slot]+"=vec3("+v+");\n";\ +#define OUTNAME(id, slot) (String(typestr[get_node_output_slot_type(get_mode(), p_type, p_node->type, slot)]) + " " + ("nd" + itos(id) + "sl" + itos(slot))) +#define OUTVAR(id, slot) ("nd" + itos(id) + "sl" + itos(slot)) +#define DEF_VEC(slot) \ + if (p_inputs[slot].ends_with("def")) { \ + Vector3 v = p_node->defaults[slot]; \ + code += String(typestr[1]) + " " + p_inputs[slot] + "=vec3(" + v + ");\n"; \ } -#define DEF_SCALAR(slot)\ - if (p_inputs[slot].ends_with("def")){\ - double v = p_node->defaults[slot];\ - code+=String(typestr[0])+" "+p_inputs[slot]+"="+rtos(v)+";\n";\ +#define DEF_SCALAR(slot) \ + if (p_inputs[slot].ends_with("def")) { \ + double v = p_node->defaults[slot]; \ + code += String(typestr[0]) + " " + p_inputs[slot] + "=" + rtos(v) + ";\n"; \ } -#define DEF_COLOR(slot)\ - if (p_inputs[slot].ends_with("def")){\ - Color col = p_node->defaults[slot];\ - code+=String(typestr[1])+" "+p_inputs[slot]+"=vec3("+rtos(col.r)+","+rtos(col.g)+","+rtos(col.b)+");\n";\ +#define DEF_COLOR(slot) \ + if (p_inputs[slot].ends_with("def")) { \ + Color col = p_node->defaults[slot]; \ + code += String(typestr[1]) + " " + p_inputs[slot] + "=vec3(" + rtos(col.r) + "," + rtos(col.g) + "," + rtos(col.b) + ");\n"; \ } -#define DEF_MATRIX(slot) \ - if (p_inputs[slot].ends_with("def")){\ - Transform xf = p_node->defaults[slot]; \ - code+=String(typestr[2])+" "+p_inputs[slot]+"=mat4(\n";\ - code+="\tvec4(vec3("+rtos(xf.basis.get_axis(0).x)+","+rtos(xf.basis.get_axis(0).y)+","+rtos(xf.basis.get_axis(0).z)+"),0),\n";\ - code+="\tvec4(vec3("+rtos(xf.basis.get_axis(1).x)+","+rtos(xf.basis.get_axis(1).y)+","+rtos(xf.basis.get_axis(1).z)+"),0),\n";\ - code+="\tvec4(vec3("+rtos(xf.basis.get_axis(2).x)+","+rtos(xf.basis.get_axis(2).y)+","+rtos(xf.basis.get_axis(2).z)+"),0),\n";\ - code+="\tvec4(vec3("+rtos(xf.origin.x)+","+rtos(xf.origin.y)+","+rtos(xf.origin.z)+"),1)\n";\ - code+=");\n";\ +#define DEF_MATRIX(slot) \ + if (p_inputs[slot].ends_with("def")) { \ + Transform xf = p_node->defaults[slot]; \ + code += String(typestr[2]) + " " + p_inputs[slot] + "=mat4(\n"; \ + code += "\tvec4(vec3(" + rtos(xf.basis.get_axis(0).x) + "," + rtos(xf.basis.get_axis(0).y) + "," + rtos(xf.basis.get_axis(0).z) + "),0),\n"; \ + code += "\tvec4(vec3(" + rtos(xf.basis.get_axis(1).x) + "," + rtos(xf.basis.get_axis(1).y) + "," + rtos(xf.basis.get_axis(1).z) + "),0),\n"; \ + code += "\tvec4(vec3(" + rtos(xf.basis.get_axis(2).x) + "," + rtos(xf.basis.get_axis(2).y) + "," + rtos(xf.basis.get_axis(2).z) + "),0),\n"; \ + code += "\tvec4(vec3(" + rtos(xf.origin.x) + "," + rtos(xf.origin.y) + "," + rtos(xf.origin.z) + "),1)\n"; \ + code += ");\n"; \ } switch(p_node->type) { diff --git a/scene/resources/shader_graph.h b/scene/resources/shader_graph.h index f4e24dbe78..190d76fce6 100644 --- a/scene/resources/shader_graph.h +++ b/scene/resources/shader_graph.h @@ -29,7 +29,6 @@ #ifndef SHADER_GRAPH_H #define SHADER_GRAPH_H - #if 0 #include "map.h" #include "scene/resources/shader.h" diff --git a/scene/resources/shape.cpp b/scene/resources/shape.cpp index a90c3b47a9..c666ff0cd3 100644 --- a/scene/resources/shape.cpp +++ b/scene/resources/shape.cpp @@ -28,25 +28,23 @@ /*************************************************************************/ #include "shape.h" -#include "servers/physics_server.h" -#include "scene/resources/mesh.h" #include "os/os.h" #include "scene/main/scene_main_loop.h" +#include "scene/resources/mesh.h" +#include "servers/physics_server.h" - -void Shape::add_vertices_to_array(PoolVector<Vector3> &array, const Transform& p_xform) { +void Shape::add_vertices_to_array(PoolVector<Vector3> &array, const Transform &p_xform) { Vector<Vector3> toadd = _gen_debug_mesh_lines(); if (toadd.size()) { - int base=array.size(); - array.resize(base+toadd.size()); + int base = array.size(); + array.resize(base + toadd.size()); PoolVector<Vector3>::Write w = array.write(); - for(int i=0;i<toadd.size();i++) { - w[i+base]=p_xform.xform(toadd[i]); + for (int i = 0; i < toadd.size(); i++) { + w[i + base] = p_xform.xform(toadd[i]); } - } } @@ -65,46 +63,39 @@ Ref<Mesh> Shape::get_debug_mesh() { array.resize(lines.size()); { - PoolVector<Vector3>::Write w=array.write(); - for(int i=0;i<lines.size();i++) { - w[i]=lines[i]; + PoolVector<Vector3>::Write w = array.write(); + for (int i = 0; i < lines.size(); i++) { + w[i] = lines[i]; } } Array arr; arr.resize(Mesh::ARRAY_MAX); - arr[Mesh::ARRAY_VERTEX]=array; + arr[Mesh::ARRAY_VERTEX] = array; - SceneTree *st=OS::get_singleton()->get_main_loop()->cast_to<SceneTree>(); + SceneTree *st = OS::get_singleton()->get_main_loop()->cast_to<SceneTree>(); - debug_mesh_cache->add_surface_from_arrays(Mesh::PRIMITIVE_LINES,arr); + debug_mesh_cache->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, arr); if (st) { - debug_mesh_cache->surface_set_material(0,st->get_debug_collision_material()); + debug_mesh_cache->surface_set_material(0, st->get_debug_collision_material()); } - } - - return debug_mesh_cache; - } Shape::Shape() { ERR_PRINT("Constructor must not be called!"); - } - Shape::Shape(RID p_shape) { - shape=p_shape; + shape = p_shape; } Shape::~Shape() { PhysicsServer::get_singleton()->free(shape); } - diff --git a/scene/resources/shape.h b/scene/resources/shape.h index 29a93b642c..8a8ecf1228 100644 --- a/scene/resources/shape.h +++ b/scene/resources/shape.h @@ -34,26 +34,24 @@ class Mesh; class Shape : public Resource { - GDCLASS( Shape, Resource ); - OBJ_SAVE_TYPE( Shape ); + GDCLASS(Shape, Resource); + OBJ_SAVE_TYPE(Shape); RES_BASE_EXTENSION("shp"); RID shape; Ref<Mesh> debug_mesh_cache; protected: - _FORCE_INLINE_ RID get_shape() const { return shape; } Shape(RID p_shape); - virtual Vector<Vector3> _gen_debug_mesh_lines()=0;// { return Vector<Vector3>(); } + virtual Vector<Vector3> _gen_debug_mesh_lines() = 0; // { return Vector<Vector3>(); } public: - virtual RID get_rid() const { return shape; } Ref<Mesh> get_debug_mesh(); - void add_vertices_to_array(PoolVector<Vector3> &array, const Transform& p_xform); + void add_vertices_to_array(PoolVector<Vector3> &array, const Transform &p_xform); Shape(); ~Shape(); diff --git a/scene/resources/shape_2d.cpp b/scene/resources/shape_2d.cpp index ec1568e218..497110c6f9 100644 --- a/scene/resources/shape_2d.cpp +++ b/scene/resources/shape_2d.cpp @@ -33,96 +33,84 @@ RID Shape2D::get_rid() const { return shape; } - void Shape2D::set_custom_solver_bias(real_t p_bias) { - custom_bias=p_bias; - Physics2DServer::get_singleton()->shape_set_custom_solver_bias(shape,custom_bias); + custom_bias = p_bias; + Physics2DServer::get_singleton()->shape_set_custom_solver_bias(shape, custom_bias); } -real_t Shape2D::get_custom_solver_bias() const{ +real_t Shape2D::get_custom_solver_bias() const { return custom_bias; - } +bool Shape2D::collide_with_motion(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion) { -bool Shape2D::collide_with_motion(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_shape_motion) { - - ERR_FAIL_COND_V(p_shape.is_null(),false); + ERR_FAIL_COND_V(p_shape.is_null(), false); int r; - return Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,p_local_motion,p_shape->get_rid(),p_shape_xform,p_shape_motion,NULL,0,r); + return Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, p_local_motion, p_shape->get_rid(), p_shape_xform, p_shape_motion, NULL, 0, r); } -bool Shape2D::collide(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform){ - ERR_FAIL_COND_V(p_shape.is_null(),false); +bool Shape2D::collide(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform) { + ERR_FAIL_COND_V(p_shape.is_null(), false); int r; - return Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,Vector2(),p_shape->get_rid(),p_shape_xform,Vector2(),NULL,0,r); - - + return Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, Vector2(), p_shape->get_rid(), p_shape_xform, Vector2(), NULL, 0, r); } -Variant Shape2D::collide_with_motion_and_get_contacts(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_shape_motion){ +Variant Shape2D::collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion) { - ERR_FAIL_COND_V(p_shape.is_null(),Variant()); + ERR_FAIL_COND_V(p_shape.is_null(), Variant()); const int max_contacts = 16; - Vector2 result[max_contacts*2]; - int contacts=0; + Vector2 result[max_contacts * 2]; + int contacts = 0; - if (!Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,p_local_motion,p_shape->get_rid(),p_shape_xform,p_shape_motion,result,max_contacts,contacts)) + if (!Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, p_local_motion, p_shape->get_rid(), p_shape_xform, p_shape_motion, result, max_contacts, contacts)) return Variant(); Array results; - results.resize(contacts*2); - for(int i=0;i<contacts;i++) { - results[i]=result[i]; + results.resize(contacts * 2); + for (int i = 0; i < contacts; i++) { + results[i] = result[i]; } return results; - } -Variant Shape2D::collide_and_get_contacts(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform){ +Variant Shape2D::collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform) { - ERR_FAIL_COND_V(p_shape.is_null(),Variant()); + ERR_FAIL_COND_V(p_shape.is_null(), Variant()); const int max_contacts = 16; - Vector2 result[max_contacts*2]; - int contacts=0; + Vector2 result[max_contacts * 2]; + int contacts = 0; - if (!Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,Vector2(),p_shape->get_rid(),p_shape_xform,Vector2(),result,max_contacts,contacts)) + if (!Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, Vector2(), p_shape->get_rid(), p_shape_xform, Vector2(), result, max_contacts, contacts)) return Variant(); Array results; - results.resize(contacts*2); - for(int i=0;i<contacts;i++) { - results[i]=result[i]; + results.resize(contacts * 2); + for (int i = 0; i < contacts; i++) { + results[i] = result[i]; } return results; - - } void Shape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_custom_solver_bias","bias"),&Shape2D::set_custom_solver_bias); - ClassDB::bind_method(D_METHOD("get_custom_solver_bias"),&Shape2D::get_custom_solver_bias); - ClassDB::bind_method(D_METHOD("collide","local_xform","with_shape:Shape2D","shape_xform"),&Shape2D::collide); - ClassDB::bind_method(D_METHOD("collide_with_motion","local_xform","local_motion","with_shape:Shape2D","shape_xform","shape_motion"),&Shape2D::collide_with_motion); - ClassDB::bind_method(D_METHOD("collide_and_get_contacts:Variant","local_xform","with_shape:Shape2D","shape_xform"),&Shape2D::collide_and_get_contacts); - ClassDB::bind_method(D_METHOD("collide_with_motion_and_get_contacts:Variant","local_xform","local_motion","with_shape:Shape2D","shape_xform","shape_motion"),&Shape2D::collide_with_motion_and_get_contacts); + ClassDB::bind_method(D_METHOD("set_custom_solver_bias", "bias"), &Shape2D::set_custom_solver_bias); + ClassDB::bind_method(D_METHOD("get_custom_solver_bias"), &Shape2D::get_custom_solver_bias); + ClassDB::bind_method(D_METHOD("collide", "local_xform", "with_shape:Shape2D", "shape_xform"), &Shape2D::collide); + ClassDB::bind_method(D_METHOD("collide_with_motion", "local_xform", "local_motion", "with_shape:Shape2D", "shape_xform", "shape_motion"), &Shape2D::collide_with_motion); + ClassDB::bind_method(D_METHOD("collide_and_get_contacts:Variant", "local_xform", "with_shape:Shape2D", "shape_xform"), &Shape2D::collide_and_get_contacts); + ClassDB::bind_method(D_METHOD("collide_with_motion_and_get_contacts:Variant", "local_xform", "local_motion", "with_shape:Shape2D", "shape_xform", "shape_motion"), &Shape2D::collide_with_motion_and_get_contacts); - ADD_PROPERTY( PropertyInfo(Variant::REAL,"custom_solver_bias",PROPERTY_HINT_RANGE,"0,1,0.001"),"set_custom_solver_bias","get_custom_solver_bias"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "custom_solver_bias", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_custom_solver_bias", "get_custom_solver_bias"); } - - -Shape2D::Shape2D(const RID& p_rid) { - shape=p_rid; - custom_bias=0; +Shape2D::Shape2D(const RID &p_rid) { + shape = p_rid; + custom_bias = 0; } - - Shape2D::~Shape2D() { Physics2DServer::get_singleton()->free(shape); diff --git a/scene/resources/shape_2d.h b/scene/resources/shape_2d.h index 6a7ec03a9a..afae74c385 100644 --- a/scene/resources/shape_2d.h +++ b/scene/resources/shape_2d.h @@ -32,28 +32,27 @@ #include "resource.h" class Shape2D : public Resource { - GDCLASS( Shape2D, Resource ); - OBJ_SAVE_TYPE( Shape2D ); + GDCLASS(Shape2D, Resource); + OBJ_SAVE_TYPE(Shape2D); RID shape; real_t custom_bias; -protected: - +protected: static void _bind_methods(); - Shape2D(const RID& p_rid); -public: + Shape2D(const RID &p_rid); +public: void set_custom_solver_bias(real_t p_bias); real_t get_custom_solver_bias() const; - bool collide_with_motion(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_p_shape_motion); - bool collide(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform); + bool collide_with_motion(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_p_shape_motion); + bool collide(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform); - Variant collide_with_motion_and_get_contacts(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_p_shape_motion); - Variant collide_and_get_contacts(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform); + Variant collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_p_shape_motion); + Variant collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform); - virtual void draw(const RID& p_to_rid,const Color& p_color) {} + virtual void draw(const RID &p_to_rid, const Color &p_color) {} virtual Rect2 get_rect() const { return Rect2(); } virtual RID get_rid() const; Shape2D(); diff --git a/scene/resources/shape_line_2d.cpp b/scene/resources/shape_line_2d.cpp index 64e50e62c8..777dbead52 100644 --- a/scene/resources/shape_line_2d.cpp +++ b/scene/resources/shape_line_2d.cpp @@ -34,23 +34,20 @@ void LineShape2D::_update_shape() { Array arr; arr.push_back(normal); arr.push_back(d); - Physics2DServer::get_singleton()->shape_set_data(get_rid(),arr); + Physics2DServer::get_singleton()->shape_set_data(get_rid(), arr); emit_changed(); - } -void LineShape2D::set_normal(const Vector2& p_normal) { +void LineShape2D::set_normal(const Vector2 &p_normal) { - normal=p_normal; + normal = p_normal; _update_shape(); - } void LineShape2D::set_d(real_t p_d) { - d=p_d; + d = p_d; _update_shape(); - } Vector2 LineShape2D::get_normal() const { @@ -62,48 +59,45 @@ real_t LineShape2D::get_d() const { return d; } - -void LineShape2D::draw(const RID& p_to_rid,const Color& p_color) { +void LineShape2D::draw(const RID &p_to_rid, const Color &p_color) { Vector2 point = get_d() * get_normal(); - Vector2 l1[2]={point-get_normal().tangent()*100,point+get_normal().tangent()*100}; - VS::get_singleton()->canvas_item_add_line(p_to_rid,l1[0],l1[1],p_color,3); - Vector2 l2[2]={point,point+get_normal()*30}; - VS::get_singleton()->canvas_item_add_line(p_to_rid,l2[0],l2[1],p_color,3); - + Vector2 l1[2] = { point - get_normal().tangent() * 100, point + get_normal().tangent() * 100 }; + VS::get_singleton()->canvas_item_add_line(p_to_rid, l1[0], l1[1], p_color, 3); + Vector2 l2[2] = { point, point + get_normal() * 30 }; + VS::get_singleton()->canvas_item_add_line(p_to_rid, l2[0], l2[1], p_color, 3); } -Rect2 LineShape2D::get_rect() const{ +Rect2 LineShape2D::get_rect() const { Vector2 point = get_d() * get_normal(); - Vector2 l1[2]={point-get_normal().tangent()*100,point+get_normal().tangent()*100}; - Vector2 l2[2]={point,point+get_normal()*30}; + Vector2 l1[2] = { point - get_normal().tangent() * 100, point + get_normal().tangent() * 100 }; + Vector2 l2[2] = { point, point + get_normal() * 30 }; Rect2 rect; - rect.pos=l1[0]; + rect.pos = l1[0]; rect.expand_to(l1[1]); rect.expand_to(l2[0]); rect.expand_to(l2[1]); return rect; - } void LineShape2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_normal","normal"),&LineShape2D::set_normal); - ClassDB::bind_method(D_METHOD("get_normal"),&LineShape2D::get_normal); - - ClassDB::bind_method(D_METHOD("set_d","d"),&LineShape2D::set_d); - ClassDB::bind_method(D_METHOD("get_d"),&LineShape2D::get_d); + ClassDB::bind_method(D_METHOD("set_normal", "normal"), &LineShape2D::set_normal); + ClassDB::bind_method(D_METHOD("get_normal"), &LineShape2D::get_normal); - ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"normal"),"set_normal","get_normal") ; - ADD_PROPERTY( PropertyInfo(Variant::REAL,"d"),"set_d","get_d") ; + ClassDB::bind_method(D_METHOD("set_d", "d"), &LineShape2D::set_d); + ClassDB::bind_method(D_METHOD("get_d"), &LineShape2D::get_d); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "normal"), "set_normal", "get_normal"); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "d"), "set_d", "get_d"); } -LineShape2D::LineShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_LINE)) { +LineShape2D::LineShape2D() + : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_LINE)) { - normal=Vector2(0,-1); - d=0; + normal = Vector2(0, -1); + d = 0; _update_shape(); } diff --git a/scene/resources/shape_line_2d.h b/scene/resources/shape_line_2d.h index abad5f6a24..cd62504d81 100644 --- a/scene/resources/shape_line_2d.h +++ b/scene/resources/shape_line_2d.h @@ -32,24 +32,24 @@ #include "scene/resources/shape_2d.h" class LineShape2D : public Shape2D { - GDCLASS( LineShape2D, Shape2D ); + GDCLASS(LineShape2D, Shape2D); Vector2 normal; real_t d; void _update_shape(); -protected: +protected: static void _bind_methods(); -public: - void set_normal(const Vector2& p_normal); +public: + void set_normal(const Vector2 &p_normal); void set_d(real_t p_d); Vector2 get_normal() const; real_t get_d() const; - virtual void draw(const RID& p_to_rid,const Color& p_color); + virtual void draw(const RID &p_to_rid, const Color &p_color); virtual Rect2 get_rect() const; LineShape2D(); diff --git a/scene/resources/sky_box.cpp b/scene/resources/sky_box.cpp index 0f8a1e5339..cb3b1cf60d 100644 --- a/scene/resources/sky_box.cpp +++ b/scene/resources/sky_box.cpp @@ -29,11 +29,10 @@ #include "sky_box.h" #include "io/image_loader.h" - void SkyBox::set_radiance_size(RadianceSize p_size) { - ERR_FAIL_INDEX(p_size,RADIANCE_SIZE_MAX); + ERR_FAIL_INDEX(p_size, RADIANCE_SIZE_MAX); - radiance_size=p_size; + radiance_size = p_size; _radiance_changed(); } @@ -44,94 +43,87 @@ SkyBox::RadianceSize SkyBox::get_radiance_size() const { void SkyBox::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_radiance_size","size"),&SkyBox::set_radiance_size); - ClassDB::bind_method(D_METHOD("get_radiance_size"),&SkyBox::get_radiance_size); - - ADD_PROPERTY(PropertyInfo(Variant::INT,"radiance_size",PROPERTY_HINT_ENUM,"256,512,1024,2048"),"set_radiance_size","get_radiance_size"); + ClassDB::bind_method(D_METHOD("set_radiance_size", "size"), &SkyBox::set_radiance_size); + ClassDB::bind_method(D_METHOD("get_radiance_size"), &SkyBox::get_radiance_size); + ADD_PROPERTY(PropertyInfo(Variant::INT, "radiance_size", PROPERTY_HINT_ENUM, "256,512,1024,2048"), "set_radiance_size", "get_radiance_size"); - BIND_CONSTANT( RADIANCE_SIZE_256 ); - BIND_CONSTANT( RADIANCE_SIZE_512 ); - BIND_CONSTANT( RADIANCE_SIZE_1024 ); - BIND_CONSTANT( RADIANCE_SIZE_2048 ); - BIND_CONSTANT( RADIANCE_SIZE_MAX ); + BIND_CONSTANT(RADIANCE_SIZE_256); + BIND_CONSTANT(RADIANCE_SIZE_512); + BIND_CONSTANT(RADIANCE_SIZE_1024); + BIND_CONSTANT(RADIANCE_SIZE_2048); + BIND_CONSTANT(RADIANCE_SIZE_MAX); } -SkyBox::SkyBox() -{ - radiance_size=RADIANCE_SIZE_512; +SkyBox::SkyBox() { + radiance_size = RADIANCE_SIZE_512; } ///////////////////////////////////////// - - void ImageSkyBox::_radiance_changed() { if (cube_map_valid) { - static const int size[RADIANCE_SIZE_MAX]={ - 256,512,1024,2048 + static const int size[RADIANCE_SIZE_MAX] = { + 256, 512, 1024, 2048 }; - VS::get_singleton()->skybox_set_texture(sky_box,cube_map,size[get_radiance_size()]); + VS::get_singleton()->skybox_set_texture(sky_box, cube_map, size[get_radiance_size()]); } } -void ImageSkyBox::set_image_path(ImagePath p_image,const String &p_path) { +void ImageSkyBox::set_image_path(ImagePath p_image, const String &p_path) { - ERR_FAIL_INDEX(p_image,IMAGE_PATH_MAX); - image_path[p_image]=p_path; + ERR_FAIL_INDEX(p_image, IMAGE_PATH_MAX); + image_path[p_image] = p_path; - bool all_ok=true; - for(int i=0;i<IMAGE_PATH_MAX;i++) { - if (image_path[i]==String()) { - all_ok=false; + bool all_ok = true; + for (int i = 0; i < IMAGE_PATH_MAX; i++) { + if (image_path[i] == String()) { + all_ok = false; } } - cube_map_valid=false; + cube_map_valid = false; if (all_ok) { Image images[IMAGE_PATH_MAX]; - int w=0,h=0; + int w = 0, h = 0; Image::Format format; - for(int i=0;i<IMAGE_PATH_MAX;i++) { - Error err = ImageLoader::load_image(image_path[i],&images[i]); + for (int i = 0; i < IMAGE_PATH_MAX; i++) { + Error err = ImageLoader::load_image(image_path[i], &images[i]); if (err) { - ERR_PRINTS("Error loading image for skybox: "+image_path[i]); + ERR_PRINTS("Error loading image for skybox: " + image_path[i]); return; } - if (i==0) { - w=images[0].get_width(); - h=images[0].get_height(); - format=images[0].get_format(); + if (i == 0) { + w = images[0].get_width(); + h = images[0].get_height(); + format = images[0].get_format(); } else { - if (images[i].get_width()!=w || images[i].get_height()!=h || images[i].get_format()!=format) { - ERR_PRINTS("Image size mismatch ("+itos(images[i].get_width())+","+itos(images[i].get_height())+":"+Image::get_format_name(images[i].get_format())+" when it should be "+itos(w)+","+itos(h)+":"+Image::get_format_name(format)+"): "+image_path[i]); + if (images[i].get_width() != w || images[i].get_height() != h || images[i].get_format() != format) { + ERR_PRINTS("Image size mismatch (" + itos(images[i].get_width()) + "," + itos(images[i].get_height()) + ":" + Image::get_format_name(images[i].get_format()) + " when it should be " + itos(w) + "," + itos(h) + ":" + Image::get_format_name(format) + "): " + image_path[i]); return; } } } - VS::get_singleton()->texture_allocate(cube_map,w,h,format,VS::TEXTURE_FLAG_FILTER|VS::TEXTURE_FLAG_CUBEMAP|VS::TEXTURE_FLAG_MIPMAPS); - for(int i=0;i<IMAGE_PATH_MAX;i++) { - VS::get_singleton()->texture_set_data(cube_map,images[i],VS::CubeMapSide(i)); + VS::get_singleton()->texture_allocate(cube_map, w, h, format, VS::TEXTURE_FLAG_FILTER | VS::TEXTURE_FLAG_CUBEMAP | VS::TEXTURE_FLAG_MIPMAPS); + for (int i = 0; i < IMAGE_PATH_MAX; i++) { + VS::get_singleton()->texture_set_data(cube_map, images[i], VS::CubeMapSide(i)); } - cube_map_valid=true; + cube_map_valid = true; _radiance_changed(); } - - } String ImageSkyBox::get_image_path(ImagePath p_image) const { - ERR_FAIL_INDEX_V(p_image,IMAGE_PATH_MAX,String()); + ERR_FAIL_INDEX_V(p_image, IMAGE_PATH_MAX, String()); return image_path[p_image]; - } RID ImageSkyBox::get_rid() const { @@ -141,42 +133,41 @@ RID ImageSkyBox::get_rid() const { void ImageSkyBox::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_image_path","image","path"),&ImageSkyBox::set_image_path); - ClassDB::bind_method(D_METHOD("get_image_path","image"),&ImageSkyBox::get_image_path); + ClassDB::bind_method(D_METHOD("set_image_path", "image", "path"), &ImageSkyBox::set_image_path); + ClassDB::bind_method(D_METHOD("get_image_path", "image"), &ImageSkyBox::get_image_path); List<String> extensions; ImageLoader::get_recognized_extensions(&extensions); String hints; - for(List<String>::Element *E=extensions.front();E;E=E->next()) { - if (hints!=String()) { - hints+=","; + for (List<String>::Element *E = extensions.front(); E; E = E->next()) { + if (hints != String()) { + hints += ","; } - hints+="*."+E->get(); + hints += "*." + E->get(); } - ADD_GROUP("Image Path","image_path_"); - ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_x",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_NEGATIVE_X); - ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_x",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_POSITIVE_X); - ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_y",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_NEGATIVE_Y); - ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_y",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_POSITIVE_Y); - ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_z",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_NEGATIVE_Z); - ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_z",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_POSITIVE_Z); - - BIND_CONSTANT( IMAGE_PATH_NEGATIVE_X ); - BIND_CONSTANT( IMAGE_PATH_POSITIVE_X ); - BIND_CONSTANT( IMAGE_PATH_NEGATIVE_Y ); - BIND_CONSTANT( IMAGE_PATH_POSITIVE_Y ); - BIND_CONSTANT( IMAGE_PATH_NEGATIVE_Z ); - BIND_CONSTANT( IMAGE_PATH_POSITIVE_Z ); - BIND_CONSTANT( IMAGE_PATH_MAX ); - + ADD_GROUP("Image Path", "image_path_"); + ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_negative_x", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_NEGATIVE_X); + ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_positive_x", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_POSITIVE_X); + ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_negative_y", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_NEGATIVE_Y); + ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_positive_y", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_POSITIVE_Y); + ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_negative_z", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_NEGATIVE_Z); + ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_positive_z", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_POSITIVE_Z); + + BIND_CONSTANT(IMAGE_PATH_NEGATIVE_X); + BIND_CONSTANT(IMAGE_PATH_POSITIVE_X); + BIND_CONSTANT(IMAGE_PATH_NEGATIVE_Y); + BIND_CONSTANT(IMAGE_PATH_POSITIVE_Y); + BIND_CONSTANT(IMAGE_PATH_NEGATIVE_Z); + BIND_CONSTANT(IMAGE_PATH_POSITIVE_Z); + BIND_CONSTANT(IMAGE_PATH_MAX); } ImageSkyBox::ImageSkyBox() { - cube_map=VS::get_singleton()->texture_create(); - sky_box=VS::get_singleton()->skybox_create(); - cube_map_valid=false; + cube_map = VS::get_singleton()->texture_create(); + sky_box = VS::get_singleton()->skybox_create(); + cube_map_valid = false; } ImageSkyBox::~ImageSkyBox() { @@ -184,4 +175,3 @@ ImageSkyBox::~ImageSkyBox() { VS::get_singleton()->free(cube_map); VS::get_singleton()->free(sky_box); } - diff --git a/scene/resources/sky_box.h b/scene/resources/sky_box.h index 171782d132..23ba077df3 100644 --- a/scene/resources/sky_box.h +++ b/scene/resources/sky_box.h @@ -32,10 +32,9 @@ #include "scene/resources/texture.h" class SkyBox : public Resource { - GDCLASS(SkyBox,Resource); + GDCLASS(SkyBox, Resource); public: - enum RadianceSize { RADIANCE_SIZE_256, RADIANCE_SIZE_512, @@ -43,14 +42,15 @@ public: RADIANCE_SIZE_2048, RADIANCE_SIZE_MAX }; -private: +private: RadianceSize radiance_size; + protected: static void _bind_methods(); - virtual void _radiance_changed()=0; -public: + virtual void _radiance_changed() = 0; +public: void set_radiance_size(RadianceSize p_size); RadianceSize get_radiance_size() const; SkyBox(); @@ -58,12 +58,10 @@ public: VARIANT_ENUM_CAST(SkyBox::RadianceSize) - class ImageSkyBox : public SkyBox { - GDCLASS(ImageSkyBox,SkyBox); + GDCLASS(ImageSkyBox, SkyBox); public: - enum ImagePath { IMAGE_PATH_NEGATIVE_X, IMAGE_PATH_POSITIVE_X, @@ -73,17 +71,19 @@ public: IMAGE_PATH_POSITIVE_Z, IMAGE_PATH_MAX }; + private: RID cube_map; RID sky_box; bool cube_map_valid; String image_path[IMAGE_PATH_MAX]; + protected: static void _bind_methods(); virtual void _radiance_changed(); -public: +public: void set_image_path(ImagePath p_image, const String &p_path); String get_image_path(ImagePath p_image) const; @@ -95,5 +95,4 @@ public: VARIANT_ENUM_CAST(ImageSkyBox::ImagePath) - #endif // SKYBOX_H diff --git a/scene/resources/space_2d.cpp b/scene/resources/space_2d.cpp index f1fe9629dd..d0a18b98bd 100644 --- a/scene/resources/space_2d.cpp +++ b/scene/resources/space_2d.cpp @@ -33,11 +33,10 @@ RID Space2D::get_rid() const { return space; } - void Space2D::set_active(bool p_active) { - active=p_active; - Physics2DServer::get_singleton()->space_set_active(space,active); + active = p_active; + Physics2DServer::get_singleton()->space_set_active(space, active); } bool Space2D::is_active() const { @@ -45,24 +44,21 @@ bool Space2D::is_active() const { return active; } - void Space2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_active","active"),&Space2D::set_active); - ClassDB::bind_method(D_METHOD("is_active"),&Space2D::is_active); - - ADD_PROPERTY( PropertyInfo(Variant::BOOL,"active"),"set_active","is_active") ; + ClassDB::bind_method(D_METHOD("set_active", "active"), &Space2D::set_active); + ClassDB::bind_method(D_METHOD("is_active"), &Space2D::is_active); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "active"), "set_active", "is_active"); } Space2D::Space2D() { - active=false; - space=Physics2DServer::get_singleton()->space_create(); + active = false; + space = Physics2DServer::get_singleton()->space_create(); } Space2D::~Space2D() { Physics2DServer::get_singleton()->free(space); } - diff --git a/scene/resources/space_2d.h b/scene/resources/space_2d.h index 82aef89c07..b6c2607b13 100644 --- a/scene/resources/space_2d.h +++ b/scene/resources/space_2d.h @@ -29,21 +29,19 @@ #ifndef SPACE_2D_H #define SPACE_2D_H -#include "servers/physics_2d_server.h" #include "resource.h" - +#include "servers/physics_2d_server.h" class Space2D : public Resource { - GDCLASS(Space2D,Resource); + GDCLASS(Space2D, Resource); bool active; RID space; -protected: +protected: static void _bind_methods(); -public: - +public: void set_active(bool p_active); bool is_active() const; diff --git a/scene/resources/sphere_shape.cpp b/scene/resources/sphere_shape.cpp index 3029625928..c242e748a4 100644 --- a/scene/resources/sphere_shape.cpp +++ b/scene/resources/sphere_shape.cpp @@ -31,24 +31,23 @@ Vector<Vector3> SphereShape::_gen_debug_mesh_lines() { - float r=get_radius(); + float r = get_radius(); Vector<Vector3> points; - for(int i=0;i<=360;i++) { + for (int i = 0; i <= 360; i++) { - float ra=Math::deg2rad((float)i); - float rb=Math::deg2rad((float)i+1); - Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*r; - Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*r; - - points.push_back(Vector3(a.x,0,a.y)); - points.push_back(Vector3(b.x,0,b.y)); - points.push_back(Vector3(0,a.x,a.y)); - points.push_back(Vector3(0,b.x,b.y)); - points.push_back(Vector3(a.x,a.y,0)); - points.push_back(Vector3(b.x,b.y,0)); + float ra = Math::deg2rad((float)i); + float rb = Math::deg2rad((float)i + 1); + Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * r; + Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * r; + points.push_back(Vector3(a.x, 0, a.y)); + points.push_back(Vector3(b.x, 0, b.y)); + points.push_back(Vector3(0, a.x, a.y)); + points.push_back(Vector3(0, b.x, b.y)); + points.push_back(Vector3(a.x, a.y, 0)); + points.push_back(Vector3(b.x, b.y, 0)); } return points; @@ -56,12 +55,12 @@ Vector<Vector3> SphereShape::_gen_debug_mesh_lines() { void SphereShape::_update_shape() { - PhysicsServer::get_singleton()->shape_set_data(get_shape(),radius); + PhysicsServer::get_singleton()->shape_set_data(get_shape(), radius); } void SphereShape::set_radius(float p_radius) { - radius=p_radius; + radius = p_radius; _update_shape(); notify_change_to_owners(); _change_notify("radius"); @@ -72,17 +71,16 @@ float SphereShape::get_radius() const { return radius; } - void SphereShape::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_radius","radius"),&SphereShape::set_radius); - ClassDB::bind_method(D_METHOD("get_radius"),&SphereShape::get_radius); - - ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0,4096,0.01"), "set_radius", "get_radius"); + ClassDB::bind_method(D_METHOD("set_radius", "radius"), &SphereShape::set_radius); + ClassDB::bind_method(D_METHOD("get_radius"), &SphereShape::get_radius); + ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_radius", "get_radius"); } -SphereShape::SphereShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_SPHERE)) { +SphereShape::SphereShape() + : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_SPHERE)) { set_radius(1.0); } diff --git a/scene/resources/sphere_shape.h b/scene/resources/sphere_shape.h index 990564be80..576c59ee7d 100644 --- a/scene/resources/sphere_shape.h +++ b/scene/resources/sphere_shape.h @@ -29,22 +29,20 @@ #ifndef SPHERE_SHAPE_H #define SPHERE_SHAPE_H - #include "scene/resources/shape.h" class SphereShape : public Shape { - GDCLASS(SphereShape,Shape); + GDCLASS(SphereShape, Shape); float radius; protected: - static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); -public: +public: void set_radius(float p_radius); float get_radius() const; diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp index 34a4202942..7a503207bc 100644 --- a/scene/resources/style_box.cpp +++ b/scene/resources/style_box.cpp @@ -28,25 +28,24 @@ /*************************************************************************/ #include "style_box.h" -bool StyleBox::test_mask(const Point2& p_point, const Rect2& p_rect) const { +bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const { return true; } void StyleBox::set_default_margin(Margin p_margin, float p_value) { - margin[p_margin]=p_value; + margin[p_margin] = p_value; emit_changed(); - } -float StyleBox::get_default_margin(Margin p_margin) const{ +float StyleBox::get_default_margin(Margin p_margin) const { return margin[p_margin]; } float StyleBox::get_margin(Margin p_margin) const { - if (margin[p_margin]<0) + if (margin[p_margin] < 0) return get_style_margin(p_margin); else return margin[p_margin]; @@ -54,13 +53,12 @@ float StyleBox::get_margin(Margin p_margin) const { Size2 StyleBox::get_minimum_size() const { - return Size2( get_margin( MARGIN_LEFT) + get_margin( MARGIN_RIGHT ) , get_margin( MARGIN_TOP) + get_margin( MARGIN_BOTTOM ) ); + return Size2(get_margin(MARGIN_LEFT) + get_margin(MARGIN_RIGHT), get_margin(MARGIN_TOP) + get_margin(MARGIN_BOTTOM)); } - Point2 StyleBox::get_offset() const { - return Point2( get_margin( MARGIN_LEFT), get_margin( MARGIN_TOP) ); + return Point2(get_margin(MARGIN_LEFT), get_margin(MARGIN_TOP)); } Size2 StyleBox::get_center_size() const { @@ -70,58 +68,53 @@ Size2 StyleBox::get_center_size() const { void StyleBox::_bind_methods() { - ClassDB::bind_method(D_METHOD("test_mask","point","rect"),&StyleBox::test_mask); + ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask); - ClassDB::bind_method(D_METHOD("set_default_margin","margin","offset"),&StyleBox::set_default_margin); - ClassDB::bind_method(D_METHOD("get_default_margin","margin"),&StyleBox::get_default_margin); + ClassDB::bind_method(D_METHOD("set_default_margin", "margin", "offset"), &StyleBox::set_default_margin); + ClassDB::bind_method(D_METHOD("get_default_margin", "margin"), &StyleBox::get_default_margin); //ClassDB::bind_method(D_METHOD("set_default_margin"),&StyleBox::set_default_margin); //ClassDB::bind_method(D_METHOD("get_default_margin"),&StyleBox::get_default_margin); - ClassDB::bind_method(D_METHOD("get_margin","margin"),&StyleBox::get_margin); - ClassDB::bind_method(D_METHOD("get_minimum_size"),&StyleBox::get_minimum_size); - ClassDB::bind_method(D_METHOD("get_center_size"),&StyleBox::get_center_size); - ClassDB::bind_method(D_METHOD("get_offset"),&StyleBox::get_offset); - - ClassDB::bind_method(D_METHOD("draw","canvas_item","rect"),&StyleBox::draw); - - ADD_GROUP("Content Margin","content_margin_"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_left", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_LEFT ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_right", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_RIGHT ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_top", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_TOP); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_bottom", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_BOTTOM ); + ClassDB::bind_method(D_METHOD("get_margin", "margin"), &StyleBox::get_margin); + ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size); + ClassDB::bind_method(D_METHOD("get_center_size"), &StyleBox::get_center_size); + ClassDB::bind_method(D_METHOD("get_offset"), &StyleBox::get_offset); + ClassDB::bind_method(D_METHOD("draw", "canvas_item", "rect"), &StyleBox::draw); + ADD_GROUP("Content Margin", "content_margin_"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_BOTTOM); } StyleBox::StyleBox() { - for (int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - margin[i]=-1; + margin[i] = -1; } } - void StyleBoxTexture::set_texture(RES p_texture) { - if (texture==p_texture) + if (texture == p_texture) return; - texture=p_texture; + texture = p_texture; emit_signal("texture_changed"); emit_changed(); - } RES StyleBoxTexture::get_texture() const { return texture; } -void StyleBoxTexture::set_margin_size(Margin p_margin,float p_size) { +void StyleBoxTexture::set_margin_size(Margin p_margin, float p_size) { - margin[p_margin]=p_size; + margin[p_margin] = p_size; emit_changed(); - } float StyleBoxTexture::get_margin_size(Margin p_margin) const { @@ -133,23 +126,22 @@ float StyleBoxTexture::get_style_margin(Margin p_margin) const { return margin[p_margin]; } -void StyleBoxTexture::draw(RID p_canvas_item,const Rect2& p_rect) const { +void StyleBoxTexture::draw(RID p_canvas_item, const Rect2 &p_rect) const { if (texture.is_null()) return; - Rect2 r=p_rect; - r.pos.x-=expand_margin[MARGIN_LEFT]; - r.pos.y-=expand_margin[MARGIN_TOP]; - r.size.x+=expand_margin[MARGIN_LEFT]+expand_margin[MARGIN_RIGHT]; - r.size.y+=expand_margin[MARGIN_TOP]+expand_margin[MARGIN_BOTTOM]; - VisualServer::get_singleton()->canvas_item_add_nine_patch( p_canvas_item,r,region_rect,texture->get_rid(),Vector2(margin[MARGIN_LEFT],margin[MARGIN_TOP]),Vector2(margin[MARGIN_RIGHT],margin[MARGIN_BOTTOM]),VS::NINE_PATCH_STRETCH,VS::NINE_PATCH_STRETCH,draw_center,modulate); + Rect2 r = p_rect; + r.pos.x -= expand_margin[MARGIN_LEFT]; + r.pos.y -= expand_margin[MARGIN_TOP]; + r.size.x += expand_margin[MARGIN_LEFT] + expand_margin[MARGIN_RIGHT]; + r.size.y += expand_margin[MARGIN_TOP] + expand_margin[MARGIN_BOTTOM]; + VisualServer::get_singleton()->canvas_item_add_nine_patch(p_canvas_item, r, region_rect, texture->get_rid(), Vector2(margin[MARGIN_LEFT], margin[MARGIN_TOP]), Vector2(margin[MARGIN_RIGHT], margin[MARGIN_BOTTOM]), VS::NINE_PATCH_STRETCH, VS::NINE_PATCH_STRETCH, draw_center, modulate); } void StyleBoxTexture::set_draw_center(bool p_draw) { - draw_center=p_draw; + draw_center = p_draw; emit_changed(); - } bool StyleBoxTexture::get_draw_center() const { @@ -165,26 +157,25 @@ Size2 StyleBoxTexture::get_center_size() const { return texture->get_size() - get_minimum_size(); } -void StyleBoxTexture::set_expand_margin_size(Margin p_expand_margin,float p_size) { +void StyleBoxTexture::set_expand_margin_size(Margin p_expand_margin, float p_size) { - ERR_FAIL_INDEX(p_expand_margin,4); - expand_margin[p_expand_margin]=p_size; + ERR_FAIL_INDEX(p_expand_margin, 4); + expand_margin[p_expand_margin] = p_size; emit_changed(); - } float StyleBoxTexture::get_expand_margin_size(Margin p_expand_margin) const { - ERR_FAIL_INDEX_V(p_expand_margin,4,0); + ERR_FAIL_INDEX_V(p_expand_margin, 4, 0); return expand_margin[p_expand_margin]; } -void StyleBoxTexture::set_region_rect(const Rect2& p_region_rect) { +void StyleBoxTexture::set_region_rect(const Rect2 &p_region_rect) { - if (region_rect==p_region_rect) + if (region_rect == p_region_rect) return; - region_rect=p_region_rect; + region_rect = p_region_rect; emit_changed(); } @@ -193,11 +184,10 @@ Rect2 StyleBoxTexture::get_region_rect() const { return region_rect; } - -void StyleBoxTexture::set_modulate(const Color& p_modulate) { - if (modulate==p_modulate) +void StyleBoxTexture::set_modulate(const Color &p_modulate) { + if (modulate == p_modulate) return; - modulate=p_modulate; + modulate = p_modulate; emit_changed(); } @@ -206,84 +196,74 @@ Color StyleBoxTexture::get_modulate() const { return modulate; } - void StyleBoxTexture::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_texture","texture:Texture"),&StyleBoxTexture::set_texture); - ClassDB::bind_method(D_METHOD("get_texture:Texture"),&StyleBoxTexture::get_texture); - - ClassDB::bind_method(D_METHOD("set_margin_size","margin","size"),&StyleBoxTexture::set_margin_size); - ClassDB::bind_method(D_METHOD("get_margin_size","margin"),&StyleBoxTexture::get_margin_size); + ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &StyleBoxTexture::set_texture); + ClassDB::bind_method(D_METHOD("get_texture:Texture"), &StyleBoxTexture::get_texture); - ClassDB::bind_method(D_METHOD("set_expand_margin_size","margin","size"),&StyleBoxTexture::set_expand_margin_size); - ClassDB::bind_method(D_METHOD("get_expand_margin_size","margin"),&StyleBoxTexture::get_expand_margin_size); + ClassDB::bind_method(D_METHOD("set_margin_size", "margin", "size"), &StyleBoxTexture::set_margin_size); + ClassDB::bind_method(D_METHOD("get_margin_size", "margin"), &StyleBoxTexture::get_margin_size); - ClassDB::bind_method(D_METHOD("set_region_rect","region"),&StyleBoxTexture::set_region_rect); - ClassDB::bind_method(D_METHOD("get_region_rect"),&StyleBoxTexture::get_region_rect); + ClassDB::bind_method(D_METHOD("set_expand_margin_size", "margin", "size"), &StyleBoxTexture::set_expand_margin_size); + ClassDB::bind_method(D_METHOD("get_expand_margin_size", "margin"), &StyleBoxTexture::get_expand_margin_size); - ClassDB::bind_method(D_METHOD("set_draw_center","enable"),&StyleBoxTexture::set_draw_center); - ClassDB::bind_method(D_METHOD("get_draw_center"),&StyleBoxTexture::get_draw_center); + ClassDB::bind_method(D_METHOD("set_region_rect", "region"), &StyleBoxTexture::set_region_rect); + ClassDB::bind_method(D_METHOD("get_region_rect"), &StyleBoxTexture::get_region_rect); - ClassDB::bind_method(D_METHOD("set_modulate","color"),&StyleBoxTexture::set_modulate); - ClassDB::bind_method(D_METHOD("get_modulate"),&StyleBoxTexture::get_modulate); + ClassDB::bind_method(D_METHOD("set_draw_center", "enable"), &StyleBoxTexture::set_draw_center); + ClassDB::bind_method(D_METHOD("get_draw_center"), &StyleBoxTexture::get_draw_center); + ClassDB::bind_method(D_METHOD("set_modulate", "color"), &StyleBoxTexture::set_modulate); + ClassDB::bind_method(D_METHOD("get_modulate"), &StyleBoxTexture::get_modulate); ADD_SIGNAL(MethodInfo("texture_changed")); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture" ), "set_texture","get_texture") ; - ADD_PROPERTYNZ( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect"); - ADD_GROUP("Margin","margin_"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_left", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_LEFT ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_right", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_RIGHT ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_top", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_TOP); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_bottom", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_BOTTOM ); - ADD_GROUP("Expand Margin","expand_margin_"); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_left", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_LEFT ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_right", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_RIGHT ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_top", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_TOP ); - ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_bottom", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_BOTTOM ); - ADD_GROUP("Modulate","modulate_"); - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "modulate_color" ), "set_modulate","get_modulate"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "draw_center" ) , "set_draw_center","get_draw_center"); - + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); + ADD_PROPERTYNZ(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect"); + ADD_GROUP("Margin", "margin_"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_BOTTOM); + ADD_GROUP("Expand Margin", "expand_margin_"); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_LEFT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_RIGHT); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_TOP); + ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_BOTTOM); + ADD_GROUP("Modulate", "modulate_"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate_color"), "set_modulate", "get_modulate"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "get_draw_center"); } StyleBoxTexture::StyleBoxTexture() { - - for (int i=0;i<4;i++) { - margin[i]=0; - expand_margin[i]=0; + for (int i = 0; i < 4; i++) { + margin[i] = 0; + expand_margin[i] = 0; } - draw_center=true; - modulate=Color(1,1,1,1); - + draw_center = true; + modulate = Color(1, 1, 1, 1); } StyleBoxTexture::~StyleBoxTexture() { - - } //////////////// -void StyleBoxFlat::set_bg_color(const Color& p_color) { +void StyleBoxFlat::set_bg_color(const Color &p_color) { - bg_color=p_color; + bg_color = p_color; emit_changed(); - } -void StyleBoxFlat::set_light_color(const Color& p_color) { +void StyleBoxFlat::set_light_color(const Color &p_color) { - light_color=p_color; + light_color = p_color; emit_changed(); - } -void StyleBoxFlat::set_dark_color(const Color& p_color) { +void StyleBoxFlat::set_dark_color(const Color &p_color) { - dark_color=p_color; + dark_color = p_color; emit_changed(); - } Color StyleBoxFlat::get_bg_color() const { @@ -299,37 +279,31 @@ Color StyleBoxFlat::get_dark_color() const { return dark_color; } - void StyleBoxFlat::set_border_size(int p_size) { - border_size=p_size; + border_size = p_size; emit_changed(); - } int StyleBoxFlat::get_border_size() const { return border_size; - } void StyleBoxFlat::set_border_blend(bool p_blend) { - blend=p_blend; + blend = p_blend; emit_changed(); - } bool StyleBoxFlat::get_border_blend() const { return blend; - } void StyleBoxFlat::set_draw_center(bool p_draw) { - draw_center=p_draw; + draw_center = p_draw; emit_changed(); - } bool StyleBoxFlat::get_draw_center() const { @@ -340,48 +314,41 @@ Size2 StyleBoxFlat::get_center_size() const { return Size2(); } - -void StyleBoxFlat::draw(RID p_canvas_item,const Rect2& p_rect) const { +void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const { VisualServer *vs = VisualServer::get_singleton(); Rect2i r = p_rect; - for (int i=0;i<border_size;i++) { - + for (int i = 0; i < border_size; i++) { - - Color color_upleft=light_color; - Color color_downright=dark_color; + Color color_upleft = light_color; + Color color_downright = dark_color; if (blend) { - color_upleft.r=(border_size-i)*color_upleft.r/border_size + i*bg_color.r/border_size; - color_upleft.g=(border_size-i)*color_upleft.g/border_size + i*bg_color.g/border_size; - color_upleft.b=(border_size-i)*color_upleft.b/border_size + i*bg_color.b/border_size; - - color_downright.r=(border_size-i)*color_downright.r/border_size + i*bg_color.r/border_size; - color_downright.g=(border_size-i)*color_downright.g/border_size + i*bg_color.g/border_size; - color_downright.b=(border_size-i)*color_downright.b/border_size + i*bg_color.b/border_size; + color_upleft.r = (border_size - i) * color_upleft.r / border_size + i * bg_color.r / border_size; + color_upleft.g = (border_size - i) * color_upleft.g / border_size + i * bg_color.g / border_size; + color_upleft.b = (border_size - i) * color_upleft.b / border_size + i * bg_color.b / border_size; + color_downright.r = (border_size - i) * color_downright.r / border_size + i * bg_color.r / border_size; + color_downright.g = (border_size - i) * color_downright.g / border_size + i * bg_color.g / border_size; + color_downright.b = (border_size - i) * color_downright.b / border_size + i * bg_color.b / border_size; } - vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i( r.pos.x,r.pos.y+r.size.y-1), Size2(r.size.x ,1 )),color_downright); - vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i( r.pos.x+r.size.x-1,r.pos.y ), Size2( 1 ,r.size.y )), color_downright); - - vs->canvas_item_add_rect(p_canvas_item, Rect2( r.pos, Size2(r.size.x ,1 )), color_upleft); - vs->canvas_item_add_rect(p_canvas_item, Rect2( r.pos, Size2( 1 ,r.size.y )), color_upleft); + vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i(r.pos.x, r.pos.y + r.size.y - 1), Size2(r.size.x, 1)), color_downright); + vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i(r.pos.x + r.size.x - 1, r.pos.y), Size2(1, r.size.y)), color_downright); + vs->canvas_item_add_rect(p_canvas_item, Rect2(r.pos, Size2(r.size.x, 1)), color_upleft); + vs->canvas_item_add_rect(p_canvas_item, Rect2(r.pos, Size2(1, r.size.y)), color_upleft); r.pos.x++; r.pos.y++; - r.size.x-=2; - r.size.y-=2; + r.size.x -= 2; + r.size.y -= 2; } if (draw_center) - vs->canvas_item_add_rect(p_canvas_item, Rect2( r.pos, r.size) , bg_color ); - - + vs->canvas_item_add_rect(p_canvas_item, Rect2(r.pos, r.size), bg_color); } float StyleBoxFlat::get_style_margin(Margin p_margin) const { @@ -390,40 +357,35 @@ float StyleBoxFlat::get_style_margin(Margin p_margin) const { } void StyleBoxFlat::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_bg_color","color"),&StyleBoxFlat::set_bg_color); - ClassDB::bind_method(D_METHOD("get_bg_color"),&StyleBoxFlat::get_bg_color); - ClassDB::bind_method(D_METHOD("set_light_color","color"),&StyleBoxFlat::set_light_color); - ClassDB::bind_method(D_METHOD("get_light_color"),&StyleBoxFlat::get_light_color); - ClassDB::bind_method(D_METHOD("set_dark_color","color"),&StyleBoxFlat::set_dark_color); - ClassDB::bind_method(D_METHOD("get_dark_color"),&StyleBoxFlat::get_dark_color); - ClassDB::bind_method(D_METHOD("set_border_size","size"),&StyleBoxFlat::set_border_size); - ClassDB::bind_method(D_METHOD("get_border_size"),&StyleBoxFlat::get_border_size); - ClassDB::bind_method(D_METHOD("set_border_blend","blend"),&StyleBoxFlat::set_border_blend); - ClassDB::bind_method(D_METHOD("get_border_blend"),&StyleBoxFlat::get_border_blend); - ClassDB::bind_method(D_METHOD("set_draw_center","size"),&StyleBoxFlat::set_draw_center); - ClassDB::bind_method(D_METHOD("get_draw_center"),&StyleBoxFlat::get_draw_center); - - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "bg_color"), "set_bg_color","get_bg_color") ; - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "light_color"),"set_light_color","get_light_color"); - ADD_PROPERTY( PropertyInfo( Variant::COLOR, "dark_color"),"set_dark_color","get_dark_color"); - ADD_PROPERTY( PropertyInfo( Variant::INT, "border_size",PROPERTY_HINT_RANGE,"0,4096"),"set_border_size","get_border_size"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "border_blend"),"set_border_blend","get_border_blend"); - ADD_PROPERTY( PropertyInfo( Variant::BOOL, "draw_bg"),"set_draw_center","get_draw_center"); - + ClassDB::bind_method(D_METHOD("set_bg_color", "color"), &StyleBoxFlat::set_bg_color); + ClassDB::bind_method(D_METHOD("get_bg_color"), &StyleBoxFlat::get_bg_color); + ClassDB::bind_method(D_METHOD("set_light_color", "color"), &StyleBoxFlat::set_light_color); + ClassDB::bind_method(D_METHOD("get_light_color"), &StyleBoxFlat::get_light_color); + ClassDB::bind_method(D_METHOD("set_dark_color", "color"), &StyleBoxFlat::set_dark_color); + ClassDB::bind_method(D_METHOD("get_dark_color"), &StyleBoxFlat::get_dark_color); + ClassDB::bind_method(D_METHOD("set_border_size", "size"), &StyleBoxFlat::set_border_size); + ClassDB::bind_method(D_METHOD("get_border_size"), &StyleBoxFlat::get_border_size); + ClassDB::bind_method(D_METHOD("set_border_blend", "blend"), &StyleBoxFlat::set_border_blend); + ClassDB::bind_method(D_METHOD("get_border_blend"), &StyleBoxFlat::get_border_blend); + ClassDB::bind_method(D_METHOD("set_draw_center", "size"), &StyleBoxFlat::set_draw_center); + ClassDB::bind_method(D_METHOD("get_draw_center"), &StyleBoxFlat::get_draw_center); + + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "bg_color"), "set_bg_color", "get_bg_color"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "light_color"), "set_light_color", "get_light_color"); + ADD_PROPERTY(PropertyInfo(Variant::COLOR, "dark_color"), "set_dark_color", "get_dark_color"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "border_size", PROPERTY_HINT_RANGE, "0,4096"), "set_border_size", "get_border_size"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "border_blend"), "set_border_blend", "get_border_blend"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_bg"), "set_draw_center", "get_draw_center"); } StyleBoxFlat::StyleBoxFlat() { - bg_color=Color(0.6,0.6,0.6); - light_color=Color(0.8,0.8,0.8); - dark_color=Color(0.8,0.8,0.8); - draw_center=true; - blend=true; - border_size=0; - + bg_color = Color(0.6, 0.6, 0.6); + light_color = Color(0.8, 0.8, 0.8); + dark_color = Color(0.8, 0.8, 0.8); + draw_center = true; + blend = true; + border_size = 0; } StyleBoxFlat::~StyleBoxFlat() { - - } - diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h index f8b02724ee..f0107ed71f 100644 --- a/scene/resources/style_box.h +++ b/scene/resources/style_box.h @@ -30,32 +30,31 @@ #define STYLE_BOX_H #include "resource.h" -#include "servers/visual_server.h" #include "scene/resources/texture.h" +#include "servers/visual_server.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class StyleBox : public Resource { - GDCLASS( StyleBox, Resource ); + GDCLASS(StyleBox, Resource); RES_BASE_EXTENSION("sbx"); - OBJ_SAVE_TYPE( StyleBox ); + OBJ_SAVE_TYPE(StyleBox); float margin[4]; protected: - - virtual float get_style_margin(Margin p_margin) const=0; + virtual float get_style_margin(Margin p_margin) const = 0; static void _bind_methods(); -public: - virtual bool test_mask(const Point2& p_point, const Rect2& p_rect) const; +public: + virtual bool test_mask(const Point2 &p_point, const Rect2 &p_rect) const; void set_default_margin(Margin p_margin, float p_value); float get_default_margin(Margin p_margin) const; float get_margin(Margin p_margin) const; virtual Size2 get_center_size() const; - virtual void draw(RID p_canvas_item,const Rect2& p_rect) const=0; + virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const = 0; Size2 get_minimum_size() const; Point2 get_offset() const; @@ -65,19 +64,17 @@ public: class StyleBoxEmpty : public StyleBox { - GDCLASS( StyleBoxEmpty, StyleBox ); + GDCLASS(StyleBoxEmpty, StyleBox); virtual float get_style_margin(Margin p_margin) const { return 0; } -public: - virtual void draw(RID p_canvas_item,const Rect2& p_rect) const {} +public: + virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const {} StyleBoxEmpty() {} - }; class StyleBoxTexture : public StyleBox { - GDCLASS( StyleBoxTexture, StyleBox ); - + GDCLASS(StyleBoxTexture, StyleBox); float expand_margin[4]; float margin[4]; @@ -86,21 +83,18 @@ class StyleBoxTexture : public StyleBox { bool draw_center; Color modulate; - protected: - virtual float get_style_margin(Margin p_margin) const; static void _bind_methods(); public: - - void set_expand_margin_size(Margin p_expand_margin,float p_size); + void set_expand_margin_size(Margin p_expand_margin, float p_size); float get_expand_margin_size(Margin p_expand_margin) const; - void set_margin_size(Margin p_margin,float p_size); + void set_margin_size(Margin p_margin, float p_size); float get_margin_size(Margin p_margin) const; - void set_region_rect(const Rect2& p_region_rect); + void set_region_rect(const Rect2 &p_region_rect); Rect2 get_region_rect() const; void set_texture(RES p_texture); @@ -110,20 +104,18 @@ public: bool get_draw_center() const; virtual Size2 get_center_size() const; - void set_modulate(const Color& p_modulate); + void set_modulate(const Color &p_modulate); Color get_modulate() const; - - virtual void draw(RID p_canvas_item,const Rect2& p_rect) const; + virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const; StyleBoxTexture(); ~StyleBoxTexture(); - }; class StyleBoxFlat : public StyleBox { - GDCLASS( StyleBoxFlat, StyleBox ); + GDCLASS(StyleBoxFlat, StyleBox); Color bg_color; Color light_color; @@ -135,15 +127,13 @@ class StyleBoxFlat : public StyleBox { bool blend; protected: - virtual float get_style_margin(Margin p_margin) const; static void _bind_methods(); public: - - void set_bg_color(const Color& p_color); - void set_light_color(const Color& p_color); - void set_dark_color(const Color& p_color); + void set_bg_color(const Color &p_color); + void set_light_color(const Color &p_color); + void set_dark_color(const Color &p_color); Color get_bg_color() const; Color get_light_color() const; @@ -159,13 +149,10 @@ public: bool get_draw_center() const; virtual Size2 get_center_size() const; - virtual void draw(RID p_canvas_item,const Rect2& p_rect) const; + virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const; StyleBoxFlat(); ~StyleBoxFlat(); - }; - - #endif diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp index cf07f1658b..7564735cf2 100644 --- a/scene/resources/surface_tool.cpp +++ b/scene/resources/surface_tool.cpp @@ -32,56 +32,53 @@ #define _VERTEX_SNAP 0.0001 #define EQ_VERTEX_DIST 0.00001 +bool SurfaceTool::Vertex::operator==(const Vertex &p_b) const { -bool SurfaceTool::Vertex::operator==(const Vertex& p_b) const { - - - if (vertex!=p_b.vertex) + if (vertex != p_b.vertex) return false; - if (uv!=p_b.uv) + if (uv != p_b.uv) return false; - if (uv2!=p_b.uv2) + if (uv2 != p_b.uv2) return false; - if (normal!=p_b.normal) + if (normal != p_b.normal) return false; - if (binormal!=p_b.binormal) + if (binormal != p_b.binormal) return false; - if (color!=p_b.color) + if (color != p_b.color) return false; - if (bones.size()!=p_b.bones.size()) + if (bones.size() != p_b.bones.size()) return false; - for(int i=0;i<bones.size();i++) { - if (bones[i]!=p_b.bones[i]) + for (int i = 0; i < bones.size(); i++) { + if (bones[i] != p_b.bones[i]) return false; } - for(int i=0;i<weights.size();i++) { - if (weights[i]!=p_b.weights[i]) + for (int i = 0; i < weights.size(); i++) { + if (weights[i] != p_b.weights[i]) return false; } return true; } - uint32_t SurfaceTool::VertexHasher::hash(const Vertex &p_vtx) { - uint32_t h = hash_djb2_buffer((const uint8_t*)&p_vtx.vertex,sizeof(real_t)*3); - h = hash_djb2_buffer((const uint8_t*)&p_vtx.normal,sizeof(real_t)*3,h); - h = hash_djb2_buffer((const uint8_t*)&p_vtx.binormal,sizeof(real_t)*3,h); - h = hash_djb2_buffer((const uint8_t*)&p_vtx.tangent,sizeof(real_t)*3,h); - h = hash_djb2_buffer((const uint8_t*)&p_vtx.uv,sizeof(real_t)*2,h); - h = hash_djb2_buffer((const uint8_t*)&p_vtx.uv2,sizeof(real_t)*2,h); - h = hash_djb2_buffer((const uint8_t*)&p_vtx.color,sizeof(real_t)*4,h); - h = hash_djb2_buffer((const uint8_t*)p_vtx.bones.ptr(),p_vtx.bones.size()*sizeof(int),h); - h = hash_djb2_buffer((const uint8_t*)p_vtx.weights.ptr(),p_vtx.weights.size()*sizeof(float),h); + uint32_t h = hash_djb2_buffer((const uint8_t *)&p_vtx.vertex, sizeof(real_t) * 3); + h = hash_djb2_buffer((const uint8_t *)&p_vtx.normal, sizeof(real_t) * 3, h); + h = hash_djb2_buffer((const uint8_t *)&p_vtx.binormal, sizeof(real_t) * 3, h); + h = hash_djb2_buffer((const uint8_t *)&p_vtx.tangent, sizeof(real_t) * 3, h); + h = hash_djb2_buffer((const uint8_t *)&p_vtx.uv, sizeof(real_t) * 2, h); + h = hash_djb2_buffer((const uint8_t *)&p_vtx.uv2, sizeof(real_t) * 2, h); + h = hash_djb2_buffer((const uint8_t *)&p_vtx.color, sizeof(real_t) * 4, h); + h = hash_djb2_buffer((const uint8_t *)p_vtx.bones.ptr(), p_vtx.bones.size() * sizeof(int), h); + h = hash_djb2_buffer((const uint8_t *)p_vtx.weights.ptr(), p_vtx.weights.size() * sizeof(float), h); return h; } @@ -89,165 +86,154 @@ void SurfaceTool::begin(Mesh::PrimitiveType p_primitive) { clear(); - primitive=p_primitive; - begun=true; - first=true; + primitive = p_primitive; + begun = true; + first = true; } -void SurfaceTool::add_vertex( const Vector3& p_vertex) { +void SurfaceTool::add_vertex(const Vector3 &p_vertex) { ERR_FAIL_COND(!begun); Vertex vtx; - vtx.vertex=p_vertex; - vtx.color=last_color; - vtx.normal=last_normal; - vtx.uv=last_uv; - vtx.weights=last_weights; - vtx.bones=last_bones; - vtx.tangent=last_tangent.normal; - vtx.binormal=last_normal.cross(last_tangent.normal).normalized() * last_tangent.d; + vtx.vertex = p_vertex; + vtx.color = last_color; + vtx.normal = last_normal; + vtx.uv = last_uv; + vtx.weights = last_weights; + vtx.bones = last_bones; + vtx.tangent = last_tangent.normal; + vtx.binormal = last_normal.cross(last_tangent.normal).normalized() * last_tangent.d; vertex_array.push_back(vtx); - first=false; - format|=Mesh::ARRAY_FORMAT_VERTEX; - + first = false; + format |= Mesh::ARRAY_FORMAT_VERTEX; } -void SurfaceTool::add_color( Color p_color ) { +void SurfaceTool::add_color(Color p_color) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_COLOR)); + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_COLOR)); - format|=Mesh::ARRAY_FORMAT_COLOR; - last_color=p_color; + format |= Mesh::ARRAY_FORMAT_COLOR; + last_color = p_color; } -void SurfaceTool::add_normal( const Vector3& p_normal) { +void SurfaceTool::add_normal(const Vector3 &p_normal) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_NORMAL)); + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_NORMAL)); - format|=Mesh::ARRAY_FORMAT_NORMAL; - last_normal=p_normal; + format |= Mesh::ARRAY_FORMAT_NORMAL; + last_normal = p_normal; } - -void SurfaceTool::add_tangent( const Plane& p_tangent ) { +void SurfaceTool::add_tangent(const Plane &p_tangent) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_TANGENT)); - - format|=Mesh::ARRAY_FORMAT_TANGENT; - last_tangent=p_tangent; - + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TANGENT)); + format |= Mesh::ARRAY_FORMAT_TANGENT; + last_tangent = p_tangent; } - -void SurfaceTool::add_uv( const Vector2& p_uv) { +void SurfaceTool::add_uv(const Vector2 &p_uv) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_TEX_UV)); - - format|=Mesh::ARRAY_FORMAT_TEX_UV; - last_uv=p_uv; + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV)); + format |= Mesh::ARRAY_FORMAT_TEX_UV; + last_uv = p_uv; } -void SurfaceTool::add_uv2( const Vector2& p_uv2) { +void SurfaceTool::add_uv2(const Vector2 &p_uv2) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_TEX_UV2)); - - format|=Mesh::ARRAY_FORMAT_TEX_UV2; - last_uv2=p_uv2; + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV2)); + format |= Mesh::ARRAY_FORMAT_TEX_UV2; + last_uv2 = p_uv2; } -void SurfaceTool::add_bones( const Vector<int>& p_bones) { +void SurfaceTool::add_bones(const Vector<int> &p_bones) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND(p_bones.size()!=4); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_BONES)); + ERR_FAIL_COND(p_bones.size() != 4); + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_BONES)); - format|=Mesh::ARRAY_FORMAT_BONES; - last_bones=p_bones; + format |= Mesh::ARRAY_FORMAT_BONES; + last_bones = p_bones; } -void SurfaceTool::add_weights( const Vector<float>& p_weights) { +void SurfaceTool::add_weights(const Vector<float> &p_weights) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND(p_weights.size()!=4); - ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_WEIGHTS)); - - format|=Mesh::ARRAY_FORMAT_WEIGHTS; - last_weights=p_weights; + ERR_FAIL_COND(p_weights.size() != 4); + ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_WEIGHTS)); + format |= Mesh::ARRAY_FORMAT_WEIGHTS; + last_weights = p_weights; } void SurfaceTool::add_smooth_group(bool p_smooth) { ERR_FAIL_COND(!begun); if (index_array.size()) { - smooth_groups[index_array.size()]=p_smooth; + smooth_groups[index_array.size()] = p_smooth; } else { - smooth_groups[vertex_array.size()]=p_smooth; + smooth_groups[vertex_array.size()] = p_smooth; } } -void SurfaceTool::add_triangle_fan(const Vector<Vector3>& p_vertexes, const Vector<Vector2>& p_uvs, const Vector<Color>& p_colors,const Vector<Vector2>& p_uv2s, const Vector<Vector3>& p_normals, const Vector<Plane>& p_tangents) { +void SurfaceTool::add_triangle_fan(const Vector<Vector3> &p_vertexes, const Vector<Vector2> &p_uvs, const Vector<Color> &p_colors, const Vector<Vector2> &p_uv2s, const Vector<Vector3> &p_normals, const Vector<Plane> &p_tangents) { ERR_FAIL_COND(!begun); - ERR_FAIL_COND(primitive!=Mesh::PRIMITIVE_TRIANGLES); - ERR_FAIL_COND(p_vertexes.size()<3); - -#define ADD_POINT(n)\ - {\ - if(p_colors.size() > n)\ - add_color(p_colors[n]);\ - if(p_uvs.size() > n)\ - add_uv(p_uvs[n]);\ - if(p_uv2s.size() > n)\ - add_uv2(p_uv2s[n]);\ - if(p_normals.size() > n)\ - add_normal(p_normals[n]);\ - if(p_tangents.size() > n)\ - add_tangent(p_tangents[n]);\ - add_vertex(p_vertexes[n]);\ + ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES); + ERR_FAIL_COND(p_vertexes.size() < 3); + +#define ADD_POINT(n) \ + { \ + if (p_colors.size() > n) \ + add_color(p_colors[n]); \ + if (p_uvs.size() > n) \ + add_uv(p_uvs[n]); \ + if (p_uv2s.size() > n) \ + add_uv2(p_uv2s[n]); \ + if (p_normals.size() > n) \ + add_normal(p_normals[n]); \ + if (p_tangents.size() > n) \ + add_tangent(p_tangents[n]); \ + add_vertex(p_vertexes[n]); \ } - for(int i=0;i<p_vertexes.size() - 2;i++) { + for (int i = 0; i < p_vertexes.size() - 2; i++) { ADD_POINT(0); - ADD_POINT(i+1); - ADD_POINT(i+2); + ADD_POINT(i + 1); + ADD_POINT(i + 2); } #undef ADD_POINT - } -void SurfaceTool::add_index( int p_index) { +void SurfaceTool::add_index(int p_index) { ERR_FAIL_COND(!begun); - format|=Mesh::ARRAY_FORMAT_INDEX; + format |= Mesh::ARRAY_FORMAT_INDEX; index_array.push_back(p_index); } -Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) { - +Ref<Mesh> SurfaceTool::commit(const Ref<Mesh> &p_existing) { Ref<Mesh> mesh; if (p_existing.is_valid()) - mesh=p_existing; + mesh = p_existing; else - mesh= Ref<Mesh>( memnew( Mesh ) ); + mesh = Ref<Mesh>(memnew(Mesh)); - int varr_len=vertex_array.size(); + int varr_len = vertex_array.size(); - - if (varr_len==0) + if (varr_len == 0) return mesh; int surface = mesh->get_surface_count(); @@ -255,9 +241,9 @@ Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) { Array a; a.resize(Mesh::ARRAY_MAX); - for (int i=0;i<Mesh::ARRAY_MAX;i++) { + for (int i = 0; i < Mesh::ARRAY_MAX; i++) { - switch(format&(1<<i)) { + switch (format & (1 << i)) { case Mesh::ARRAY_FORMAT_VERTEX: case Mesh::ARRAY_FORMAT_NORMAL: { @@ -266,24 +252,23 @@ Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) { array.resize(varr_len); PoolVector<Vector3>::Write w = array.write(); - int idx=0; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx++) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx++) { - const Vertex &v=E->get(); + const Vertex &v = E->get(); - switch(i) { + switch (i) { case Mesh::ARRAY_VERTEX: { - w[idx]=v.vertex; + w[idx] = v.vertex; } break; case Mesh::ARRAY_NORMAL: { - w[idx]=v.normal; + w[idx] = v.normal; } break; } - } - w=PoolVector<Vector3>::Write(); - a[i]=array; + w = PoolVector<Vector3>::Write(); + a[i] = array; } break; @@ -294,141 +279,134 @@ Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) { array.resize(varr_len); PoolVector<Vector2>::Write w = array.write(); - int idx=0; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx++) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx++) { - const Vertex &v=E->get(); + const Vertex &v = E->get(); - switch(i) { + switch (i) { case Mesh::ARRAY_TEX_UV: { - w[idx]=v.uv; + w[idx] = v.uv; } break; case Mesh::ARRAY_TEX_UV2: { - w[idx]=v.uv2; + w[idx] = v.uv2; } break; } - } - w=PoolVector<Vector2>::Write(); - a[i]=array; + w = PoolVector<Vector2>::Write(); + a[i] = array; } break; case Mesh::ARRAY_FORMAT_TANGENT: { - PoolVector<float> array; - array.resize(varr_len*4); + array.resize(varr_len * 4); PoolVector<float>::Write w = array.write(); - int idx=0; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx+=4) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx += 4) { - const Vertex &v=E->get(); + const Vertex &v = E->get(); - w[idx+0]=v.tangent.x; - w[idx+1]=v.tangent.y; - w[idx+2]=v.tangent.z; + w[idx + 0] = v.tangent.x; + w[idx + 1] = v.tangent.y; + w[idx + 2] = v.tangent.z; //float d = v.tangent.dot(v.binormal,v.normal); - float d = v.binormal.dot( v.normal.cross(v.tangent)); - w[idx+3]=d<0 ? -1 : 1; + float d = v.binormal.dot(v.normal.cross(v.tangent)); + w[idx + 3] = d < 0 ? -1 : 1; } - w=PoolVector<float>::Write(); - a[i]=array; + w = PoolVector<float>::Write(); + a[i] = array; } break; - case Mesh::ARRAY_FORMAT_COLOR: { + case Mesh::ARRAY_FORMAT_COLOR: { PoolVector<Color> array; array.resize(varr_len); PoolVector<Color>::Write w = array.write(); - int idx=0; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx++) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx++) { - const Vertex &v=E->get(); - w[idx]=v.color; + const Vertex &v = E->get(); + w[idx] = v.color; } - w=PoolVector<Color>::Write(); - a[i]=array; + w = PoolVector<Color>::Write(); + a[i] = array; } break; case Mesh::ARRAY_FORMAT_BONES: { - PoolVector<int> array; - array.resize(varr_len*4); + array.resize(varr_len * 4); PoolVector<int>::Write w = array.write(); - int idx=0; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx+=4) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx += 4) { - const Vertex &v=E->get(); + const Vertex &v = E->get(); - ERR_CONTINUE( v.bones.size()!=4 ); + ERR_CONTINUE(v.bones.size() != 4); - for(int j=0;j<4;j++) { - w[idx+j]=v.bones[j]; + for (int j = 0; j < 4; j++) { + w[idx + j] = v.bones[j]; } - } - w=PoolVector<int>::Write(); - a[i]=array; + w = PoolVector<int>::Write(); + a[i] = array; } break; case Mesh::ARRAY_FORMAT_WEIGHTS: { - PoolVector<float> array; - array.resize(varr_len*4); + array.resize(varr_len * 4); PoolVector<float>::Write w = array.write(); - int idx=0; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx+=4) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx += 4) { - const Vertex &v=E->get(); - ERR_CONTINUE( v.weights.size()!=4 ); + const Vertex &v = E->get(); + ERR_CONTINUE(v.weights.size() != 4); - for(int j=0;j<4;j++) { + for (int j = 0; j < 4; j++) { - w[idx+j]=v.weights[j]; + w[idx + j] = v.weights[j]; } - } - w=PoolVector<float>::Write(); - a[i]=array; + w = PoolVector<float>::Write(); + a[i] = array; } break; case Mesh::ARRAY_FORMAT_INDEX: { - ERR_CONTINUE( index_array.size() ==0 ); + ERR_CONTINUE(index_array.size() == 0); PoolVector<int> array; array.resize(index_array.size()); PoolVector<int>::Write w = array.write(); - int idx=0; - for(List< int>::Element *E=index_array.front();E;E=E->next(),idx++) { + int idx = 0; + for (List<int>::Element *E = index_array.front(); E; E = E->next(), idx++) { - w[idx]=E->get(); + w[idx] = E->get(); } - w=PoolVector<int>::Write(); - a[i]=array; + w = PoolVector<int>::Write(); + a[i] = array; } break; default: {} } - } - mesh->add_surface_from_arrays(primitive,a); + mesh->add_surface_from_arrays(primitive, a); if (material.is_valid()) - mesh->surface_set_material(surface,material); + mesh->surface_set_material(surface, material); return mesh; } @@ -438,57 +416,54 @@ void SurfaceTool::index() { if (index_array.size()) return; //already indexed - - HashMap<Vertex,int,VertexHasher> indices; + HashMap<Vertex, int, VertexHasher> indices; List<Vertex> new_vertices; - for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next()) { + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next()) { - int *idxptr=indices.getptr(E->get()); + int *idxptr = indices.getptr(E->get()); int idx; if (!idxptr) { - idx=indices.size(); + idx = indices.size(); new_vertices.push_back(E->get()); - indices[E->get()]=idx; + indices[E->get()] = idx; } else { - idx=*idxptr; + idx = *idxptr; } index_array.push_back(idx); - } vertex_array.clear(); - vertex_array=new_vertices; + vertex_array = new_vertices; - format|=Mesh::ARRAY_FORMAT_INDEX; + format |= Mesh::ARRAY_FORMAT_INDEX; } void SurfaceTool::deindex() { - if (index_array.size()==0) + if (index_array.size() == 0) return; //nothing to deindex - Vector< Vertex > varr; + Vector<Vertex> varr; varr.resize(vertex_array.size()); - int idx=0; - for (List< Vertex >::Element *E=vertex_array.front();E;E=E->next()) { + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next()) { - varr[idx++]=E->get(); + varr[idx++] = E->get(); } vertex_array.clear(); - for (List<int>::Element *E=index_array.front();E;E=E->next()) { + for (List<int>::Element *E = index_array.front(); E; E = E->next()) { - ERR_FAIL_INDEX(E->get(),varr.size()); + ERR_FAIL_INDEX(E->get(), varr.size()); vertex_array.push_back(varr[E->get()]); } - format&=~Mesh::ARRAY_FORMAT_INDEX; + format &= ~Mesh::ARRAY_FORMAT_INDEX; } - -void SurfaceTool::_create_list(const Ref<Mesh>& p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index, int& lformat) { +void SurfaceTool::_create_list(const Ref<Mesh> &p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index, int &lformat) { Array arr = p_existing->surface_get_arrays(p_surface); - ERR_FAIL_COND( arr.size() !=VS::ARRAY_MAX ); + ERR_FAIL_COND(arr.size() != VS::ARRAY_MAX); PoolVector<Vector3> varr = arr[VS::ARRAY_VERTEX]; PoolVector<Vector3> narr = arr[VS::ARRAY_NORMAL]; @@ -501,90 +476,90 @@ void SurfaceTool::_create_list(const Ref<Mesh>& p_existing, int p_surface, List< int vc = varr.size(); - if (vc==0) + if (vc == 0) return; - lformat=0; + lformat = 0; PoolVector<Vector3>::Read rv; if (varr.size()) { - lformat|=VS::ARRAY_FORMAT_VERTEX; - rv=varr.read(); + lformat |= VS::ARRAY_FORMAT_VERTEX; + rv = varr.read(); } PoolVector<Vector3>::Read rn; if (narr.size()) { - lformat|=VS::ARRAY_FORMAT_NORMAL; - rn=narr.read(); + lformat |= VS::ARRAY_FORMAT_NORMAL; + rn = narr.read(); } PoolVector<float>::Read rt; if (tarr.size()) { - lformat|=VS::ARRAY_FORMAT_TANGENT; - rt=tarr.read(); + lformat |= VS::ARRAY_FORMAT_TANGENT; + rt = tarr.read(); } PoolVector<Color>::Read rc; if (carr.size()) { - lformat|=VS::ARRAY_FORMAT_COLOR; - rc=carr.read(); + lformat |= VS::ARRAY_FORMAT_COLOR; + rc = carr.read(); } PoolVector<Vector2>::Read ruv; if (uvarr.size()) { - lformat|=VS::ARRAY_FORMAT_TEX_UV; - ruv=uvarr.read(); + lformat |= VS::ARRAY_FORMAT_TEX_UV; + ruv = uvarr.read(); } PoolVector<Vector2>::Read ruv2; if (uv2arr.size()) { - lformat|=VS::ARRAY_FORMAT_TEX_UV2; - ruv2=uv2arr.read(); + lformat |= VS::ARRAY_FORMAT_TEX_UV2; + ruv2 = uv2arr.read(); } PoolVector<int>::Read rb; if (barr.size()) { - lformat|=VS::ARRAY_FORMAT_BONES; - rb=barr.read(); + lformat |= VS::ARRAY_FORMAT_BONES; + rb = barr.read(); } PoolVector<float>::Read rw; if (warr.size()) { - lformat|=VS::ARRAY_FORMAT_WEIGHTS; - rw=warr.read(); + lformat |= VS::ARRAY_FORMAT_WEIGHTS; + rw = warr.read(); } - for(int i=0;i<vc;i++) { + for (int i = 0; i < vc; i++) { Vertex v; - if (lformat&VS::ARRAY_FORMAT_VERTEX) - v.vertex=varr[i]; - if (lformat&VS::ARRAY_FORMAT_NORMAL) - v.normal=narr[i]; - if (lformat&VS::ARRAY_FORMAT_TANGENT) { - Plane p( tarr[i*4+0], tarr[i*4+1], tarr[i*4+2], tarr[i*4+3] ); - v.tangent=p.normal; - v.binormal=p.normal.cross(last_normal).normalized() * p.d; + if (lformat & VS::ARRAY_FORMAT_VERTEX) + v.vertex = varr[i]; + if (lformat & VS::ARRAY_FORMAT_NORMAL) + v.normal = narr[i]; + if (lformat & VS::ARRAY_FORMAT_TANGENT) { + Plane p(tarr[i * 4 + 0], tarr[i * 4 + 1], tarr[i * 4 + 2], tarr[i * 4 + 3]); + v.tangent = p.normal; + v.binormal = p.normal.cross(last_normal).normalized() * p.d; } - if (lformat&VS::ARRAY_FORMAT_COLOR) - v.color=carr[i]; - if (lformat&VS::ARRAY_FORMAT_TEX_UV) - v.uv=uvarr[i]; - if (lformat&VS::ARRAY_FORMAT_TEX_UV2) - v.uv2=uv2arr[i]; - if (lformat&VS::ARRAY_FORMAT_BONES) { + if (lformat & VS::ARRAY_FORMAT_COLOR) + v.color = carr[i]; + if (lformat & VS::ARRAY_FORMAT_TEX_UV) + v.uv = uvarr[i]; + if (lformat & VS::ARRAY_FORMAT_TEX_UV2) + v.uv2 = uv2arr[i]; + if (lformat & VS::ARRAY_FORMAT_BONES) { Vector<int> b; b.resize(4); - b[0]=barr[i*4+0]; - b[1]=barr[i*4+1]; - b[2]=barr[i*4+2]; - b[3]=barr[i*4+3]; - v.bones=b; + b[0] = barr[i * 4 + 0]; + b[1] = barr[i * 4 + 1]; + b[2] = barr[i * 4 + 2]; + b[3] = barr[i * 4 + 3]; + v.bones = b; } - if (lformat&VS::ARRAY_FORMAT_WEIGHTS) { + if (lformat & VS::ARRAY_FORMAT_WEIGHTS) { Vector<float> w; w.resize(4); - w[0]=warr[i*4+0]; - w[1]=warr[i*4+1]; - w[2]=warr[i*4+2]; - w[3]=warr[i*4+3]; - v.weights=w; + w[0] = warr[i * 4 + 0]; + w[1] = warr[i * 4 + 1]; + w[2] = warr[i * 4 + 2]; + w[3] = warr[i * 4 + 3]; + v.weights = w; } r_vertex->push_back(v); @@ -592,64 +567,58 @@ void SurfaceTool::_create_list(const Ref<Mesh>& p_existing, int p_surface, List< //indices - PoolVector<int> idx= arr[VS::ARRAY_INDEX]; + PoolVector<int> idx = arr[VS::ARRAY_INDEX]; int is = idx.size(); if (is) { - lformat|=VS::ARRAY_FORMAT_INDEX; - PoolVector<int>::Read iarr=idx.read(); - for(int i=0;i<is;i++) { + lformat |= VS::ARRAY_FORMAT_INDEX; + PoolVector<int>::Read iarr = idx.read(); + for (int i = 0; i < is; i++) { r_index->push_back(iarr[i]); } - } - - } - -void SurfaceTool::create_from(const Ref<Mesh>& p_existing, int p_surface) { +void SurfaceTool::create_from(const Ref<Mesh> &p_existing, int p_surface) { clear(); - primitive=p_existing->surface_get_primitive_type(p_surface); - _create_list(p_existing,p_surface,&vertex_array,&index_array,format); - material=p_existing->surface_get_material(p_surface); - + primitive = p_existing->surface_get_primitive_type(p_surface); + _create_list(p_existing, p_surface, &vertex_array, &index_array, format); + material = p_existing->surface_get_material(p_surface); } -void SurfaceTool::append_from(const Ref<Mesh>& p_existing, int p_surface,const Transform& p_xform) { +void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform &p_xform) { - if (vertex_array.size()==0) { - primitive=p_existing->surface_get_primitive_type(p_surface); - format=0; + if (vertex_array.size() == 0) { + primitive = p_existing->surface_get_primitive_type(p_surface); + format = 0; } int nformat; List<Vertex> nvertices; List<int> nindices; - _create_list(p_existing,p_surface,&nvertices,&nindices,nformat); - format|=nformat; + _create_list(p_existing, p_surface, &nvertices, &nindices, nformat); + format |= nformat; int vfrom = vertex_array.size(); + for (List<Vertex>::Element *E = nvertices.front(); E; E = E->next()) { - for(List<Vertex>::Element *E=nvertices.front();E;E=E->next()) { - - Vertex v=E->get(); - v.vertex=p_xform.xform(v.vertex); - if (nformat&VS::ARRAY_FORMAT_NORMAL) { - v.normal=p_xform.basis.xform(v.normal); + Vertex v = E->get(); + v.vertex = p_xform.xform(v.vertex); + if (nformat & VS::ARRAY_FORMAT_NORMAL) { + v.normal = p_xform.basis.xform(v.normal); } - if (nformat&VS::ARRAY_FORMAT_TANGENT) { - v.tangent=p_xform.basis.xform(v.tangent); - v.binormal=p_xform.basis.xform(v.binormal); + if (nformat & VS::ARRAY_FORMAT_TANGENT) { + v.tangent = p_xform.basis.xform(v.tangent); + v.binormal = p_xform.basis.xform(v.binormal); } vertex_array.push_back(v); } - for(List<int>::Element *E=nindices.front();E;E=E->next()) { + for (List<int>::Element *E = nindices.front(); E; E = E->next()) { - int dst_index = E->get()+vfrom; + int dst_index = E->get() + vfrom; /* if (dst_index <0 || dst_index>=vertex_array.size()) { print_line("invalid index!"); @@ -657,240 +626,220 @@ void SurfaceTool::append_from(const Ref<Mesh>& p_existing, int p_surface,const T */ index_array.push_back(dst_index); } - if (index_array.size()%3) + if (index_array.size() % 3) print_line("IA not div of 3?"); - } //mikktspace callbacks -int SurfaceTool::mikktGetNumFaces(const SMikkTSpaceContext * pContext) { +int SurfaceTool::mikktGetNumFaces(const SMikkTSpaceContext *pContext) { - Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData); - return varr.size()/3; + Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData); + return varr.size() / 3; } -int SurfaceTool::mikktGetNumVerticesOfFace(const SMikkTSpaceContext * pContext, const int iFace){ +int SurfaceTool::mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace) { return 3; //always 3 } -void SurfaceTool::mikktGetPosition(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert){ - - Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData); - Vector3 v = varr[iFace*3+iVert]->get().vertex; - fvPosOut[0]=v.x; - fvPosOut[1]=v.y; - fvPosOut[2]=v.z; - +void SurfaceTool::mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert) { + Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData); + Vector3 v = varr[iFace * 3 + iVert]->get().vertex; + fvPosOut[0] = v.x; + fvPosOut[1] = v.y; + fvPosOut[2] = v.z; } -void SurfaceTool::mikktGetNormal(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert){ - - - Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData); - Vector3 v = varr[iFace*3+iVert]->get().normal; - fvNormOut[0]=v.x; - fvNormOut[1]=v.y; - fvNormOut[2]=v.z; +void SurfaceTool::mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert) { + Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData); + Vector3 v = varr[iFace * 3 + iVert]->get().normal; + fvNormOut[0] = v.x; + fvNormOut[1] = v.y; + fvNormOut[2] = v.z; } -void SurfaceTool::mikktGetTexCoord(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert){ +void SurfaceTool::mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert) { - Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData); - Vector2 v = varr[iFace*3+iVert]->get().uv; - fvTexcOut[0]=v.x; - fvTexcOut[1]=v.y; + Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData); + Vector2 v = varr[iFace * 3 + iVert]->get().uv; + fvTexcOut[0] = v.x; + fvTexcOut[1] = v.y; //fvTexcOut[1]=1.0-v.y; - } -void SurfaceTool::mikktSetTSpaceBasic(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert){ +void SurfaceTool::mikktSetTSpaceBasic(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert) { - Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData); - Vertex &vtx = varr[iFace*3+iVert]->get(); + Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData); + Vertex &vtx = varr[iFace * 3 + iVert]->get(); - vtx.tangent = Vector3(fvTangent[0],fvTangent[1],fvTangent[2]); + vtx.tangent = Vector3(fvTangent[0], fvTangent[1], fvTangent[2]); vtx.binormal = vtx.normal.cross(vtx.tangent) * fSign; } - void SurfaceTool::generate_tangents() { - ERR_FAIL_COND(!(format&Mesh::ARRAY_FORMAT_TEX_UV)); - ERR_FAIL_COND(!(format&Mesh::ARRAY_FORMAT_NORMAL)); + ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_TEX_UV)); + ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_NORMAL)); - bool indexed = index_array.size()>0; + bool indexed = index_array.size() > 0; if (indexed) deindex(); - SMikkTSpaceInterface mkif; - mkif.m_getNormal=mikktGetNormal; - mkif.m_getNumFaces=mikktGetNumFaces; - mkif.m_getNumVerticesOfFace=mikktGetNumVerticesOfFace; - mkif.m_getPosition=mikktGetPosition; - mkif.m_getTexCoord=mikktGetTexCoord; - mkif.m_setTSpaceBasic=mikktSetTSpaceBasic; - mkif.m_setTSpace=NULL; + mkif.m_getNormal = mikktGetNormal; + mkif.m_getNumFaces = mikktGetNumFaces; + mkif.m_getNumVerticesOfFace = mikktGetNumVerticesOfFace; + mkif.m_getPosition = mikktGetPosition; + mkif.m_getTexCoord = mikktGetTexCoord; + mkif.m_setTSpaceBasic = mikktSetTSpaceBasic; + mkif.m_setTSpace = NULL; SMikkTSpaceContext msc; - msc.m_pInterface=&mkif; + msc.m_pInterface = &mkif; - Vector<List<Vertex>::Element*> vtx; + Vector<List<Vertex>::Element *> vtx; vtx.resize(vertex_array.size()); - int idx=0; - for (List<Vertex>::Element *E=vertex_array.front();E;E=E->next()) { - vtx[idx++]=E; - E->get().binormal=Vector3(); - E->get().tangent=Vector3(); + int idx = 0; + for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next()) { + vtx[idx++] = E; + E->get().binormal = Vector3(); + E->get().tangent = Vector3(); } - msc.m_pUserData=&vtx; + msc.m_pUserData = &vtx; bool res = genTangSpaceDefault(&msc); ERR_FAIL_COND(!res); - format|=Mesh::ARRAY_FORMAT_TANGENT; + format |= Mesh::ARRAY_FORMAT_TANGENT; if (indexed) index(); - - } void SurfaceTool::generate_normals() { - ERR_FAIL_COND(primitive!=Mesh::PRIMITIVE_TRIANGLES); + ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES); - bool was_indexed=index_array.size(); + bool was_indexed = index_array.size(); deindex(); - HashMap<Vertex,Vector3,VertexHasher> vertex_hash; + HashMap<Vertex, Vector3, VertexHasher> vertex_hash; - int count=0; - bool smooth=false; + int count = 0; + bool smooth = false; if (smooth_groups.has(0)) - smooth=smooth_groups[0]; + smooth = smooth_groups[0]; - List< Vertex >::Element *B=vertex_array.front(); - for(List< Vertex >::Element *E=B;E;) { + List<Vertex>::Element *B = vertex_array.front(); + for (List<Vertex>::Element *E = B; E;) { - List< Vertex >::Element *v[3]; - v[0]=E; - v[1]=v[0]->next(); + List<Vertex>::Element *v[3]; + v[0] = E; + v[1] = v[0]->next(); ERR_FAIL_COND(!v[1]); - v[2]=v[1]->next(); + v[2] = v[1]->next(); ERR_FAIL_COND(!v[2]); - E=v[2]->next(); + E = v[2]->next(); - Vector3 normal = Plane(v[0]->get().vertex,v[1]->get().vertex,v[2]->get().vertex).normal; + Vector3 normal = Plane(v[0]->get().vertex, v[1]->get().vertex, v[2]->get().vertex).normal; if (smooth) { - for(int i=0;i<3;i++) { + for (int i = 0; i < 3; i++) { - Vector3 *lv=vertex_hash.getptr(v[i]->get()); + Vector3 *lv = vertex_hash.getptr(v[i]->get()); if (!lv) { - vertex_hash.set(v[i]->get(),normal); + vertex_hash.set(v[i]->get(), normal); } else { - (*lv)+=normal; + (*lv) += normal; } } } else { - for(int i=0;i<3;i++) { - - v[i]->get().normal=normal; + for (int i = 0; i < 3; i++) { + v[i]->get().normal = normal; } } - count+=3; + count += 3; if (smooth_groups.has(count) || !E) { if (vertex_hash.size()) { - while (B!=E) { + while (B != E) { - - Vector3* lv=vertex_hash.getptr(B->get()); + Vector3 *lv = vertex_hash.getptr(B->get()); if (lv) { - B->get().normal=lv->normalized(); + B->get().normal = lv->normalized(); } - B=B->next(); + B = B->next(); } } else { - B=E; + B = E; } vertex_hash.clear(); if (E) { - smooth=smooth_groups[count]; - print_line("SMOOTH AT "+itos(count)+": "+itos(smooth)); - + smooth = smooth_groups[count]; + print_line("SMOOTH AT " + itos(count) + ": " + itos(smooth)); } } - } - format|=Mesh::ARRAY_FORMAT_NORMAL; + format |= Mesh::ARRAY_FORMAT_NORMAL; if (was_indexed) { index(); smooth_groups.clear(); } - } -void SurfaceTool::set_material(const Ref<Material>& p_material) { +void SurfaceTool::set_material(const Ref<Material> &p_material) { - material=p_material; + material = p_material; } void SurfaceTool::clear() { - begun=false; - primitive=Mesh::PRIMITIVE_LINES; - format=0; + begun = false; + primitive = Mesh::PRIMITIVE_LINES; + format = 0; last_bones.clear(); last_weights.clear(); index_array.clear(); vertex_array.clear(); smooth_groups.clear(); - } void SurfaceTool::_bind_methods() { - ClassDB::bind_method(D_METHOD("begin","primitive"),&SurfaceTool::begin); - ClassDB::bind_method(D_METHOD("add_vertex","vertex"),&SurfaceTool::add_vertex); - ClassDB::bind_method(D_METHOD("add_color","color"),&SurfaceTool::add_color); - ClassDB::bind_method(D_METHOD("add_normal","normal"),&SurfaceTool::add_normal); - ClassDB::bind_method(D_METHOD("add_tangent","tangent"),&SurfaceTool::add_tangent); - ClassDB::bind_method(D_METHOD("add_uv","uv"),&SurfaceTool::add_uv); - ClassDB::bind_method(D_METHOD("add_uv2","uv2"),&SurfaceTool::add_uv2); - ClassDB::bind_method(D_METHOD("add_bones","bones"),&SurfaceTool::add_bones); - ClassDB::bind_method(D_METHOD("add_weights","weights"),&SurfaceTool::add_weights); - ClassDB::bind_method(D_METHOD("add_smooth_group","smooth"),&SurfaceTool::add_smooth_group); - ClassDB::bind_method(D_METHOD("add_triangle_fan", "vertexes", "uvs", "colors", "uv2s", "normals", "tangents"),&SurfaceTool::add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()),DEFVAL(Vector<Vector3>()), DEFVAL(Vector<Plane>())); - ClassDB::bind_method(D_METHOD("set_material","material:Material"),&SurfaceTool::set_material); - ClassDB::bind_method(D_METHOD("index"),&SurfaceTool::index); - ClassDB::bind_method(D_METHOD("deindex"),&SurfaceTool::deindex); + ClassDB::bind_method(D_METHOD("begin", "primitive"), &SurfaceTool::begin); + ClassDB::bind_method(D_METHOD("add_vertex", "vertex"), &SurfaceTool::add_vertex); + ClassDB::bind_method(D_METHOD("add_color", "color"), &SurfaceTool::add_color); + ClassDB::bind_method(D_METHOD("add_normal", "normal"), &SurfaceTool::add_normal); + ClassDB::bind_method(D_METHOD("add_tangent", "tangent"), &SurfaceTool::add_tangent); + ClassDB::bind_method(D_METHOD("add_uv", "uv"), &SurfaceTool::add_uv); + ClassDB::bind_method(D_METHOD("add_uv2", "uv2"), &SurfaceTool::add_uv2); + ClassDB::bind_method(D_METHOD("add_bones", "bones"), &SurfaceTool::add_bones); + ClassDB::bind_method(D_METHOD("add_weights", "weights"), &SurfaceTool::add_weights); + ClassDB::bind_method(D_METHOD("add_smooth_group", "smooth"), &SurfaceTool::add_smooth_group); + ClassDB::bind_method(D_METHOD("add_triangle_fan", "vertexes", "uvs", "colors", "uv2s", "normals", "tangents"), &SurfaceTool::add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Vector3>()), DEFVAL(Vector<Plane>())); + ClassDB::bind_method(D_METHOD("set_material", "material:Material"), &SurfaceTool::set_material); + ClassDB::bind_method(D_METHOD("index"), &SurfaceTool::index); + ClassDB::bind_method(D_METHOD("deindex"), &SurfaceTool::deindex); ///ClassDB::bind_method(D_METHOD("generate_flat_normals"),&SurfaceTool::generate_flat_normals); - ClassDB::bind_method(D_METHOD("generate_normals"),&SurfaceTool::generate_normals); + ClassDB::bind_method(D_METHOD("generate_normals"), &SurfaceTool::generate_normals); ClassDB::bind_method(D_METHOD("add_index", "index"), &SurfaceTool::add_index); - ClassDB::bind_method(D_METHOD("commit:Mesh","existing:Mesh"),&SurfaceTool::commit,DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("clear"),&SurfaceTool::clear); - + ClassDB::bind_method(D_METHOD("commit:Mesh", "existing:Mesh"), &SurfaceTool::commit, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("clear"), &SurfaceTool::clear); } - SurfaceTool::SurfaceTool() { - first=false; - begun=false; - primitive=Mesh::PRIMITIVE_LINES; - format=0; - + first = false; + begun = false; + primitive = Mesh::PRIMITIVE_LINES; + format = 0; } - diff --git a/scene/resources/surface_tool.h b/scene/resources/surface_tool.h index f859efbfe5..542c21e7b8 100644 --- a/scene/resources/surface_tool.h +++ b/scene/resources/surface_tool.h @@ -29,34 +29,32 @@ #ifndef SURFACE_TOOL_H #define SURFACE_TOOL_H -#include "scene/resources/mesh.h" #include "mikktspace.h" - +#include "scene/resources/mesh.h" class SurfaceTool : public Reference { - GDCLASS(SurfaceTool, Reference ); + GDCLASS(SurfaceTool, Reference); + public: struct Vertex { - Vector3 vertex; - Color color; - Vector3 normal; // normal, binormal, tangent - Vector3 binormal; - Vector3 tangent; - Vector2 uv; - Vector2 uv2; - Vector<int> bones; - Vector<float> weights; + Vector3 vertex; + Color color; + Vector3 normal; // normal, binormal, tangent + Vector3 binormal; + Vector3 tangent; + Vector2 uv; + Vector2 uv2; + Vector<int> bones; + Vector<float> weights; - bool operator==(const Vertex& p_vertex) const; + bool operator==(const Vertex &p_vertex) const; - Vertex() { } + Vertex() {} }; - private: - struct VertexHasher { static _FORCE_INLINE_ uint32_t hash(const Vertex &p_vtx); }; @@ -67,9 +65,9 @@ private: int format; Ref<Material> material; //arrays - List< Vertex > vertex_array; - List< int > index_array; - Map<int,bool> smooth_groups; + List<Vertex> vertex_array; + List<int> index_array; + Map<int, bool> smooth_groups; //memory Color last_color; @@ -80,57 +78,54 @@ private: Vector<float> last_weights; Plane last_tangent; - void _create_list(const Ref<Mesh>& p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index,int &lformat); - + void _create_list(const Ref<Mesh> &p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index, int &lformat); //mikktspace callbacks - static int mikktGetNumFaces(const SMikkTSpaceContext * pContext); - static int mikktGetNumVerticesOfFace(const SMikkTSpaceContext * pContext, const int iFace); - static void mikktGetPosition(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert); - static void mikktGetNormal(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert); - static void mikktGetTexCoord(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert); - static void mikktSetTSpaceBasic(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert); -protected: + static int mikktGetNumFaces(const SMikkTSpaceContext *pContext); + static int mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace); + static void mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert); + static void mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert); + static void mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert); + static void mikktSetTSpaceBasic(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert); +protected: static void _bind_methods(); public: - void begin(Mesh::PrimitiveType p_primitive); - void add_vertex( const Vector3& p_vertex); - void add_color( Color p_color ); - void add_normal( const Vector3& p_normal); - void add_tangent( const Plane& p_tangent ); - void add_uv( const Vector2& p_uv); - void add_uv2( const Vector2& p_uv); - void add_bones( const Vector<int>& p_indices); - void add_weights( const Vector<float>& p_weights); + void add_vertex(const Vector3 &p_vertex); + void add_color(Color p_color); + void add_normal(const Vector3 &p_normal); + void add_tangent(const Plane &p_tangent); + void add_uv(const Vector2 &p_uv); + void add_uv2(const Vector2 &p_uv); + void add_bones(const Vector<int> &p_indices); + void add_weights(const Vector<float> &p_weights); void add_smooth_group(bool p_smooth); - void add_triangle_fan( const Vector<Vector3>& p_vertexes, const Vector<Vector2>& p_uvs=Vector<Vector2>(), const Vector<Color>& p_colors=Vector<Color>(), const Vector<Vector2>& p_uv2s=Vector<Vector2>(), const Vector<Vector3>& p_normals=Vector<Vector3>(), const Vector<Plane>& p_tangents=Vector<Plane>() ); + void add_triangle_fan(const Vector<Vector3> &p_vertexes, const Vector<Vector2> &p_uvs = Vector<Vector2>(), const Vector<Color> &p_colors = Vector<Color>(), const Vector<Vector2> &p_uv2s = Vector<Vector2>(), const Vector<Vector3> &p_normals = Vector<Vector3>(), const Vector<Plane> &p_tangents = Vector<Plane>()); - void add_index( int p_index); + void add_index(int p_index); void index(); void deindex(); void generate_normals(); void generate_tangents(); - void add_to_format(int p_flags) { format|=p_flags; } + void add_to_format(int p_flags) { format |= p_flags; } - void set_material(const Ref<Material>& p_material); + void set_material(const Ref<Material> &p_material); void clear(); - List< Vertex > &get_vertex_array() { return vertex_array; } + List<Vertex> &get_vertex_array() { return vertex_array; } - void create_from(const Ref<Mesh>& p_existing, int p_surface); - void append_from(const Ref<Mesh>& p_existing, int p_surface,const Transform& p_xform); - Ref<Mesh> commit(const Ref<Mesh>& p_existing=Ref<Mesh>()); + void create_from(const Ref<Mesh> &p_existing, int p_surface); + void append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform &p_xform); + Ref<Mesh> commit(const Ref<Mesh> &p_existing = Ref<Mesh>()); SurfaceTool(); }; - #endif diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp index 62feb7b37c..f979c5c758 100644 --- a/scene/resources/texture.cpp +++ b/scene/resources/texture.cpp @@ -27,213 +27,184 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "texture.h" -#include "io/image_loader.h" #include "core/os/os.h" - - +#include "io/image_loader.h" Size2 Texture::get_size() const { - return Size2(get_width(),get_height()); + return Size2(get_width(), get_height()); } +void Texture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const { -void Texture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const { - - VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,Rect2( p_pos, get_size()),get_rid(),false,p_modulate,p_transpose); - + VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, get_size()), get_rid(), false, p_modulate, p_transpose); } -void Texture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const { - - VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,p_rect,get_rid(),p_tile,p_modulate,p_transpose); +void Texture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const { + VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, get_rid(), p_tile, p_modulate, p_transpose); } -void Texture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const{ +void Texture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const { - VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,p_rect,get_rid(),p_src_rect,p_modulate,p_transpose); + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, get_rid(), p_src_rect, p_modulate, p_transpose); } -bool Texture::get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const { +bool Texture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const { - r_rect=p_rect; - r_src_rect=p_src_rect; + r_rect = p_rect; + r_src_rect = p_src_rect; return true; } void Texture::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_width"),&Texture::get_width); - ClassDB::bind_method(D_METHOD("get_height"),&Texture::get_height); - ClassDB::bind_method(D_METHOD("get_size"),&Texture::get_size); - ClassDB::bind_method(D_METHOD("has_alpha"),&Texture::has_alpha); - ClassDB::bind_method(D_METHOD("set_flags","flags"),&Texture::set_flags); - ClassDB::bind_method(D_METHOD("get_flags"),&Texture::get_flags); - ClassDB::bind_method(D_METHOD("draw","canvas_item","pos","modulate","transpose"),&Texture::draw,DEFVAL(Color(1,1,1)),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("draw_rect","canvas_item","rect","tile","modulate","transpose"),&Texture::draw_rect,DEFVAL(Color(1,1,1)),DEFVAL(false)); - ClassDB::bind_method(D_METHOD("draw_rect_region","canvas_item","rect","src_rect","modulate","transpose"),&Texture::draw_rect_region,DEFVAL(Color(1,1,1)),DEFVAL(false)); - - BIND_CONSTANT( FLAG_MIPMAPS ); - BIND_CONSTANT( FLAG_REPEAT ); - BIND_CONSTANT( FLAG_FILTER ); - BIND_CONSTANT( FLAG_VIDEO_SURFACE ); - BIND_CONSTANT( FLAGS_DEFAULT ); - BIND_CONSTANT( FLAG_ANISOTROPIC_FILTER ); - BIND_CONSTANT( FLAG_CONVERT_TO_LINEAR ); - BIND_CONSTANT( FLAG_MIRRORED_REPEAT ); - + ClassDB::bind_method(D_METHOD("get_width"), &Texture::get_width); + ClassDB::bind_method(D_METHOD("get_height"), &Texture::get_height); + ClassDB::bind_method(D_METHOD("get_size"), &Texture::get_size); + ClassDB::bind_method(D_METHOD("has_alpha"), &Texture::has_alpha); + ClassDB::bind_method(D_METHOD("set_flags", "flags"), &Texture::set_flags); + ClassDB::bind_method(D_METHOD("get_flags"), &Texture::get_flags); + ClassDB::bind_method(D_METHOD("draw", "canvas_item", "pos", "modulate", "transpose"), &Texture::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("draw_rect", "canvas_item", "rect", "tile", "modulate", "transpose"), &Texture::draw_rect, DEFVAL(Color(1, 1, 1)), DEFVAL(false)); + ClassDB::bind_method(D_METHOD("draw_rect_region", "canvas_item", "rect", "src_rect", "modulate", "transpose"), &Texture::draw_rect_region, DEFVAL(Color(1, 1, 1)), DEFVAL(false)); + + BIND_CONSTANT(FLAG_MIPMAPS); + BIND_CONSTANT(FLAG_REPEAT); + BIND_CONSTANT(FLAG_FILTER); + BIND_CONSTANT(FLAG_VIDEO_SURFACE); + BIND_CONSTANT(FLAGS_DEFAULT); + BIND_CONSTANT(FLAG_ANISOTROPIC_FILTER); + BIND_CONSTANT(FLAG_CONVERT_TO_LINEAR); + BIND_CONSTANT(FLAG_MIRRORED_REPEAT); } Texture::Texture() { - - - } - - ///////////////////// - - - - void ImageTexture::reload_from_file() { - String path=get_path(); + String path = get_path(); if (!path.is_resource_file()) return; uint32_t flags = get_flags(); Image img; - Error err = ImageLoader::load_image(path,&img); - ERR_FAIL_COND(err!=OK); - - create_from_image(img,flags); + Error err = ImageLoader::load_image(path, &img); + ERR_FAIL_COND(err != OK); + create_from_image(img, flags); } -bool ImageTexture::_set(const StringName& p_name, const Variant& p_value) { +bool ImageTexture::_set(const StringName &p_name, const Variant &p_value) { - if (p_name=="image" && p_value.get_type()==Variant::IMAGE) - create_from_image( p_value,flags ); - else if (p_name=="flags") - if (w*h==0) - flags=p_value; + if (p_name == "image" && p_value.get_type() == Variant::IMAGE) + create_from_image(p_value, flags); + else if (p_name == "flags") + if (w * h == 0) + flags = p_value; else set_flags(p_value); - else if (p_name=="size") { + else if (p_name == "size") { Size2 s = p_value; - w=s.width; - h=s.height; - VisualServer::get_singleton()->texture_set_size_override(texture,w,h); - } else if (p_name=="storage") { - storage=Storage(p_value.operator int()); - } else if (p_name=="lossy_quality") { - lossy_storage_quality=p_value; - } else if (p_name=="_data") { + w = s.width; + h = s.height; + VisualServer::get_singleton()->texture_set_size_override(texture, w, h); + } else if (p_name == "storage") { + storage = Storage(p_value.operator int()); + } else if (p_name == "lossy_quality") { + lossy_storage_quality = p_value; + } else if (p_name == "_data") { _set_data(p_value); } else return false; return true; - } -bool ImageTexture::_get(const StringName& p_name,Variant &r_ret) const { - +bool ImageTexture::_get(const StringName &p_name, Variant &r_ret) const { - if (p_name=="image_data") { + if (p_name == "image_data") { - } else if (p_name=="image") - r_ret= get_data(); - else if (p_name=="flags") - r_ret= flags; - else if (p_name=="size") - r_ret=Size2(w,h); - else if (p_name=="storage") - r_ret= storage; - else if (p_name=="lossy_quality") - r_ret= lossy_storage_quality; + } else if (p_name == "image") + r_ret = get_data(); + else if (p_name == "flags") + r_ret = flags; + else if (p_name == "size") + r_ret = Size2(w, h); + else if (p_name == "storage") + r_ret = storage; + else if (p_name == "lossy_quality") + r_ret = lossy_storage_quality; else return false; return true; } +void ImageTexture::_get_property_list(List<PropertyInfo> *p_list) const { - - -void ImageTexture::_get_property_list( List<PropertyInfo> *p_list) const { - - - PropertyHint img_hint=PROPERTY_HINT_NONE; - if (storage==STORAGE_COMPRESS_LOSSY) { - img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSY; - } else if (storage==STORAGE_COMPRESS_LOSSLESS) { - img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS; + PropertyHint img_hint = PROPERTY_HINT_NONE; + if (storage == STORAGE_COMPRESS_LOSSY) { + img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSY; + } else if (storage == STORAGE_COMPRESS_LOSSLESS) { + img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS; } - - - p_list->push_back( PropertyInfo( Variant::INT, "flags", PROPERTY_HINT_FLAGS,"Mipmaps,Repeat,Filter,Anisotropic,sRGB,Mirrored Repeat") ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "image", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::VECTOR2, "size",PROPERTY_HINT_NONE, "")); - p_list->push_back( PropertyInfo( Variant::INT, "storage", PROPERTY_HINT_ENUM,"Uncompressed,Compress Lossy,Compress Lossless")); - p_list->push_back( PropertyInfo( Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE,"0.0,1.0,0.01" )); + p_list->push_back(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter,Anisotropic,sRGB,Mirrored Repeat")); + p_list->push_back(PropertyInfo(Variant::IMAGE, "image", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "size", PROPERTY_HINT_NONE, "")); + p_list->push_back(PropertyInfo(Variant::INT, "storage", PROPERTY_HINT_ENUM, "Uncompressed,Compress Lossy,Compress Lossless")); + p_list->push_back(PropertyInfo(Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE, "0.0,1.0,0.01")); } -void ImageTexture::_reload_hook(const RID& p_hook) { +void ImageTexture::_reload_hook(const RID &p_hook) { - String path=get_path(); + String path = get_path(); if (!path.is_resource_file()) return; Image img; - Error err = ImageLoader::load_image(path,&img); + Error err = ImageLoader::load_image(path, &img); - ERR_FAIL_COND(err!=OK); + ERR_FAIL_COND(err != OK); - - VisualServer::get_singleton()->texture_set_data(texture,img); + VisualServer::get_singleton()->texture_set_data(texture, img); _change_notify(); } -void ImageTexture::create(int p_width, int p_height,Image::Format p_format,uint32_t p_flags) { - - flags=p_flags; - VisualServer::get_singleton()->texture_allocate(texture,p_width, p_height, p_format, p_flags); - format=p_format; - w=p_width; - h=p_height; +void ImageTexture::create(int p_width, int p_height, Image::Format p_format, uint32_t p_flags) { + flags = p_flags; + VisualServer::get_singleton()->texture_allocate(texture, p_width, p_height, p_format, p_flags); + format = p_format; + w = p_width; + h = p_height; } -void ImageTexture::create_from_image(const Image& p_image, uint32_t p_flags) { +void ImageTexture::create_from_image(const Image &p_image, uint32_t p_flags) { - flags=p_flags; - w=p_image.get_width(); - h=p_image.get_height(); - format=p_image.get_format(); + flags = p_flags; + w = p_image.get_width(); + h = p_image.get_height(); + format = p_image.get_format(); - VisualServer::get_singleton()->texture_allocate(texture,p_image.get_width(),p_image.get_height(), p_image.get_format(), p_flags); - VisualServer::get_singleton()->texture_set_data(texture,p_image); + VisualServer::get_singleton()->texture_allocate(texture, p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags); + VisualServer::get_singleton()->texture_set_data(texture, p_image); _change_notify(); } void ImageTexture::set_flags(uint32_t p_flags) { - - -/* uint32_t cube = flags & FLAG_CUBEMAP; + /* uint32_t cube = flags & FLAG_CUBEMAP; if (flags == p_flags&cube) return; flags=p_flags|cube; */ - flags=p_flags; - VisualServer::get_singleton()->texture_set_flags(texture,p_flags); - + flags = p_flags; + VisualServer::get_singleton()->texture_set_flags(texture, p_flags); } uint32_t ImageTexture::get_flags() const { @@ -246,24 +217,23 @@ Image::Format ImageTexture::get_format() const { return format; } -void ImageTexture::load(const String& p_path) { - - Image img; - img.load(p_path); - create_from_image(img); +void ImageTexture::load(const String &p_path) { + Image img; + img.load(p_path); + create_from_image(img); } -void ImageTexture::set_data(const Image& p_image) { +void ImageTexture::set_data(const Image &p_image) { - VisualServer::get_singleton()->texture_set_data(texture,p_image); + VisualServer::get_singleton()->texture_set_data(texture, p_image); _change_notify(); } void ImageTexture::_resource_path_changed() { - String path=get_path(); + String path = get_path(); } Image ImageTexture::get_data() const { @@ -281,7 +251,6 @@ int ImageTexture::get_height() const { return h; } - RID ImageTexture::get_rid() const { return texture; @@ -289,7 +258,7 @@ RID ImageTexture::get_rid() const { void ImageTexture::fix_alpha_edges() { - if (format==Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) { + if (format == Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) { Image img = get_data(); img.fix_alpha_edges(); @@ -299,7 +268,7 @@ void ImageTexture::fix_alpha_edges() { void ImageTexture::premultiply_alpha() { - if (format==Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) { + if (format == Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) { Image img = get_data(); img.premultiply_alpha(); @@ -311,69 +280,64 @@ void ImageTexture::normal_to_xy() { Image img = get_data(); img.normalmap_to_xy(); - create_from_image(img,flags); + create_from_image(img, flags); } void ImageTexture::shrink_x2_and_keep_size() { - Size2 sizeov=get_size(); + Size2 sizeov = get_size(); Image img = get_data(); - img.resize(img.get_width()/2,img.get_height()/2,Image::INTERPOLATE_BILINEAR); - create_from_image(img,flags); + img.resize(img.get_width() / 2, img.get_height() / 2, Image::INTERPOLATE_BILINEAR); + create_from_image(img, flags); set_size_override(sizeov); - } bool ImageTexture::has_alpha() const { - return ( format==Image::FORMAT_LA8 || format==Image::FORMAT_RGBA8 ); + return (format == Image::FORMAT_LA8 || format == Image::FORMAT_RGBA8); } +void ImageTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const { -void ImageTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const { - - if ((w|h)==0) + if ((w | h) == 0) return; - VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,Rect2( p_pos, Size2(w,h)),texture,false,p_modulate,p_transpose); - + VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, Size2(w, h)), texture, false, p_modulate, p_transpose); } -void ImageTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const { +void ImageTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const { - if ((w|h)==0) + if ((w | h) == 0) return; - VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,p_rect,texture,p_tile,p_modulate,p_transpose); - + VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, texture, p_tile, p_modulate, p_transpose); } -void ImageTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const{ +void ImageTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const { - if ((w|h)==0) + if ((w | h) == 0) return; - VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,p_rect,texture,p_src_rect,p_modulate,p_transpose); + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, texture, p_src_rect, p_modulate, p_transpose); } -void ImageTexture::set_size_override(const Size2& p_size) { +void ImageTexture::set_size_override(const Size2 &p_size) { - Size2 s=p_size; - if (s.x!=0) - w=s.x; - if (s.y!=0) - h=s.y; - VisualServer::get_singleton()->texture_set_size_override(texture,w,h); + Size2 s = p_size; + if (s.x != 0) + w = s.x; + if (s.y != 0) + h = s.y; + VisualServer::get_singleton()->texture_set_size_override(texture, w, h); } -void ImageTexture::set_path(const String& p_path,bool p_take_over) { +void ImageTexture::set_path(const String &p_path, bool p_take_over) { if (texture.is_valid()) { - VisualServer::get_singleton()->texture_set_path(texture,p_path); + VisualServer::get_singleton()->texture_set_path(texture, p_path); } - Resource::set_path(p_path,p_take_over); + Resource::set_path(p_path, p_take_over); } - void ImageTexture::set_storage(Storage p_storage) { - storage=p_storage; + storage = p_storage; } ImageTexture::Storage ImageTexture::get_storage() const { @@ -383,7 +347,7 @@ ImageTexture::Storage ImageTexture::get_storage() const { void ImageTexture::set_lossy_storage_quality(float p_lossy_storage_quality) { - lossy_storage_quality=p_lossy_storage_quality; + lossy_storage_quality = p_lossy_storage_quality; } float ImageTexture::get_lossy_storage_quality() const { @@ -406,57 +370,50 @@ void ImageTexture::_set_data(Dictionary p_data) { void ImageTexture::_bind_methods() { - ClassDB::bind_method(D_METHOD("create","width","height","format","flags"),&ImageTexture::create,DEFVAL(FLAGS_DEFAULT)); - ClassDB::bind_method(D_METHOD("create_from_image","image","flags"),&ImageTexture::create_from_image,DEFVAL(FLAGS_DEFAULT)); - ClassDB::bind_method(D_METHOD("get_format"),&ImageTexture::get_format); - ClassDB::bind_method(D_METHOD("load","path"),&ImageTexture::load); - ClassDB::bind_method(D_METHOD("set_data","image"),&ImageTexture::set_data); - ClassDB::bind_method(D_METHOD("get_data","cube_side"),&ImageTexture::get_data); - ClassDB::bind_method(D_METHOD("set_storage","mode"),&ImageTexture::set_storage); - ClassDB::bind_method(D_METHOD("get_storage"),&ImageTexture::get_storage); - ClassDB::bind_method(D_METHOD("set_lossy_storage_quality","quality"),&ImageTexture::set_lossy_storage_quality); - ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"),&ImageTexture::get_lossy_storage_quality); - ClassDB::bind_method(D_METHOD("fix_alpha_edges"),&ImageTexture::fix_alpha_edges); - ClassDB::bind_method(D_METHOD("premultiply_alpha"),&ImageTexture::premultiply_alpha); - ClassDB::bind_method(D_METHOD("normal_to_xy"),&ImageTexture::normal_to_xy); - ClassDB::bind_method(D_METHOD("shrink_x2_and_keep_size"),&ImageTexture::shrink_x2_and_keep_size); - - ClassDB::bind_method(D_METHOD("set_size_override","size"),&ImageTexture::set_size_override); - ClassDB::set_method_flags(get_class_static(),_scs_create("fix_alpha_edges"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - ClassDB::set_method_flags(get_class_static(),_scs_create("premultiply_alpha"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - ClassDB::set_method_flags(get_class_static(),_scs_create("normal_to_xy"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - ClassDB::set_method_flags(get_class_static(),_scs_create("shrink_x2_and_keep_size"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); - ClassDB::bind_method(D_METHOD("_reload_hook","rid"),&ImageTexture::_reload_hook); - - - BIND_CONSTANT( STORAGE_RAW ); - BIND_CONSTANT( STORAGE_COMPRESS_LOSSY ); - BIND_CONSTANT( STORAGE_COMPRESS_LOSSLESS ); - - + ClassDB::bind_method(D_METHOD("create", "width", "height", "format", "flags"), &ImageTexture::create, DEFVAL(FLAGS_DEFAULT)); + ClassDB::bind_method(D_METHOD("create_from_image", "image", "flags"), &ImageTexture::create_from_image, DEFVAL(FLAGS_DEFAULT)); + ClassDB::bind_method(D_METHOD("get_format"), &ImageTexture::get_format); + ClassDB::bind_method(D_METHOD("load", "path"), &ImageTexture::load); + ClassDB::bind_method(D_METHOD("set_data", "image"), &ImageTexture::set_data); + ClassDB::bind_method(D_METHOD("get_data", "cube_side"), &ImageTexture::get_data); + ClassDB::bind_method(D_METHOD("set_storage", "mode"), &ImageTexture::set_storage); + ClassDB::bind_method(D_METHOD("get_storage"), &ImageTexture::get_storage); + ClassDB::bind_method(D_METHOD("set_lossy_storage_quality", "quality"), &ImageTexture::set_lossy_storage_quality); + ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"), &ImageTexture::get_lossy_storage_quality); + ClassDB::bind_method(D_METHOD("fix_alpha_edges"), &ImageTexture::fix_alpha_edges); + ClassDB::bind_method(D_METHOD("premultiply_alpha"), &ImageTexture::premultiply_alpha); + ClassDB::bind_method(D_METHOD("normal_to_xy"), &ImageTexture::normal_to_xy); + ClassDB::bind_method(D_METHOD("shrink_x2_and_keep_size"), &ImageTexture::shrink_x2_and_keep_size); + + ClassDB::bind_method(D_METHOD("set_size_override", "size"), &ImageTexture::set_size_override); + ClassDB::set_method_flags(get_class_static(), _scs_create("fix_alpha_edges"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::set_method_flags(get_class_static(), _scs_create("premultiply_alpha"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::set_method_flags(get_class_static(), _scs_create("normal_to_xy"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::set_method_flags(get_class_static(), _scs_create("shrink_x2_and_keep_size"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR); + ClassDB::bind_method(D_METHOD("_reload_hook", "rid"), &ImageTexture::_reload_hook); + + BIND_CONSTANT(STORAGE_RAW); + BIND_CONSTANT(STORAGE_COMPRESS_LOSSY); + BIND_CONSTANT(STORAGE_COMPRESS_LOSSLESS); } ImageTexture::ImageTexture() { - w=h=0; - flags=FLAGS_DEFAULT; + w = h = 0; + flags = FLAGS_DEFAULT; texture = VisualServer::get_singleton()->texture_create(); storage = STORAGE_RAW; - lossy_storage_quality=0.7; - - + lossy_storage_quality = 0.7; } - ImageTexture::~ImageTexture() { - VisualServer::get_singleton()->free( texture ); + VisualServer::get_singleton()->free(texture); } ////////////////////////////////////////// - -void StreamTexture::_requested_3d(void* p_ud) { +void StreamTexture::_requested_3d(void *p_ud) { StreamTexture *st = (StreamTexture *)p_ud; Ref<StreamTexture> stex(st); @@ -464,18 +421,16 @@ void StreamTexture::_requested_3d(void* p_ud) { request_3d_callback(stex); } -void StreamTexture::_requested_srgb(void* p_ud) { +void StreamTexture::_requested_srgb(void *p_ud) { StreamTexture *st = (StreamTexture *)p_ud; Ref<StreamTexture> stex(st); ERR_FAIL_COND(!request_srgb_callback); request_srgb_callback(stex); - } -StreamTexture::TextureFormatRequestCallback StreamTexture::request_3d_callback=NULL; -StreamTexture::TextureFormatRequestCallback StreamTexture::request_srgb_callback=NULL; - +StreamTexture::TextureFormatRequestCallback StreamTexture::request_3d_callback = NULL; +StreamTexture::TextureFormatRequestCallback StreamTexture::request_srgb_callback = NULL; uint32_t StreamTexture::get_flags() const { @@ -486,81 +441,77 @@ Image::Format StreamTexture::get_format() const { return format; } +Error StreamTexture::_load_data(const String &p_path, int &tw, int &th, int &flags, Image &image, int p_size_limit) { -Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,Image& image,int p_size_limit) { - - - FileAccess *f = FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!f,ERR_CANT_OPEN); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); uint8_t header[4]; - f->get_buffer(header,4); - if (header[0]!='G' || header[1]!='D' || header[2]!='S' || header[3]!='T') { + f->get_buffer(header, 4); + if (header[0] != 'G' || header[1] != 'D' || header[2] != 'S' || header[3] != 'T') { memdelete(f); - ERR_FAIL_COND_V(header[0]!='G' || header[1]!='D' || header[2]!='S' || header[3]!='T',ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(header[0] != 'G' || header[1] != 'D' || header[2] != 'S' || header[3] != 'T', ERR_FILE_CORRUPT); } tw = f->get_32(); th = f->get_32(); - flags= f->get_32(); //texture flags! + flags = f->get_32(); //texture flags! uint32_t df = f->get_32(); //data format - print_line("width: "+itos(tw)); - print_line("height: "+itos(th)); - print_line("flags: "+itos(flags)); - print_line("df: "+itos(df)); + print_line("width: " + itos(tw)); + print_line("height: " + itos(th)); + print_line("flags: " + itos(flags)); + print_line("df: " + itos(df)); - - if (request_3d_callback && df&FORMAT_BIT_DETECT_3D) { - print_line("request detect 3D at "+p_path); - VS::get_singleton()->texture_set_detect_3d_callback(texture,_requested_3d,this); + if (request_3d_callback && df & FORMAT_BIT_DETECT_3D) { + print_line("request detect 3D at " + p_path); + VS::get_singleton()->texture_set_detect_3d_callback(texture, _requested_3d, this); } else { - print_line("not requesting detect 3D at "+p_path); - VS::get_singleton()->texture_set_detect_3d_callback(texture,NULL,NULL); + print_line("not requesting detect 3D at " + p_path); + VS::get_singleton()->texture_set_detect_3d_callback(texture, NULL, NULL); } - if (request_srgb_callback && df&FORMAT_BIT_DETECT_SRGB) { - print_line("request detect srgb at "+p_path); - VS::get_singleton()->texture_set_detect_srgb_callback(texture,_requested_srgb,this); + if (request_srgb_callback && df & FORMAT_BIT_DETECT_SRGB) { + print_line("request detect srgb at " + p_path); + VS::get_singleton()->texture_set_detect_srgb_callback(texture, _requested_srgb, this); } else { - VS::get_singleton()->texture_set_detect_srgb_callback(texture,NULL,NULL); - print_line("not requesting detect srgb at "+p_path); + VS::get_singleton()->texture_set_detect_srgb_callback(texture, NULL, NULL); + print_line("not requesting detect srgb at " + p_path); } - if (!(df&FORMAT_BIT_STREAM)) { - p_size_limit=0; + if (!(df & FORMAT_BIT_STREAM)) { + p_size_limit = 0; } - - if (df&FORMAT_BIT_LOSSLESS || df&FORMAT_BIT_LOSSY) { + if (df & FORMAT_BIT_LOSSLESS || df & FORMAT_BIT_LOSSY) { //look for a PNG or WEBP file inside - int sw=tw; - int sh=th; + int sw = tw; + int sh = th; uint32_t mipmaps = f->get_32(); uint32_t size = f->get_32(); - print_line("mipmaps: "+itos(mipmaps)); + print_line("mipmaps: " + itos(mipmaps)); - while(mipmaps>1 && p_size_limit>0 && (sw>p_size_limit || sh>p_size_limit)) { + while (mipmaps > 1 && p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) { - f->seek(f->get_pos()+size); + f->seek(f->get_pos() + size); mipmaps = f->get_32(); size = f->get_32(); - sw=MAX(sw>>1,1); - sh=MAX(sh>>1,1); + sw = MAX(sw >> 1, 1); + sh = MAX(sh >> 1, 1); mipmaps--; } //mipmaps need to be read independently, they will be later combined Vector<Image> mipmap_images; - int total_size=0; + int total_size = 0; - for(int i=0;i<mipmaps;i++) { + for (int i = 0; i < mipmaps; i++) { - if (i>0) { + if (i > 0) { size = f->get_32(); } @@ -568,11 +519,11 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags, pv.resize(size); { PoolVector<uint8_t>::Write w = pv.write(); - f->get_buffer(w.ptr(),size); + f->get_buffer(w.ptr(), size); } Image img; - if (df&FORMAT_BIT_LOSSLESS) { + if (df & FORMAT_BIT_LOSSLESS) { img = Image::lossless_unpacker(pv); } else { img = Image::lossy_unpacker(pv); @@ -580,21 +531,20 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags, if (img.empty()) { memdelete(f); - ERR_FAIL_COND_V(img.empty(),ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(img.empty(), ERR_FILE_CORRUPT); } - total_size+=img.get_data().size(); + total_size += img.get_data().size(); mipmap_images.push_back(img); } - print_line("mipmap read total: "+itos(mipmap_images.size())); - + print_line("mipmap read total: " + itos(mipmap_images.size())); memdelete(f); //no longer needed - if (mipmap_images.size()==1) { + if (mipmap_images.size() == 1) { - image=mipmap_images[0]; + image = mipmap_images[0]; return OK; } else { @@ -602,82 +552,80 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags, img_data.resize(total_size); { - PoolVector<uint8_t>::Write w=img_data.write(); + PoolVector<uint8_t>::Write w = img_data.write(); - int ofs=0; - for(int i=0;i<mipmap_images.size();i++) { + int ofs = 0; + for (int i = 0; i < mipmap_images.size(); i++) { PoolVector<uint8_t> id = mipmap_images[i].get_data(); int len = id.size(); PoolVector<uint8_t>::Read r = id.read(); - copymem(&w[ofs],r.ptr(),len); - ofs+=len; + copymem(&w[ofs], r.ptr(), len); + ofs += len; } } - image = Image(sw,sh,true,mipmap_images[0].get_format(),img_data); + image = Image(sw, sh, true, mipmap_images[0].get_format(), img_data); return OK; } } else { //look for regular format - Image::Format format = (Image::Format)(df&FORMAT_MASK_IMAGE_FORMAT); - bool mipmaps = df&FORMAT_BIT_HAS_MIPMAPS; + Image::Format format = (Image::Format)(df & FORMAT_MASK_IMAGE_FORMAT); + bool mipmaps = df & FORMAT_BIT_HAS_MIPMAPS; if (!mipmaps) { - int size = Image::get_image_data_size(tw,th,format,0); + int size = Image::get_image_data_size(tw, th, format, 0); PoolVector<uint8_t> img_data; img_data.resize(size); { - PoolVector<uint8_t>::Write w=img_data.write(); - f->get_buffer(w.ptr(),size); + PoolVector<uint8_t>::Write w = img_data.write(); + f->get_buffer(w.ptr(), size); } memdelete(f); - image = Image(tw,th,false,format,img_data); + image = Image(tw, th, false, format, img_data); return OK; } else { - int sw=tw; - int sh=th; - - int mipmaps = Image::get_image_required_mipmaps(tw,th,format); - int total_size = Image::get_image_data_size(tw,th,format,mipmaps); - int idx=0; - int ofs=0; + int sw = tw; + int sh = th; + int mipmaps = Image::get_image_required_mipmaps(tw, th, format); + int total_size = Image::get_image_data_size(tw, th, format, mipmaps); + int idx = 0; + int ofs = 0; - while(mipmaps>1 && p_size_limit>0 && (sw>p_size_limit || sh>p_size_limit)) { + while (mipmaps > 1 && p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) { - sw=MAX(sw>>1,1); - sh=MAX(sh>>1,1); + sw = MAX(sw >> 1, 1); + sh = MAX(sh >> 1, 1); mipmaps--; idx++; } - if (idx>0) { - ofs=Image::get_image_data_size(tw,th,format,idx-1); + if (idx > 0) { + ofs = Image::get_image_data_size(tw, th, format, idx - 1); } - if (total_size - ofs <=0) { + if (total_size - ofs <= 0) { memdelete(f); ERR_FAIL_V(ERR_FILE_CORRUPT); } - f->seek(f->get_pos()+ofs); - + f->seek(f->get_pos() + ofs); PoolVector<uint8_t> img_data; img_data.resize(total_size - ofs); { - PoolVector<uint8_t>::Write w=img_data.write(); - int bytes = f->get_buffer(w.ptr(),total_size - ofs); - print_line("requested read: "+itos(total_size - ofs)+" but got: "+itos(bytes)); + PoolVector<uint8_t>::Write w = img_data.write(); + int bytes = f->get_buffer(w.ptr(), total_size - ofs); + print_line("requested read: " + itos(total_size - ofs) + " but got: " + itos(bytes)); memdelete(f); @@ -686,7 +634,7 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags, } } - image = Image(sw,sh,true,format,img_data); + image = Image(sw, sh, true, format, img_data); return OK; } @@ -695,23 +643,22 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags, return ERR_BUG; //unreachable } -Error StreamTexture::load(const String& p_path) { - +Error StreamTexture::load(const String &p_path) { - int lw,lh,lflags; + int lw, lh, lflags; Image image; - Error err = _load_data(p_path,lw,lh,lflags,image); + Error err = _load_data(p_path, lw, lh, lflags, image); if (err) return err; - VS::get_singleton()->texture_allocate(texture,image.get_width(),image.get_height(),image.get_format(),lflags); - VS::get_singleton()->texture_set_data(texture,image); + VS::get_singleton()->texture_allocate(texture, image.get_width(), image.get_height(), image.get_format(), lflags); + VS::get_singleton()->texture_set_data(texture, image); - w=lw; - h=lh; - flags=lflags; - path_to_file=p_path; - format=image.get_format(); + w = lw; + h = lh; + flags = lflags; + path_to_file = p_path; + format = image.get_format(); return OK; } @@ -733,26 +680,23 @@ RID StreamTexture::get_rid() const { return texture; } +void StreamTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const { -void StreamTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const { - - if ((w|h)==0) + if ((w | h) == 0) return; - VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,Rect2( p_pos, Size2(w,h)),texture,false,p_modulate,p_transpose); - + VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, Size2(w, h)), texture, false, p_modulate, p_transpose); } -void StreamTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const { +void StreamTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const { - if ((w|h)==0) + if ((w | h) == 0) return; - VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,p_rect,texture,p_tile,p_modulate,p_transpose); - + VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, texture, p_tile, p_modulate, p_transpose); } -void StreamTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const{ +void StreamTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const { - if ((w|h)==0) + if ((w | h) == 0) return; - VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,p_rect,texture,p_src_rect,p_modulate,p_transpose); + VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, texture, p_src_rect, p_modulate, p_transpose); } bool StreamTexture::has_alpha() const { @@ -765,16 +709,15 @@ Image StreamTexture::get_data() const { return VS::get_singleton()->texture_get_data(texture); } -void StreamTexture::set_flags(uint32_t p_flags){ - +void StreamTexture::set_flags(uint32_t p_flags) { } void StreamTexture::reload_from_file() { #ifdef TOOLS_ENABLED String ipath = get_import_path(); - if (ipath.is_resource_file() && ipath!=path_to_file) { - path_to_file=ipath; + if (ipath.is_resource_file() && ipath != path_to_file) { + path_to_file = ipath; } #endif load(path_to_file); @@ -782,19 +725,18 @@ void StreamTexture::reload_from_file() { void StreamTexture::_bind_methods() { - ClassDB::bind_method(D_METHOD("load","path"),&StreamTexture::load); - ClassDB::bind_method(D_METHOD("get_load_path"),&StreamTexture::get_load_path); + ClassDB::bind_method(D_METHOD("load", "path"), &StreamTexture::load); + ClassDB::bind_method(D_METHOD("get_load_path"), &StreamTexture::get_load_path); - ADD_PROPERTY( PropertyInfo(Variant::STRING,"load_path",PROPERTY_HINT_FILE,"*.stex"),"load","get_load_path"); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "load_path", PROPERTY_HINT_FILE, "*.stex"), "load", "get_load_path"); } - StreamTexture::StreamTexture() { - format=Image::FORMAT_MAX; - flags=0; - w=0; - h=0; + format = Image::FORMAT_MAX; + flags = 0; + w = 0; + h = 0; texture = VS::get_singleton()->texture_create(); } @@ -804,61 +746,53 @@ StreamTexture::~StreamTexture() { VS::get_singleton()->free(texture); } - - -RES ResourceFormatLoaderStreamTexture::load(const String &p_path,const String& p_original_path,Error *r_error) { +RES ResourceFormatLoaderStreamTexture::load(const String &p_path, const String &p_original_path, Error *r_error) { Ref<StreamTexture> st; st.instance(); Error err = st->load(p_path); if (r_error) - *r_error=err; - if (err!=OK) + *r_error = err; + if (err != OK) return RES(); return st; } -void ResourceFormatLoaderStreamTexture::get_recognized_extensions(List<String> *p_extensions) const{ +void ResourceFormatLoaderStreamTexture::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("stex"); } -bool ResourceFormatLoaderStreamTexture::handles_type(const String& p_type) const{ - return p_type=="StreamTexture"; - +bool ResourceFormatLoaderStreamTexture::handles_type(const String &p_type) const { + return p_type == "StreamTexture"; } -String ResourceFormatLoaderStreamTexture::get_resource_type(const String &p_path) const{ +String ResourceFormatLoaderStreamTexture::get_resource_type(const String &p_path) const { - if (p_path.get_extension().to_lower()=="stex") + if (p_path.get_extension().to_lower() == "stex") return "StreamTexture"; return ""; } - - - - ////////////////////////////////////////// - int AtlasTexture::get_width() const { - if (region.size.width==0) { + if (region.size.width == 0) { if (atlas.is_valid()) return atlas->get_width(); return 1; } else { - return region.size.width+margin.size.width; + return region.size.width + margin.size.width; } } int AtlasTexture::get_height() const { - if (region.size.height==0) { + if (region.size.height == 0) { if (atlas.is_valid()) return atlas->get_height(); return 1; } else { - return region.size.height+margin.size.height; + return region.size.height + margin.size.height; } } RID AtlasTexture::get_rid() const { @@ -881,11 +815,9 @@ void AtlasTexture::set_flags(uint32_t p_flags) { if (atlas.is_valid()) atlas->set_flags(p_flags); - } - -uint32_t AtlasTexture::get_flags() const{ +uint32_t AtlasTexture::get_flags() const { if (atlas.is_valid()) return atlas->get_flags(); @@ -893,24 +825,23 @@ uint32_t AtlasTexture::get_flags() const{ return 0; } -void AtlasTexture::set_atlas(const Ref<Texture>& p_atlas){ +void AtlasTexture::set_atlas(const Ref<Texture> &p_atlas) { - if (atlas==p_atlas) + if (atlas == p_atlas) return; - atlas=p_atlas; + atlas = p_atlas; emit_changed(); emit_signal("atlas_changed"); } -Ref<Texture> AtlasTexture::get_atlas() const{ +Ref<Texture> AtlasTexture::get_atlas() const { return atlas; } -void AtlasTexture::set_region(const Rect2& p_region) { +void AtlasTexture::set_region(const Rect2 &p_region) { - region=p_region; + region = p_region; emit_changed(); - } Rect2 AtlasTexture::get_region() const { @@ -918,11 +849,10 @@ Rect2 AtlasTexture::get_region() const { return region; } -void AtlasTexture::set_margin(const Rect2& p_margin) { +void AtlasTexture::set_margin(const Rect2 &p_margin) { - margin=p_margin; + margin = p_margin; emit_changed(); - } Rect2 AtlasTexture::get_margin() const { @@ -932,144 +862,128 @@ Rect2 AtlasTexture::get_margin() const { void AtlasTexture::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_atlas","atlas:Texture"),&AtlasTexture::set_atlas); - ClassDB::bind_method(D_METHOD("get_atlas:Texture"),&AtlasTexture::get_atlas); + ClassDB::bind_method(D_METHOD("set_atlas", "atlas:Texture"), &AtlasTexture::set_atlas); + ClassDB::bind_method(D_METHOD("get_atlas:Texture"), &AtlasTexture::get_atlas); - ClassDB::bind_method(D_METHOD("set_region","region"),&AtlasTexture::set_region); - ClassDB::bind_method(D_METHOD("get_region"),&AtlasTexture::get_region); + ClassDB::bind_method(D_METHOD("set_region", "region"), &AtlasTexture::set_region); + ClassDB::bind_method(D_METHOD("get_region"), &AtlasTexture::get_region); - ClassDB::bind_method(D_METHOD("set_margin","margin"),&AtlasTexture::set_margin); - ClassDB::bind_method(D_METHOD("get_margin"),&AtlasTexture::get_margin); + ClassDB::bind_method(D_METHOD("set_margin", "margin"), &AtlasTexture::set_margin); + ClassDB::bind_method(D_METHOD("get_margin"), &AtlasTexture::get_margin); ADD_SIGNAL(MethodInfo("atlas_changed")); - ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "atlas", PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_atlas","get_atlas") ; - ADD_PROPERTY( PropertyInfo( Variant::RECT2, "region"), "set_region","get_region") ; - ADD_PROPERTY( PropertyInfo( Variant::RECT2, "margin"), "set_margin","get_margin") ; - + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "atlas", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_atlas", "get_atlas"); + ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region"), "set_region", "get_region"); + ADD_PROPERTY(PropertyInfo(Variant::RECT2, "margin"), "set_margin", "get_margin"); } +void AtlasTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const { - - -void AtlasTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const { - - Rect2 rc=region; + Rect2 rc = region; if (!atlas.is_valid()) return; - if (rc.size.width==0) { - rc.size.width=atlas->get_width(); + if (rc.size.width == 0) { + rc.size.width = atlas->get_width(); } - if (rc.size.height==0) { - rc.size.height=atlas->get_height(); + if (rc.size.height == 0) { + rc.size.height = atlas->get_height(); } - VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,Rect2(p_pos+margin.pos,rc.size),atlas->get_rid(),rc,p_modulate,p_transpose); + VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(p_pos + margin.pos, rc.size), atlas->get_rid(), rc, p_modulate, p_transpose); } -void AtlasTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const { +void AtlasTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const { - Rect2 rc=region; + Rect2 rc = region; if (!atlas.is_valid()) return; - if (rc.size.width==0) { - rc.size.width=atlas->get_width(); + if (rc.size.width == 0) { + rc.size.width = atlas->get_width(); } - if (rc.size.height==0) { - rc.size.height=atlas->get_height(); + if (rc.size.height == 0) { + rc.size.height = atlas->get_height(); } - Vector2 scale = p_rect.size / (region.size+margin.size); - Rect2 dr( p_rect.pos+margin.pos*scale,rc.size*scale ); - - VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,dr,atlas->get_rid(),rc,p_modulate,p_transpose); + Vector2 scale = p_rect.size / (region.size + margin.size); + Rect2 dr(p_rect.pos + margin.pos * scale, rc.size * scale); + VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, dr, atlas->get_rid(), rc, p_modulate, p_transpose); } -void AtlasTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const { +void AtlasTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const { //this might not necesarily work well if using a rect, needs to be fixed properly - Rect2 rc=region; + Rect2 rc = region; if (!atlas.is_valid()) return; - Rect2 src=p_src_rect; - src.pos+=(rc.pos-margin.pos); + Rect2 src = p_src_rect; + src.pos += (rc.pos - margin.pos); Rect2 src_c = rc.clip(src); - if (src_c.size==Size2()) + if (src_c.size == Size2()) return; - Vector2 ofs = (src_c.pos-src.pos); + Vector2 ofs = (src_c.pos - src.pos); Vector2 scale = p_rect.size / p_src_rect.size; - if(scale.x < 0) - { - float mx = (margin.size.width - margin.pos.x); - mx -= margin.pos.x; - ofs.x = -(ofs.x + mx); - } - if(scale.y < 0) - { - float my = margin.size.height - margin.pos.y; - my -= margin.pos.y; - ofs.y = -(ofs.y + my); - } - Rect2 dr( p_rect.pos+ofs*scale,src_c.size*scale ); + if (scale.x < 0) { + float mx = (margin.size.width - margin.pos.x); + mx -= margin.pos.x; + ofs.x = -(ofs.x + mx); + } + if (scale.y < 0) { + float my = margin.size.height - margin.pos.y; + my -= margin.pos.y; + ofs.y = -(ofs.y + my); + } + Rect2 dr(p_rect.pos + ofs * scale, src_c.size * scale); - VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,dr,atlas->get_rid(),src_c,p_modulate,p_transpose); + VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, dr, atlas->get_rid(), src_c, p_modulate, p_transpose); } -bool AtlasTexture::get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const { +bool AtlasTexture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const { - Rect2 rc=region; + Rect2 rc = region; if (!atlas.is_valid()) return false; - Rect2 src=p_src_rect; - src.pos+=(rc.pos-margin.pos); + Rect2 src = p_src_rect; + src.pos += (rc.pos - margin.pos); Rect2 src_c = rc.clip(src); - if (src_c.size==Size2()) + if (src_c.size == Size2()) return false; - Vector2 ofs = (src_c.pos-src.pos); + Vector2 ofs = (src_c.pos - src.pos); Vector2 scale = p_rect.size / p_src_rect.size; - if(scale.x < 0) - { - float mx = (margin.size.width - margin.pos.x); - mx -= margin.pos.x; - ofs.x = -(ofs.x + mx); - } - if(scale.y < 0) - { - float my = margin.size.height - margin.pos.y; - my -= margin.pos.y; - ofs.y = -(ofs.y + my); - } - Rect2 dr( p_rect.pos+ofs*scale,src_c.size*scale ); - - - - r_rect=dr; - r_src_rect=src_c; + if (scale.x < 0) { + float mx = (margin.size.width - margin.pos.x); + mx -= margin.pos.x; + ofs.x = -(ofs.x + mx); + } + if (scale.y < 0) { + float my = margin.size.height - margin.pos.y; + my -= margin.pos.y; + ofs.y = -(ofs.y + my); + } + Rect2 dr(p_rect.pos + ofs * scale, src_c.size * scale); + + r_rect = dr; + r_src_rect = src_c; return true; } - AtlasTexture::AtlasTexture() { - - } - ////////////////////////////////////////// - int LargeTexture::get_width() const { return size.width; @@ -1085,7 +999,7 @@ RID LargeTexture::get_rid() const { bool LargeTexture::has_alpha() const { - for(int i=0;i<pieces.size();i++) { + for (int i = 0; i < pieces.size(); i++) { if (pieces[i].texture->has_alpha()) return true; } @@ -1095,14 +1009,12 @@ bool LargeTexture::has_alpha() const { void LargeTexture::set_flags(uint32_t p_flags) { - for(int i=0;i<pieces.size();i++) { + for (int i = 0; i < pieces.size(); i++) { pieces[i].texture->set_flags(p_flags); } - } - -uint32_t LargeTexture::get_flags() const{ +uint32_t LargeTexture::get_flags() const { if (pieces.size()) return pieces[0].texture->get_flags(); @@ -1110,168 +1022,149 @@ uint32_t LargeTexture::get_flags() const{ return 0; } - -int LargeTexture::add_piece(const Point2& p_offset,const Ref<Texture>& p_texture) { +int LargeTexture::add_piece(const Point2 &p_offset, const Ref<Texture> &p_texture) { ERR_FAIL_COND_V(p_texture.is_null(), -1); Piece p; - p.offset=p_offset; - p.texture=p_texture; + p.offset = p_offset; + p.texture = p_texture; pieces.push_back(p); return pieces.size() - 1; } -void LargeTexture::set_piece_offset(int p_idx, const Point2& p_offset) { +void LargeTexture::set_piece_offset(int p_idx, const Point2 &p_offset) { ERR_FAIL_INDEX(p_idx, pieces.size()); pieces[p_idx].offset = p_offset; }; -void LargeTexture::set_piece_texture(int p_idx, const Ref<Texture>& p_texture) { +void LargeTexture::set_piece_texture(int p_idx, const Ref<Texture> &p_texture) { ERR_FAIL_INDEX(p_idx, pieces.size()); pieces[p_idx].texture = p_texture; }; +void LargeTexture::set_size(const Size2 &p_size) { - -void LargeTexture::set_size(const Size2& p_size){ - - size=p_size; + size = p_size; } -void LargeTexture::clear(){ +void LargeTexture::clear() { pieces.clear(); - size=Size2i(); + size = Size2i(); } Array LargeTexture::_get_data() const { Array arr; - for(int i=0;i<pieces.size();i++) { + for (int i = 0; i < pieces.size(); i++) { arr.push_back(pieces[i].offset); arr.push_back(pieces[i].texture); } arr.push_back(Size2(size)); return arr; - } -void LargeTexture::_set_data(const Array& p_array) { +void LargeTexture::_set_data(const Array &p_array) { - ERR_FAIL_COND(p_array.size()<1); - ERR_FAIL_COND(!(p_array.size()&1)); + ERR_FAIL_COND(p_array.size() < 1); + ERR_FAIL_COND(!(p_array.size() & 1)); clear(); - for(int i=0;i<p_array.size()-1;i+=2) { - add_piece(p_array[i],p_array[i+1]); + for (int i = 0; i < p_array.size() - 1; i += 2) { + add_piece(p_array[i], p_array[i + 1]); } - size=Size2(p_array[p_array.size()-1]); + size = Size2(p_array[p_array.size() - 1]); } int LargeTexture::get_piece_count() const { return pieces.size(); } -Vector2 LargeTexture::get_piece_offset(int p_idx) const{ +Vector2 LargeTexture::get_piece_offset(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,pieces.size(),Vector2()); + ERR_FAIL_INDEX_V(p_idx, pieces.size(), Vector2()); return pieces[p_idx].offset; } -Ref<Texture> LargeTexture::get_piece_texture(int p_idx) const{ +Ref<Texture> LargeTexture::get_piece_texture(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,pieces.size(),Ref<Texture>()); + ERR_FAIL_INDEX_V(p_idx, pieces.size(), Ref<Texture>()); return pieces[p_idx].texture; - } - void LargeTexture::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_piece","ofs","texture:Texture"),&LargeTexture::add_piece); - ClassDB::bind_method(D_METHOD("set_piece_offset", "idx", "ofs"),&LargeTexture::set_piece_offset); - ClassDB::bind_method(D_METHOD("set_piece_texture","idx", "texture:Texture"),&LargeTexture::set_piece_texture); - ClassDB::bind_method(D_METHOD("set_size","size"),&LargeTexture::set_size); - ClassDB::bind_method(D_METHOD("clear"),&LargeTexture::clear); + ClassDB::bind_method(D_METHOD("add_piece", "ofs", "texture:Texture"), &LargeTexture::add_piece); + ClassDB::bind_method(D_METHOD("set_piece_offset", "idx", "ofs"), &LargeTexture::set_piece_offset); + ClassDB::bind_method(D_METHOD("set_piece_texture", "idx", "texture:Texture"), &LargeTexture::set_piece_texture); + ClassDB::bind_method(D_METHOD("set_size", "size"), &LargeTexture::set_size); + ClassDB::bind_method(D_METHOD("clear"), &LargeTexture::clear); - ClassDB::bind_method(D_METHOD("get_piece_count"),&LargeTexture::get_piece_count); - ClassDB::bind_method(D_METHOD("get_piece_offset","idx"),&LargeTexture::get_piece_offset); - ClassDB::bind_method(D_METHOD("get_piece_texture:Texture","idx"),&LargeTexture::get_piece_texture); + ClassDB::bind_method(D_METHOD("get_piece_count"), &LargeTexture::get_piece_count); + ClassDB::bind_method(D_METHOD("get_piece_offset", "idx"), &LargeTexture::get_piece_offset); + ClassDB::bind_method(D_METHOD("get_piece_texture:Texture", "idx"), &LargeTexture::get_piece_texture); - ClassDB::bind_method(D_METHOD("_set_data","data"),&LargeTexture::_set_data); - ClassDB::bind_method(D_METHOD("_get_data"),&LargeTexture::_get_data); - - ADD_PROPERTY( PropertyInfo( Variant::ARRAY, "_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_data","_get_data") ; + ClassDB::bind_method(D_METHOD("_set_data", "data"), &LargeTexture::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &LargeTexture::_get_data); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); } +void LargeTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const { - - -void LargeTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const { - - for(int i=0;i<pieces.size();i++) { + for (int i = 0; i < pieces.size(); i++) { // TODO - pieces[i].texture->draw(p_canvas_item,pieces[i].offset+p_pos,p_modulate,p_transpose); + pieces[i].texture->draw(p_canvas_item, pieces[i].offset + p_pos, p_modulate, p_transpose); } } -void LargeTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const { +void LargeTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const { //tiling not supported for this - if (size.x==0 || size.y==0) + if (size.x == 0 || size.y == 0) return; - Size2 scale = p_rect.size/size; + Size2 scale = p_rect.size / size; - for(int i=0;i<pieces.size();i++) { + for (int i = 0; i < pieces.size(); i++) { // TODO - pieces[i].texture->draw_rect(p_canvas_item,Rect2(pieces[i].offset*scale+p_rect.pos,pieces[i].texture->get_size()*scale),false,p_modulate,p_transpose); + pieces[i].texture->draw_rect(p_canvas_item, Rect2(pieces[i].offset * scale + p_rect.pos, pieces[i].texture->get_size() * scale), false, p_modulate, p_transpose); } } -void LargeTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const { - +void LargeTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const { //tiling not supported for this - if (p_src_rect.size.x==0 || p_src_rect.size.y==0) + if (p_src_rect.size.x == 0 || p_src_rect.size.y == 0) return; - Size2 scale = p_rect.size/p_src_rect.size; + Size2 scale = p_rect.size / p_src_rect.size; - for(int i=0;i<pieces.size();i++) { + for (int i = 0; i < pieces.size(); i++) { // TODO - Rect2 rect( pieces[i].offset, pieces[i].texture->get_size()); + Rect2 rect(pieces[i].offset, pieces[i].texture->get_size()); if (!p_src_rect.intersects(rect)) continue; Rect2 local = p_src_rect.clip(rect); Rect2 target = local; - target.size*=scale; - target.pos=p_rect.pos+(p_src_rect.pos+rect.pos)*scale; - local.pos-=rect.pos; - pieces[i].texture->draw_rect_region(p_canvas_item,target,local,p_modulate,p_transpose); + target.size *= scale; + target.pos = p_rect.pos + (p_src_rect.pos + rect.pos) * scale; + local.pos -= rect.pos; + pieces[i].texture->draw_rect_region(p_canvas_item, target, local, p_modulate, p_transpose); } - } - LargeTexture::LargeTexture() { - - } - /////////////////////////////////////////////// - - - void CubeMap::set_flags(uint32_t p_flags) { - flags=p_flags; + flags = p_flags; if (_is_valid()) - VS::get_singleton()->texture_set_flags(cubemap,flags|VS::TEXTURE_FLAG_CUBEMAP); + VS::get_singleton()->texture_set_flags(cubemap, flags | VS::TEXTURE_FLAG_CUBEMAP); } uint32_t CubeMap::get_flags() const { @@ -1279,27 +1172,26 @@ uint32_t CubeMap::get_flags() const { return flags; } -void CubeMap::set_side(Side p_side,const Image& p_image) { +void CubeMap::set_side(Side p_side, const Image &p_image) { ERR_FAIL_COND(p_image.empty()); - ERR_FAIL_INDEX(p_side,6); + ERR_FAIL_INDEX(p_side, 6); if (!_is_valid()) { format = p_image.get_format(); - w=p_image.get_width(); - h=p_image.get_height(); - VS::get_singleton()->texture_allocate(cubemap,w,h,p_image.get_format(),flags|VS::TEXTURE_FLAG_CUBEMAP); + w = p_image.get_width(); + h = p_image.get_height(); + VS::get_singleton()->texture_allocate(cubemap, w, h, p_image.get_format(), flags | VS::TEXTURE_FLAG_CUBEMAP); } - VS::get_singleton()->texture_set_data(cubemap,p_image,VS::CubeMapSide(p_side)); - valid[p_side]=true; + VS::get_singleton()->texture_set_data(cubemap, p_image, VS::CubeMapSide(p_side)); + valid[p_side] = true; } Image CubeMap::get_side(Side p_side) const { if (!valid[p_side]) return Image(); - return VS::get_singleton()->texture_get_data(cubemap,VS::CubeMapSide(p_side)); - + return VS::get_singleton()->texture_get_data(cubemap, VS::CubeMapSide(p_side)); } Image::Format CubeMap::get_format() const { @@ -1320,10 +1212,9 @@ RID CubeMap::get_rid() const { return cubemap; } - void CubeMap::set_storage(Storage p_storage) { - storage=p_storage; + storage = p_storage; } CubeMap::Storage CubeMap::get_storage() const { @@ -1333,7 +1224,7 @@ CubeMap::Storage CubeMap::get_storage() const { void CubeMap::set_lossy_storage_quality(float p_lossy_storage_quality) { - lossy_storage_quality=p_lossy_storage_quality; + lossy_storage_quality = p_lossy_storage_quality; } float CubeMap::get_lossy_storage_quality() const { @@ -1341,149 +1232,133 @@ float CubeMap::get_lossy_storage_quality() const { return lossy_storage_quality; } -void CubeMap::set_path(const String& p_path,bool p_take_over) { +void CubeMap::set_path(const String &p_path, bool p_take_over) { if (cubemap.is_valid()) { - VisualServer::get_singleton()->texture_set_path(cubemap,p_path); + VisualServer::get_singleton()->texture_set_path(cubemap, p_path); } - Resource::set_path(p_path,p_take_over); + Resource::set_path(p_path, p_take_over); } +bool CubeMap::_set(const StringName &p_name, const Variant &p_value) { -bool CubeMap::_set(const StringName& p_name, const Variant& p_value) { - - if (p_name=="side/left") { - set_side(SIDE_LEFT,p_value); - } else if (p_name=="side/right") { - set_side(SIDE_RIGHT,p_value); - } else if (p_name=="side/bottom") { - set_side(SIDE_BOTTOM,p_value); - } else if (p_name=="side/top") { - set_side(SIDE_TOP,p_value); - } else if (p_name=="side/front") { - set_side(SIDE_FRONT,p_value); - } else if (p_name=="side/back") { - set_side(SIDE_BACK,p_value); - } else if (p_name=="flags") { + if (p_name == "side/left") { + set_side(SIDE_LEFT, p_value); + } else if (p_name == "side/right") { + set_side(SIDE_RIGHT, p_value); + } else if (p_name == "side/bottom") { + set_side(SIDE_BOTTOM, p_value); + } else if (p_name == "side/top") { + set_side(SIDE_TOP, p_value); + } else if (p_name == "side/front") { + set_side(SIDE_FRONT, p_value); + } else if (p_name == "side/back") { + set_side(SIDE_BACK, p_value); + } else if (p_name == "flags") { set_flags(p_value); - } else if (p_name=="storage") { - storage=Storage(p_value.operator int()); - } else if (p_name=="lossy_quality") { - lossy_storage_quality=p_value; + } else if (p_name == "storage") { + storage = Storage(p_value.operator int()); + } else if (p_name == "lossy_quality") { + lossy_storage_quality = p_value; } else return false; return true; - } -bool CubeMap::_get(const StringName& p_name,Variant &r_ret) const { - - if (p_name=="side/left") { - r_ret=get_side(SIDE_LEFT); - } else if (p_name=="side/right") { - r_ret=get_side(SIDE_RIGHT); - } else if (p_name=="side/bottom") { - r_ret=get_side(SIDE_BOTTOM); - } else if (p_name=="side/top") { - r_ret=get_side(SIDE_TOP); - } else if (p_name=="side/front") { - r_ret=get_side(SIDE_FRONT); - } else if (p_name=="side/back") { - r_ret=get_side(SIDE_BACK); - } else if (p_name=="flags") { - r_ret= flags; - } else if (p_name=="storage") { - r_ret= storage; - } else if (p_name=="lossy_quality") { - r_ret= lossy_storage_quality; +bool CubeMap::_get(const StringName &p_name, Variant &r_ret) const { + + if (p_name == "side/left") { + r_ret = get_side(SIDE_LEFT); + } else if (p_name == "side/right") { + r_ret = get_side(SIDE_RIGHT); + } else if (p_name == "side/bottom") { + r_ret = get_side(SIDE_BOTTOM); + } else if (p_name == "side/top") { + r_ret = get_side(SIDE_TOP); + } else if (p_name == "side/front") { + r_ret = get_side(SIDE_FRONT); + } else if (p_name == "side/back") { + r_ret = get_side(SIDE_BACK); + } else if (p_name == "flags") { + r_ret = flags; + } else if (p_name == "storage") { + r_ret = storage; + } else if (p_name == "lossy_quality") { + r_ret = lossy_storage_quality; } else return false; return true; } +void CubeMap::_get_property_list(List<PropertyInfo> *p_list) const { - - -void CubeMap::_get_property_list( List<PropertyInfo> *p_list) const { - - - PropertyHint img_hint=PROPERTY_HINT_NONE; - if (storage==STORAGE_COMPRESS_LOSSY) { - img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSY; - } else if (storage==STORAGE_COMPRESS_LOSSLESS) { - img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS; + PropertyHint img_hint = PROPERTY_HINT_NONE; + if (storage == STORAGE_COMPRESS_LOSSY) { + img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSY; + } else if (storage == STORAGE_COMPRESS_LOSSLESS) { + img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS; } - - p_list->push_back( PropertyInfo( Variant::INT, "flags", PROPERTY_HINT_FLAGS,"Mipmaps,Repeat,Filter" ) ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "side/left", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "side/right", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "side/bottom", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "side/top", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "side/front", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::IMAGE, "side/back", img_hint,String::num(lossy_storage_quality)) ); - p_list->push_back( PropertyInfo( Variant::INT, "storage", PROPERTY_HINT_ENUM,"Uncompressed,Compress Lossy,Compress Lossless",PROPERTY_USAGE_EDITOR)); - p_list->push_back( PropertyInfo( Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE,"0.0,1.0,0.01" ) ); + p_list->push_back(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter")); + p_list->push_back(PropertyInfo(Variant::IMAGE, "side/left", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::IMAGE, "side/right", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::IMAGE, "side/bottom", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::IMAGE, "side/top", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::IMAGE, "side/front", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::IMAGE, "side/back", img_hint, String::num(lossy_storage_quality))); + p_list->push_back(PropertyInfo(Variant::INT, "storage", PROPERTY_HINT_ENUM, "Uncompressed,Compress Lossy,Compress Lossless", PROPERTY_USAGE_EDITOR)); + p_list->push_back(PropertyInfo(Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE, "0.0,1.0,0.01")); } void CubeMap::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_width"),&CubeMap::get_width); - ClassDB::bind_method(D_METHOD("get_height"),&CubeMap::get_height); + ClassDB::bind_method(D_METHOD("get_width"), &CubeMap::get_width); + ClassDB::bind_method(D_METHOD("get_height"), &CubeMap::get_height); //ClassDB::bind_method(D_METHOD("get_rid"),&CubeMap::get_rid); - ClassDB::bind_method(D_METHOD("set_flags","flags"),&CubeMap::set_flags); - ClassDB::bind_method(D_METHOD("get_flags"),&CubeMap::get_flags); - - ClassDB::bind_method(D_METHOD("set_side","side","image"),&CubeMap::set_side); - ClassDB::bind_method(D_METHOD("get_side","side"),&CubeMap::get_side); - ClassDB::bind_method(D_METHOD("set_storage","mode"),&CubeMap::set_storage); - ClassDB::bind_method(D_METHOD("get_storage"),&CubeMap::get_storage); - ClassDB::bind_method(D_METHOD("set_lossy_storage_quality","quality"),&CubeMap::set_lossy_storage_quality); - ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"),&CubeMap::get_lossy_storage_quality); - - - BIND_CONSTANT( STORAGE_RAW ); - BIND_CONSTANT( STORAGE_COMPRESS_LOSSY ); - BIND_CONSTANT( STORAGE_COMPRESS_LOSSLESS ); - BIND_CONSTANT( SIDE_LEFT ); - BIND_CONSTANT( SIDE_RIGHT ); - BIND_CONSTANT( SIDE_BOTTOM ); - BIND_CONSTANT( SIDE_TOP ); - BIND_CONSTANT( SIDE_FRONT ); - BIND_CONSTANT( SIDE_BACK ); - BIND_CONSTANT( FLAG_MIPMAPS ); - BIND_CONSTANT( FLAG_REPEAT ); - BIND_CONSTANT( FLAG_FILTER ); - BIND_CONSTANT( FLAGS_DEFAULT ); - - + ClassDB::bind_method(D_METHOD("set_flags", "flags"), &CubeMap::set_flags); + ClassDB::bind_method(D_METHOD("get_flags"), &CubeMap::get_flags); + + ClassDB::bind_method(D_METHOD("set_side", "side", "image"), &CubeMap::set_side); + ClassDB::bind_method(D_METHOD("get_side", "side"), &CubeMap::get_side); + ClassDB::bind_method(D_METHOD("set_storage", "mode"), &CubeMap::set_storage); + ClassDB::bind_method(D_METHOD("get_storage"), &CubeMap::get_storage); + ClassDB::bind_method(D_METHOD("set_lossy_storage_quality", "quality"), &CubeMap::set_lossy_storage_quality); + ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"), &CubeMap::get_lossy_storage_quality); + + BIND_CONSTANT(STORAGE_RAW); + BIND_CONSTANT(STORAGE_COMPRESS_LOSSY); + BIND_CONSTANT(STORAGE_COMPRESS_LOSSLESS); + BIND_CONSTANT(SIDE_LEFT); + BIND_CONSTANT(SIDE_RIGHT); + BIND_CONSTANT(SIDE_BOTTOM); + BIND_CONSTANT(SIDE_TOP); + BIND_CONSTANT(SIDE_FRONT); + BIND_CONSTANT(SIDE_BACK); + BIND_CONSTANT(FLAG_MIPMAPS); + BIND_CONSTANT(FLAG_REPEAT); + BIND_CONSTANT(FLAG_FILTER); + BIND_CONSTANT(FLAGS_DEFAULT); } CubeMap::CubeMap() { - w=h=0; - flags=FLAGS_DEFAULT; - for(int i=0;i<6;i++) - valid[i]=false; + w = h = 0; + flags = FLAGS_DEFAULT; + for (int i = 0; i < 6; i++) + valid[i] = false; cubemap = VisualServer::get_singleton()->texture_create(); storage = STORAGE_RAW; - lossy_storage_quality=0.7; - - + lossy_storage_quality = 0.7; } - CubeMap::~CubeMap() { - VisualServer::get_singleton()->free( cubemap ); + VisualServer::get_singleton()->free(cubemap); } - - - /* BIND_CONSTANT( FLAG_CUBEMAP ); BIND_CONSTANT( CUBEMAP_LEFT ); BIND_CONSTANT( CUBEMAP_RIGHT ); diff --git a/scene/resources/texture.h b/scene/resources/texture.h index cae77ad5cf..0092fee836 100644 --- a/scene/resources/texture.h +++ b/scene/resources/texture.h @@ -29,76 +29,73 @@ #ifndef TEXTURE_H #define TEXTURE_H -#include "resource.h" -#include "servers/visual_server.h" #include "io/resource_loader.h" #include "math_2d.h" +#include "resource.h" +#include "servers/visual_server.h" /** @author Juan Linietsky <reduzio@gmail.com> */ - - class Texture : public Resource { - GDCLASS( Texture, Resource ); - OBJ_SAVE_TYPE( Texture ); //children are all saved as Texture, so they can be exchanged + GDCLASS(Texture, Resource); + OBJ_SAVE_TYPE(Texture); //children are all saved as Texture, so they can be exchanged protected: - static void _bind_methods(); -public: +public: enum Flags { - FLAG_MIPMAPS=VisualServer::TEXTURE_FLAG_MIPMAPS, - FLAG_REPEAT=VisualServer::TEXTURE_FLAG_REPEAT, - FLAG_FILTER=VisualServer::TEXTURE_FLAG_FILTER, - FLAG_ANISOTROPIC_FILTER=VisualServer::TEXTURE_FLAG_ANISOTROPIC_FILTER, - FLAG_CONVERT_TO_LINEAR=VisualServer::TEXTURE_FLAG_CONVERT_TO_LINEAR, - FLAG_VIDEO_SURFACE=VisualServer::TEXTURE_FLAG_USED_FOR_STREAMING, - FLAGS_DEFAULT=FLAG_MIPMAPS|FLAG_REPEAT|FLAG_FILTER, - FLAG_MIRRORED_REPEAT=VisualServer::TEXTURE_FLAG_MIRRORED_REPEAT + FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS, + FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT, + FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER, + FLAG_ANISOTROPIC_FILTER = VisualServer::TEXTURE_FLAG_ANISOTROPIC_FILTER, + FLAG_CONVERT_TO_LINEAR = VisualServer::TEXTURE_FLAG_CONVERT_TO_LINEAR, + FLAG_VIDEO_SURFACE = VisualServer::TEXTURE_FLAG_USED_FOR_STREAMING, + FLAGS_DEFAULT = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER, + FLAG_MIRRORED_REPEAT = VisualServer::TEXTURE_FLAG_MIRRORED_REPEAT }; - - virtual int get_width() const=0; - virtual int get_height() const=0; + virtual int get_width() const = 0; + virtual int get_height() const = 0; virtual Size2 get_size() const; - virtual RID get_rid() const=0; + virtual RID get_rid() const = 0; - virtual bool has_alpha() const=0; + virtual bool has_alpha() const = 0; - virtual void set_flags(uint32_t p_flags)=0; - virtual uint32_t get_flags() const=0; + virtual void set_flags(uint32_t p_flags) = 0; + virtual uint32_t get_flags() const = 0; - virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual bool get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const; + virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const; virtual Image get_data() const { return Image(); } Texture(); }; -VARIANT_ENUM_CAST( Texture::Flags ); - +VARIANT_ENUM_CAST(Texture::Flags); class ImageTexture : public Texture { - GDCLASS( ImageTexture, Texture ); + GDCLASS(ImageTexture, Texture); RES_BASE_EXTENSION("tex"); + public: enum Storage { STORAGE_RAW, STORAGE_COMPRESS_LOSSY, STORAGE_COMPRESS_LOSSLESS }; + private: RID texture; Image::Format format; uint32_t flags; - int w,h; + int w, h; Storage storage; Size2 size_override; float lossy_storage_quality; @@ -106,28 +103,25 @@ private: protected: virtual void reload_from_file(); - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; - void _reload_hook(const RID& p_hook); + void _reload_hook(const RID &p_hook); virtual void _resource_path_changed(); static void _bind_methods(); void _set_data(Dictionary p_data); public: - - - void create(int p_width, int p_height,Image::Format p_format,uint32_t p_flags=FLAGS_DEFAULT); - void create_from_image(const Image& p_image, uint32_t p_flags=FLAGS_DEFAULT); - + void create(int p_width, int p_height, Image::Format p_format, uint32_t p_flags = FLAGS_DEFAULT); + void create_from_image(const Image &p_image, uint32_t p_flags = FLAGS_DEFAULT); void set_flags(uint32_t p_flags); uint32_t get_flags() const; Image::Format get_format() const; - void load(const String& p_path); - void set_data(const Image& p_image); + void load(const String &p_path); + void set_data(const Image &p_image); Image get_data() const; int get_width() const; @@ -136,9 +130,9 @@ public: virtual RID get_rid() const; bool has_alpha() const; - virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; + virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; void set_storage(Storage p_storage); Storage get_storage() const; @@ -150,21 +144,18 @@ public: void normal_to_xy(); void shrink_x2_and_keep_size(); + void set_size_override(const Size2 &p_size); - void set_size_override(const Size2& p_size); - - virtual void set_path(const String& p_path,bool p_take_over=false); + virtual void set_path(const String &p_path, bool p_take_over = false); ImageTexture(); ~ImageTexture(); - }; - - class StreamTexture : public Texture { - GDCLASS( StreamTexture, Texture ); + GDCLASS(StreamTexture, Texture); + public: enum DataFormat { DATA_FORMAT_IMAGE, @@ -173,53 +164,49 @@ public: }; enum FormatBits { - FORMAT_MASK_IMAGE_FORMAT=(1<<20)-1, - FORMAT_BIT_LOSSLESS=1<<20, - FORMAT_BIT_LOSSY=1<<21, - FORMAT_BIT_STREAM=1<<22, - FORMAT_BIT_HAS_MIPMAPS=1<<23, - FORMAT_BIT_DETECT_3D=1<<24, - FORMAT_BIT_DETECT_SRGB=1<<25, + FORMAT_MASK_IMAGE_FORMAT = (1 << 20) - 1, + FORMAT_BIT_LOSSLESS = 1 << 20, + FORMAT_BIT_LOSSY = 1 << 21, + FORMAT_BIT_STREAM = 1 << 22, + FORMAT_BIT_HAS_MIPMAPS = 1 << 23, + FORMAT_BIT_DETECT_3D = 1 << 24, + FORMAT_BIT_DETECT_SRGB = 1 << 25, }; private: - - Error _load_data(const String &p_path, int &tw, int &th, int& flags, Image& image, int p_size_limit=0); + Error _load_data(const String &p_path, int &tw, int &th, int &flags, Image &image, int p_size_limit = 0); String path_to_file; RID texture; Image::Format format; uint32_t flags; - int w,h; + int w, h; virtual void reload_from_file(); - static void _requested_3d(void* p_ud); - static void _requested_srgb(void* p_ud); + static void _requested_3d(void *p_ud); + static void _requested_srgb(void *p_ud); protected: - static void _bind_methods(); public: - - - typedef void (*TextureFormatRequestCallback)(const Ref<StreamTexture>&); + typedef void (*TextureFormatRequestCallback)(const Ref<StreamTexture> &); static TextureFormatRequestCallback request_3d_callback; static TextureFormatRequestCallback request_srgb_callback; uint32_t get_flags() const; Image::Format get_format() const; - Error load(const String& p_path); + Error load(const String &p_path); String get_load_path() const; int get_width() const; int get_height() const; virtual RID get_rid() const; - virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; + virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; virtual bool has_alpha() const; virtual void set_flags(uint32_t p_flags); @@ -228,37 +215,31 @@ public: StreamTexture(); ~StreamTexture(); - }; - class ResourceFormatLoaderStreamTexture : public ResourceFormatLoader { public: - virtual RES load(const String &p_path,const String& p_original_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; - 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; - }; - - -VARIANT_ENUM_CAST( ImageTexture::Storage ); +VARIANT_ENUM_CAST(ImageTexture::Storage); class AtlasTexture : public Texture { - GDCLASS( AtlasTexture, Texture ); + GDCLASS(AtlasTexture, Texture); RES_BASE_EXTENSION("atex"); -protected: - +protected: Ref<Texture> atlas; Rect2 region; Rect2 margin; static void _bind_methods(); -public: +public: virtual int get_width() const; virtual int get_height() const; virtual RID get_rid() const; @@ -268,30 +249,29 @@ public: virtual void set_flags(uint32_t p_flags); virtual uint32_t get_flags() const; - void set_atlas(const Ref<Texture>& p_atlas); + void set_atlas(const Ref<Texture> &p_atlas); Ref<Texture> get_atlas() const; - void set_region(const Rect2& p_region); - Rect2 get_region() const ; - - void set_margin(const Rect2& p_margin); - Rect2 get_margin() const ; + void set_region(const Rect2 &p_region); + Rect2 get_region() const; - virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual bool get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const; + void set_margin(const Rect2 &p_margin); + Rect2 get_margin() const; + virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const; AtlasTexture(); }; class LargeTexture : public Texture { - GDCLASS( LargeTexture, Texture ); + GDCLASS(LargeTexture, Texture); RES_BASE_EXTENSION("ltex"); -protected: +protected: struct Piece { Point2 offset; @@ -301,12 +281,11 @@ protected: Vector<Piece> pieces; Size2i size; - Array _get_data() const; - void _set_data(const Array& p_array); + void _set_data(const Array &p_array); static void _bind_methods(); -public: +public: virtual int get_width() const; virtual int get_height() const; virtual RID get_rid() const; @@ -316,31 +295,29 @@ public: virtual void set_flags(uint32_t p_flags); virtual uint32_t get_flags() const; - int add_piece(const Point2& p_offset,const Ref<Texture>& p_texture); - void set_piece_offset(int p_idx, const Point2& p_offset); - void set_piece_texture(int p_idx, const Ref<Texture>& p_texture); + int add_piece(const Point2 &p_offset, const Ref<Texture> &p_texture); + void set_piece_offset(int p_idx, const Point2 &p_offset); + void set_piece_texture(int p_idx, const Ref<Texture> &p_texture); - void set_size(const Size2& p_size); + void set_size(const Size2 &p_size); void clear(); int get_piece_count() const; Vector2 get_piece_offset(int p_idx) const; Ref<Texture> get_piece_texture(int p_idx) const; - virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const; - + virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; + virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const; LargeTexture(); }; - - class CubeMap : public Resource { - GDCLASS( CubeMap, Resource ); + GDCLASS(CubeMap, Resource); RES_BASE_EXTENSION("cbm"); + public: enum Storage { STORAGE_RAW, @@ -359,37 +336,40 @@ public: }; enum Flags { - FLAG_MIPMAPS=VisualServer::TEXTURE_FLAG_MIPMAPS, - FLAG_REPEAT=VisualServer::TEXTURE_FLAG_REPEAT, - FLAG_FILTER=VisualServer::TEXTURE_FLAG_FILTER, - FLAGS_DEFAULT=FLAG_MIPMAPS|FLAG_REPEAT|FLAG_FILTER, + FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS, + FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT, + FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER, + FLAGS_DEFAULT = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER, }; private: - bool valid[6]; RID cubemap; Image::Format format; uint32_t flags; - int w,h; + int w, h; Storage storage; Size2 size_override; float lossy_storage_quality; - _FORCE_INLINE_ bool _is_valid() const { for(int i=0;i<6;i++) { if (valid[i]) return true; } return false; } + _FORCE_INLINE_ bool _is_valid() const { + for (int i = 0; i < 6; i++) { + if (valid[i]) return true; + } + return false; + } protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); -public: +public: void set_flags(uint32_t p_flags); uint32_t get_flags() const; - void set_side(Side p_side,const Image& p_image); + void set_side(Side p_side, const Image &p_image); Image get_side(Side p_side) const; Image::Format get_format() const; @@ -404,17 +384,15 @@ public: void set_lossy_storage_quality(float p_lossy_storage_quality); float get_lossy_storage_quality() const; - virtual void set_path(const String& p_path,bool p_take_over=false); + virtual void set_path(const String &p_path, bool p_take_over = false); CubeMap(); ~CubeMap(); - }; -VARIANT_ENUM_CAST( CubeMap::Flags ); -VARIANT_ENUM_CAST( CubeMap::Side ); -VARIANT_ENUM_CAST( CubeMap::Storage ); - +VARIANT_ENUM_CAST(CubeMap::Flags); +VARIANT_ENUM_CAST(CubeMap::Side); +VARIANT_ENUM_CAST(CubeMap::Storage); /* enum CubeMapSide { @@ -430,5 +408,4 @@ VARIANT_ENUM_CAST( CubeMap::Storage ); */ //VARIANT_ENUM_CAST( Texture::CubeMapSide ); - #endif diff --git a/scene/resources/theme.cpp b/scene/resources/theme.cpp index 10ad38d498..c1ef3e8c1f 100644 --- a/scene/resources/theme.cpp +++ b/scene/resources/theme.cpp @@ -27,64 +27,61 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "theme.h" -#include "print_string.h" #include "os/file_access.h" - +#include "print_string.h" Ref<Theme> Theme::default_theme; - void Theme::_emit_theme_changed() { emit_changed(); } -void Theme::_ref_font( Ref<Font> p_sc) { +void Theme::_ref_font(Ref<Font> p_sc) { if (!font_refcount.has(p_sc)) { - font_refcount[p_sc]=1; - p_sc->connect("changed",this,"_emit_theme_changed"); + font_refcount[p_sc] = 1; + p_sc->connect("changed", this, "_emit_theme_changed"); } else { - font_refcount[p_sc]+=1; + font_refcount[p_sc] += 1; } } -void Theme::_unref_font(Ref<Font> p_sc) { +void Theme::_unref_font(Ref<Font> p_sc) { ERR_FAIL_COND(!font_refcount.has(p_sc)); font_refcount[p_sc]--; - if (font_refcount[p_sc]==0) { - p_sc->disconnect("changed",this,"_emit_theme_changed"); + if (font_refcount[p_sc] == 0) { + p_sc->disconnect("changed", this, "_emit_theme_changed"); font_refcount.erase(p_sc); } } +bool Theme::_set(const StringName &p_name, const Variant &p_value) { -bool Theme::_set(const StringName& p_name, const Variant& p_value) { - - String sname=p_name; + String sname = p_name; - if (sname.find("/")!=-1) { + if (sname.find("/") != -1) { - String type=sname.get_slicec('/',1); - String node_type=sname.get_slicec('/',0); - String name=sname.get_slicec('/',2); + String type = sname.get_slicec('/', 1); + String node_type = sname.get_slicec('/', 0); + String name = sname.get_slicec('/', 2); - if (type=="icons") { + if (type == "icons") { - set_icon(name,node_type,p_value); - } else if (type=="styles") { + set_icon(name, node_type, p_value); + } else if (type == "styles") { - set_stylebox(name,node_type,p_value); - } else if (type=="fonts") { + set_stylebox(name, node_type, p_value); + } else if (type == "fonts") { - set_font(name,node_type,p_value); - } else if (type=="colors") { + set_font(name, node_type, p_value); + } else if (type == "colors") { - set_color(name,node_type,p_value); - } else if (type=="constants") { + set_color(name, node_type, p_value); + } else if (type == "constants") { - set_constant(name,node_type,p_value); + set_constant(name, node_type, p_value); } else return false; @@ -92,43 +89,42 @@ bool Theme::_set(const StringName& p_name, const Variant& p_value) { } return false; - } -bool Theme::_get(const StringName& p_name,Variant &r_ret) const { +bool Theme::_get(const StringName &p_name, Variant &r_ret) const { - String sname=p_name; + String sname = p_name; - if (sname.find("/")!=-1) { + if (sname.find("/") != -1) { - String type=sname.get_slicec('/',1); - String node_type=sname.get_slicec('/',0); - String name=sname.get_slicec('/',2); + String type = sname.get_slicec('/', 1); + String node_type = sname.get_slicec('/', 0); + String name = sname.get_slicec('/', 2); - if (type=="icons") { + if (type == "icons") { - if (!has_icon(name,node_type)) - r_ret=Ref<Texture>(); + if (!has_icon(name, node_type)) + r_ret = Ref<Texture>(); else - r_ret= get_icon(name,node_type); - } else if (type=="styles") { + r_ret = get_icon(name, node_type); + } else if (type == "styles") { - if (!has_stylebox(name,node_type)) - r_ret=Ref<StyleBox>(); + if (!has_stylebox(name, node_type)) + r_ret = Ref<StyleBox>(); else - r_ret= get_stylebox(name,node_type); - } else if (type=="fonts") { + r_ret = get_stylebox(name, node_type); + } else if (type == "fonts") { - if (!has_font(name,node_type)) - r_ret=Ref<Font>(); + if (!has_font(name, node_type)) + r_ret = Ref<Font>(); else - r_ret= get_font(name,node_type); - } else if (type=="colors") { + r_ret = get_font(name, node_type); + } else if (type == "colors") { - r_ret= get_color(name,node_type); - } else if (type=="constants") { + r_ret = get_color(name, node_type); + } else if (type == "constants") { - r_ret= get_constant(name,node_type); + r_ret = get_constant(name, node_type); } else return false; @@ -138,77 +134,74 @@ bool Theme::_get(const StringName& p_name,Variant &r_ret) const { return false; } -void Theme::_get_property_list( List<PropertyInfo> *p_list) const { - +void Theme::_get_property_list(List<PropertyInfo> *p_list) const { List<PropertyInfo> list; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=icon_map.next(key))) { + while ((key = icon_map.next(key))) { - const StringName *key2=NULL; + const StringName *key2 = NULL; - while((key2=icon_map[*key].next(key2))) { + while ((key2 = icon_map[*key].next(key2))) { - list.push_back( PropertyInfo( Variant::OBJECT, String()+*key+"/icons/"+*key2, PROPERTY_HINT_RESOURCE_TYPE, "Texture",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NULL ) ); + list.push_back(PropertyInfo(Variant::OBJECT, String() + *key + "/icons/" + *key2, PROPERTY_HINT_RESOURCE_TYPE, "Texture", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NULL)); } } - key=NULL; + key = NULL; - while((key=style_map.next(key))) { + while ((key = style_map.next(key))) { - const StringName *key2=NULL; + const StringName *key2 = NULL; - while((key2=style_map[*key].next(key2))) { + while ((key2 = style_map[*key].next(key2))) { - list.push_back( PropertyInfo( Variant::OBJECT, String()+*key+"/styles/"+*key2, PROPERTY_HINT_RESOURCE_TYPE, "StyleBox", PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NULL ) ); + list.push_back(PropertyInfo(Variant::OBJECT, String() + *key + "/styles/" + *key2, PROPERTY_HINT_RESOURCE_TYPE, "StyleBox", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NULL)); } } - key=NULL; + key = NULL; + while ((key = font_map.next(key))) { - while((key=font_map.next(key))) { + const StringName *key2 = NULL; - const StringName *key2=NULL; + while ((key2 = font_map[*key].next(key2))) { - while((key2=font_map[*key].next(key2))) { - - list.push_back( PropertyInfo( Variant::OBJECT, String()+*key+"/fonts/"+*key2, PROPERTY_HINT_RESOURCE_TYPE, "Font",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NULL ) ); + list.push_back(PropertyInfo(Variant::OBJECT, String() + *key + "/fonts/" + *key2, PROPERTY_HINT_RESOURCE_TYPE, "Font", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NULL)); } } - key=NULL; + key = NULL; - while((key=color_map.next(key))) { + while ((key = color_map.next(key))) { - const StringName *key2=NULL; + const StringName *key2 = NULL; - while((key2=color_map[*key].next(key2))) { + while ((key2 = color_map[*key].next(key2))) { - list.push_back( PropertyInfo( Variant::COLOR, String()+*key+"/colors/"+*key2 ) ); + list.push_back(PropertyInfo(Variant::COLOR, String() + *key + "/colors/" + *key2)); } } - key=NULL; + key = NULL; - while((key=constant_map.next(key))) { + while ((key = constant_map.next(key))) { - const StringName *key2=NULL; + const StringName *key2 = NULL; - while((key2=constant_map[*key].next(key2))) { + while ((key2 = constant_map[*key].next(key2))) { - list.push_back( PropertyInfo( Variant::INT, String()+*key+"/constants/"+*key2 ) ); + list.push_back(PropertyInfo(Variant::INT, String() + *key + "/constants/" + *key2)); } } list.sort(); - for(List<PropertyInfo>::Element *E=list.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = list.front(); E; E = E->next()) { p_list->push_back(E->get()); } - } Ref<Theme> Theme::get_default() { @@ -216,17 +209,16 @@ Ref<Theme> Theme::get_default() { return default_theme; } +void Theme::set_default_theme_font(const Ref<Font> &p_default_font) { -void Theme::set_default_theme_font( const Ref<Font>& p_default_font ) { - - if (default_theme_font==p_default_font) + if (default_theme_font == p_default_font) return; if (default_theme_font.is_valid()) { _unref_font(default_theme_font); } - default_theme_font=p_default_font; + default_theme_font = p_default_font; if (default_theme_font.is_valid()) { _ref_font(default_theme_font); @@ -234,7 +226,6 @@ void Theme::set_default_theme_font( const Ref<Font>& p_default_font ) { _change_notify(); emit_changed(); - } Ref<Font> Theme::get_default_theme_font() const { @@ -242,43 +233,42 @@ Ref<Font> Theme::get_default_theme_font() const { return default_theme_font; } -void Theme::set_default(const Ref<Theme>& p_default) { +void Theme::set_default(const Ref<Theme> &p_default) { - default_theme=p_default; + default_theme = p_default; } Ref<Texture> Theme::default_icon; Ref<StyleBox> Theme::default_style; Ref<Font> Theme::default_font; +void Theme::set_default_icon(const Ref<Texture> &p_icon) { -void Theme::set_default_icon( const Ref<Texture>& p_icon ) { - - default_icon=p_icon; + default_icon = p_icon; } -void Theme::set_default_style( const Ref<StyleBox>& p_style) { +void Theme::set_default_style(const Ref<StyleBox> &p_style) { - default_style=p_style; + default_style = p_style; } -void Theme::set_default_font( const Ref<Font>& p_font ) { +void Theme::set_default_font(const Ref<Font> &p_font) { - default_font=p_font; + default_font = p_font; } -void Theme::set_icon(const StringName& p_name,const StringName& p_type,const Ref<Texture>& p_icon) { +void Theme::set_icon(const StringName &p_name, const StringName &p_type, const Ref<Texture> &p_icon) { //ERR_FAIL_COND(p_icon.is_null()); - bool new_value=!icon_map.has(p_type) || !icon_map[p_type].has(p_name); + bool new_value = !icon_map.has(p_type) || !icon_map[p_type].has(p_name); - icon_map[p_type][p_name]=p_icon; + icon_map[p_type][p_name] = p_icon; if (new_value) { _change_notify(); emit_changed(); } } -Ref<Texture> Theme::get_icon(const StringName& p_name,const StringName& p_type) const { +Ref<Texture> Theme::get_icon(const StringName &p_name, const StringName &p_type) const { if (icon_map.has(p_type) && icon_map[p_type].has(p_name) && icon_map[p_type][p_name].is_valid()) { @@ -288,13 +278,12 @@ Ref<Texture> Theme::get_icon(const StringName& p_name,const StringName& p_type) } } -bool Theme::has_icon(const StringName& p_name,const StringName& p_type) const { +bool Theme::has_icon(const StringName &p_name, const StringName &p_type) const { return (icon_map.has(p_type) && icon_map[p_type].has(p_name) && icon_map[p_type][p_name].is_valid()); } - -void Theme::clear_icon(const StringName& p_name,const StringName& p_type) { +void Theme::clear_icon(const StringName &p_name, const StringName &p_type) { ERR_FAIL_COND(!icon_map.has(p_type)); ERR_FAIL_COND(!icon_map[p_type].has(p_name)); @@ -302,7 +291,6 @@ void Theme::clear_icon(const StringName& p_name,const StringName& p_type) { icon_map[p_type].erase(p_name); _change_notify(); emit_changed(); - } void Theme::get_icon_list(StringName p_type, List<StringName> *p_list) const { @@ -310,19 +298,18 @@ void Theme::get_icon_list(StringName p_type, List<StringName> *p_list) const { if (!icon_map.has(p_type)) return; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=icon_map[p_type].next(key))) { + while ((key = icon_map[p_type].next(key))) { p_list->push_back(*key); } - } -void Theme::set_shader(const StringName &p_name,const StringName &p_type,const Ref<Shader>& p_shader) { - bool new_value=!shader_map.has(p_type) || !shader_map[p_type].has(p_name); +void Theme::set_shader(const StringName &p_name, const StringName &p_type, const Ref<Shader> &p_shader) { + bool new_value = !shader_map.has(p_type) || !shader_map[p_type].has(p_name); - shader_map[p_type][p_name]=p_shader; + shader_map[p_type][p_name] = p_shader; if (new_value) { _change_notify(); @@ -355,48 +342,43 @@ void Theme::get_shader_list(const StringName &p_type, List<StringName> *p_list) if (!shader_map.has(p_type)) return; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=shader_map[p_type].next(key))) { + while ((key = shader_map[p_type].next(key))) { p_list->push_back(*key); } - } - -void Theme::set_stylebox(const StringName& p_name,const StringName& p_type,const Ref<StyleBox>& p_style) { +void Theme::set_stylebox(const StringName &p_name, const StringName &p_type, const Ref<StyleBox> &p_style) { //ERR_FAIL_COND(p_style.is_null()); - bool new_value=!style_map.has(p_type) || !style_map[p_type].has(p_name); + bool new_value = !style_map.has(p_type) || !style_map[p_type].has(p_name); - style_map[p_type][p_name]=p_style; + style_map[p_type][p_name] = p_style; if (new_value) _change_notify(); emit_changed(); - } - -Ref<StyleBox> Theme::get_stylebox(const StringName& p_name,const StringName& p_type) const { +Ref<StyleBox> Theme::get_stylebox(const StringName &p_name, const StringName &p_type) const { if (style_map.has(p_type) && style_map[p_type].has(p_name) && style_map[p_type][p_name].is_valid()) { return style_map[p_type][p_name]; } else { return default_style; - } } -bool Theme::has_stylebox(const StringName& p_name,const StringName& p_type) const { +bool Theme::has_stylebox(const StringName &p_name, const StringName &p_type) const { return (style_map.has(p_type) && style_map[p_type].has(p_name) && style_map[p_type][p_name].is_valid()); } -void Theme::clear_stylebox(const StringName& p_name,const StringName& p_type) { +void Theme::clear_stylebox(const StringName &p_name, const StringName &p_type) { ERR_FAIL_COND(!style_map.has(p_type)); ERR_FAIL_COND(!style_map[p_type].has(p_name)); @@ -404,7 +386,6 @@ void Theme::clear_stylebox(const StringName& p_name,const StringName& p_type) { style_map[p_type].erase(p_name); _change_notify(); emit_changed(); - } void Theme::get_stylebox_list(StringName p_type, List<StringName> *p_list) const { @@ -412,34 +393,33 @@ void Theme::get_stylebox_list(StringName p_type, List<StringName> *p_list) const if (!style_map.has(p_type)) return; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=style_map[p_type].next(key))) { + while ((key = style_map[p_type].next(key))) { p_list->push_back(*key); } - } void Theme::get_stylebox_types(List<StringName> *p_list) const { - const StringName *key=NULL; - while((key=style_map.next(key))) { + const StringName *key = NULL; + while ((key = style_map.next(key))) { p_list->push_back(*key); } } -void Theme::set_font(const StringName& p_name,const StringName& p_type,const Ref<Font>& p_font) { +void Theme::set_font(const StringName &p_name, const StringName &p_type, const Ref<Font> &p_font) { //ERR_FAIL_COND(p_font.is_null()); - bool new_value=!font_map.has(p_type) || !font_map[p_type].has(p_name); + bool new_value = !font_map.has(p_type) || !font_map[p_type].has(p_name); if (!new_value) { if (font_map[p_type][p_name].is_valid()) { _unref_font(font_map[p_type][p_name]); } } - font_map[p_type][p_name]=p_font; + font_map[p_type][p_name] = p_font; if (p_font.is_valid()) { _ref_font(p_font); @@ -450,7 +430,7 @@ void Theme::set_font(const StringName& p_name,const StringName& p_type,const Ref emit_changed(); } } -Ref<Font> Theme::get_font(const StringName& p_name,const StringName& p_type) const { +Ref<Font> Theme::get_font(const StringName &p_name, const StringName &p_type) const { if (font_map.has(p_type) && font_map[p_type].has(p_name) && font_map[p_type][p_name].is_valid()) return font_map[p_type][p_name]; @@ -458,15 +438,14 @@ Ref<Font> Theme::get_font(const StringName& p_name,const StringName& p_type) con return default_theme_font; else return default_font; - } -bool Theme::has_font(const StringName& p_name,const StringName& p_type) const { +bool Theme::has_font(const StringName &p_name, const StringName &p_type) const { return (font_map.has(p_type) && font_map[p_type].has(p_name) && font_map[p_type][p_name].is_valid()); } -void Theme::clear_font(const StringName& p_name,const StringName& p_type) { +void Theme::clear_font(const StringName &p_name, const StringName &p_type) { ERR_FAIL_COND(!font_map.has(p_type)); ERR_FAIL_COND(!font_map[p_type].has(p_name)); @@ -478,7 +457,6 @@ void Theme::clear_font(const StringName& p_name,const StringName& p_type) { font_map[p_type].erase(p_name); _change_notify(); emit_changed(); - } void Theme::get_font_list(StringName p_type, List<StringName> *p_list) const { @@ -486,45 +464,40 @@ void Theme::get_font_list(StringName p_type, List<StringName> *p_list) const { if (!font_map.has(p_type)) return; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=font_map[p_type].next(key))) { + while ((key = font_map[p_type].next(key))) { p_list->push_back(*key); } - } -void Theme::set_color(const StringName& p_name,const StringName& p_type,const Color& p_color) { +void Theme::set_color(const StringName &p_name, const StringName &p_type, const Color &p_color) { - bool new_value=!color_map.has(p_type) || !color_map[p_type].has(p_name); + bool new_value = !color_map.has(p_type) || !color_map[p_type].has(p_name); - color_map[p_type][p_name]=p_color; + color_map[p_type][p_name] = p_color; if (new_value) { _change_notify(); emit_changed(); - } } - - -Color Theme::get_color(const StringName& p_name,const StringName& p_type) const { +Color Theme::get_color(const StringName &p_name, const StringName &p_type) const { if (color_map.has(p_type) && color_map[p_type].has(p_name)) return color_map[p_type][p_name]; else return Color(); - } -bool Theme::has_color(const StringName& p_name,const StringName& p_type) const { +bool Theme::has_color(const StringName &p_name, const StringName &p_type) const { return (color_map.has(p_type) && color_map[p_type].has(p_name)); } -void Theme::clear_color(const StringName& p_name,const StringName& p_type) { +void Theme::clear_color(const StringName &p_name, const StringName &p_type) { ERR_FAIL_COND(!color_map.has(p_type)); ERR_FAIL_COND(!color_map[p_type].has(p_name)); @@ -532,7 +505,6 @@ void Theme::clear_color(const StringName& p_name,const StringName& p_type) { color_map[p_type].erase(p_name); _change_notify(); emit_changed(); - } void Theme::get_color_list(StringName p_type, List<StringName> *p_list) const { @@ -540,19 +512,18 @@ void Theme::get_color_list(StringName p_type, List<StringName> *p_list) const { if (!color_map.has(p_type)) return; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=color_map[p_type].next(key))) { + while ((key = color_map[p_type].next(key))) { p_list->push_back(*key); } - } -void Theme::set_constant(const StringName& p_name,const StringName& p_type,int p_constant) { +void Theme::set_constant(const StringName &p_name, const StringName &p_type, int p_constant) { - bool new_value=!constant_map.has(p_type) || !constant_map[p_type].has(p_name); - constant_map[p_type][p_name]=p_constant; + bool new_value = !constant_map.has(p_type) || !constant_map[p_type].has(p_name); + constant_map[p_type][p_name] = p_constant; if (new_value) { _change_notify(); @@ -560,22 +531,21 @@ void Theme::set_constant(const StringName& p_name,const StringName& p_type,int p } } -int Theme::get_constant(const StringName& p_name,const StringName& p_type) const { +int Theme::get_constant(const StringName &p_name, const StringName &p_type) const { if (constant_map.has(p_type) && constant_map[p_type].has(p_name)) return constant_map[p_type][p_name]; else { return 0; } - } -bool Theme::has_constant(const StringName& p_name,const StringName& p_type) const { +bool Theme::has_constant(const StringName &p_name, const StringName &p_type) const { return (constant_map.has(p_type) && constant_map[p_type].has(p_name)); } -void Theme::clear_constant(const StringName& p_name,const StringName& p_type) { +void Theme::clear_constant(const StringName &p_name, const StringName &p_type) { ERR_FAIL_COND(!constant_map.has(p_type)); ERR_FAIL_COND(!constant_map[p_type].has(p_name)); @@ -583,7 +553,6 @@ void Theme::clear_constant(const StringName& p_name,const StringName& p_type) { constant_map[p_type].erase(p_name); _change_notify(); emit_changed(); - } void Theme::get_constant_list(StringName p_type, List<StringName> *p_list) const { @@ -591,192 +560,176 @@ void Theme::get_constant_list(StringName p_type, List<StringName> *p_list) const if (!constant_map.has(p_type)) return; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=constant_map[p_type].next(key))) { + while ((key = constant_map[p_type].next(key))) { p_list->push_back(*key); } - } - void Theme::copy_default_theme() { - Ref<Theme> default_theme=get_default(); + Ref<Theme> default_theme = get_default(); - icon_map=default_theme->icon_map; - style_map=default_theme->style_map; - font_map=default_theme->font_map; - color_map=default_theme->color_map; - constant_map=default_theme->constant_map; + icon_map = default_theme->icon_map; + style_map = default_theme->style_map; + font_map = default_theme->font_map; + color_map = default_theme->color_map; + constant_map = default_theme->constant_map; _change_notify(); emit_changed(); - } void Theme::get_type_list(List<StringName> *p_list) const { Set<StringName> types; - const StringName *key=NULL; + const StringName *key = NULL; - while((key=icon_map.next(key))) { + while ((key = icon_map.next(key))) { types.insert(*key); } - key=NULL; + key = NULL; - while((key=style_map.next(key))) { + while ((key = style_map.next(key))) { types.insert(*key); } - key=NULL; + key = NULL; - while((key=font_map.next(key))) { + while ((key = font_map.next(key))) { types.insert(*key); } - key=NULL; + key = NULL; - while((key=color_map.next(key))) { + while ((key = color_map.next(key))) { types.insert(*key); } - key=NULL; + key = NULL; - while((key=constant_map.next(key))) { + while ((key = constant_map.next(key))) { types.insert(*key); } - - for(Set<StringName>::Element *E=types.front();E;E=E->next()) { + for (Set<StringName>::Element *E = types.front(); E; E = E->next()) { p_list->push_back(E->get()); } } - void Theme::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_icon","name","type","texture:Texture"),&Theme::set_icon); - ClassDB::bind_method(D_METHOD("get_icon:Texture","name","type"),&Theme::get_icon); - ClassDB::bind_method(D_METHOD("has_icon","name","type"),&Theme::has_icon); - ClassDB::bind_method(D_METHOD("clear_icon","name","type"),&Theme::clear_icon); - ClassDB::bind_method(D_METHOD("get_icon_list","type"),&Theme::_get_icon_list); - - ClassDB::bind_method(D_METHOD("set_stylebox","name","type","texture:StyleBox"),&Theme::set_stylebox); - ClassDB::bind_method(D_METHOD("get_stylebox:StyleBox","name","type"),&Theme::get_stylebox); - ClassDB::bind_method(D_METHOD("has_stylebox","name","type"),&Theme::has_stylebox); - ClassDB::bind_method(D_METHOD("clear_stylebox","name","type"),&Theme::clear_stylebox); - ClassDB::bind_method(D_METHOD("get_stylebox_list","type"),&Theme::_get_stylebox_list); - ClassDB::bind_method(D_METHOD("get_stylebox_types"),&Theme::_get_stylebox_types); + ClassDB::bind_method(D_METHOD("set_icon", "name", "type", "texture:Texture"), &Theme::set_icon); + ClassDB::bind_method(D_METHOD("get_icon:Texture", "name", "type"), &Theme::get_icon); + ClassDB::bind_method(D_METHOD("has_icon", "name", "type"), &Theme::has_icon); + ClassDB::bind_method(D_METHOD("clear_icon", "name", "type"), &Theme::clear_icon); + ClassDB::bind_method(D_METHOD("get_icon_list", "type"), &Theme::_get_icon_list); - ClassDB::bind_method(D_METHOD("set_font","name","type","font:Font"),&Theme::set_font); - ClassDB::bind_method(D_METHOD("get_font:Font","name","type"),&Theme::get_font); - ClassDB::bind_method(D_METHOD("has_font","name","type"),&Theme::has_font); - ClassDB::bind_method(D_METHOD("clear_font","name","type"),&Theme::clear_font); - ClassDB::bind_method(D_METHOD("get_font_list","type"),&Theme::_get_font_list); + ClassDB::bind_method(D_METHOD("set_stylebox", "name", "type", "texture:StyleBox"), &Theme::set_stylebox); + ClassDB::bind_method(D_METHOD("get_stylebox:StyleBox", "name", "type"), &Theme::get_stylebox); + ClassDB::bind_method(D_METHOD("has_stylebox", "name", "type"), &Theme::has_stylebox); + ClassDB::bind_method(D_METHOD("clear_stylebox", "name", "type"), &Theme::clear_stylebox); + ClassDB::bind_method(D_METHOD("get_stylebox_list", "type"), &Theme::_get_stylebox_list); + ClassDB::bind_method(D_METHOD("get_stylebox_types"), &Theme::_get_stylebox_types); - ClassDB::bind_method(D_METHOD("set_color","name","type","color"),&Theme::set_color); - ClassDB::bind_method(D_METHOD("get_color","name","type"),&Theme::get_color); - ClassDB::bind_method(D_METHOD("has_color","name","type"),&Theme::has_color); - ClassDB::bind_method(D_METHOD("clear_color","name","type"),&Theme::clear_color); - ClassDB::bind_method(D_METHOD("get_color_list","type"),&Theme::_get_color_list); + ClassDB::bind_method(D_METHOD("set_font", "name", "type", "font:Font"), &Theme::set_font); + ClassDB::bind_method(D_METHOD("get_font:Font", "name", "type"), &Theme::get_font); + ClassDB::bind_method(D_METHOD("has_font", "name", "type"), &Theme::has_font); + ClassDB::bind_method(D_METHOD("clear_font", "name", "type"), &Theme::clear_font); + ClassDB::bind_method(D_METHOD("get_font_list", "type"), &Theme::_get_font_list); - ClassDB::bind_method(D_METHOD("set_constant","name","type","constant"),&Theme::set_constant); - ClassDB::bind_method(D_METHOD("get_constant","name","type"),&Theme::get_constant); - ClassDB::bind_method(D_METHOD("has_constant","name","type"),&Theme::has_constant); - ClassDB::bind_method(D_METHOD("clear_constant","name","type"),&Theme::clear_constant); - ClassDB::bind_method(D_METHOD("get_constant_list","type"),&Theme::_get_constant_list); + ClassDB::bind_method(D_METHOD("set_color", "name", "type", "color"), &Theme::set_color); + ClassDB::bind_method(D_METHOD("get_color", "name", "type"), &Theme::get_color); + ClassDB::bind_method(D_METHOD("has_color", "name", "type"), &Theme::has_color); + ClassDB::bind_method(D_METHOD("clear_color", "name", "type"), &Theme::clear_color); + ClassDB::bind_method(D_METHOD("get_color_list", "type"), &Theme::_get_color_list); - ClassDB::bind_method(D_METHOD("set_default_font","font"),&Theme::set_default_theme_font); - ClassDB::bind_method(D_METHOD("get_default_font"),&Theme::get_default_theme_font); + ClassDB::bind_method(D_METHOD("set_constant", "name", "type", "constant"), &Theme::set_constant); + ClassDB::bind_method(D_METHOD("get_constant", "name", "type"), &Theme::get_constant); + ClassDB::bind_method(D_METHOD("has_constant", "name", "type"), &Theme::has_constant); + ClassDB::bind_method(D_METHOD("clear_constant", "name", "type"), &Theme::clear_constant); + ClassDB::bind_method(D_METHOD("get_constant_list", "type"), &Theme::_get_constant_list); - ClassDB::bind_method(D_METHOD("get_type_list","type"),&Theme::_get_type_list); + ClassDB::bind_method(D_METHOD("set_default_font", "font"), &Theme::set_default_theme_font); + ClassDB::bind_method(D_METHOD("get_default_font"), &Theme::get_default_theme_font); - ClassDB::bind_method(D_METHOD("_emit_theme_changed"),&Theme::_emit_theme_changed); + ClassDB::bind_method(D_METHOD("get_type_list", "type"), &Theme::_get_type_list); + ClassDB::bind_method(D_METHOD("_emit_theme_changed"), &Theme::_emit_theme_changed); + ClassDB::bind_method("copy_default_theme", &Theme::copy_default_theme); - - ClassDB::bind_method("copy_default_theme",&Theme::copy_default_theme); - - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"default_font",PROPERTY_HINT_RESOURCE_TYPE,"Font"),"set_default_font","get_default_font"); - + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "default_font", PROPERTY_HINT_RESOURCE_TYPE, "Font"), "set_default_font", "get_default_font"); } Theme::Theme() { - - } - -Theme::~Theme() -{ +Theme::~Theme() { } - - -RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderTheme::load(const String &p_path, const String &p_original_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); - ERR_EXPLAIN("Unable to open theme file: "+p_path); - ERR_FAIL_COND_V(err,RES()); + ERR_EXPLAIN("Unable to open theme file: " + p_path); + ERR_FAIL_COND_V(err, RES()); String base_path = p_path.get_base_dir(); - Ref<Theme> theme( memnew( Theme ) ); - Map<StringName,Variant> library; + Ref<Theme> theme(memnew(Theme)); + Map<StringName, Variant> library; if (r_error) - *r_error=ERR_FILE_CORRUPT; + *r_error = ERR_FILE_CORRUPT; - bool reading_library=false; - int line=0; + bool reading_library = false; + int line = 0; - while(!f->eof_reached()) { + while (!f->eof_reached()) { String l = f->get_line().strip_edges(); line++; int comment = l.find(";"); - if (comment!=-1) - l=l.substr(0,comment); - if (l=="") + if (comment != -1) + l = l.substr(0, comment); + if (l == "") continue; if (l.begins_with("[")) { - if (l=="[library]") { - reading_library=true; - } else if (l=="[theme]") { - reading_library=false; + if (l == "[library]") { + reading_library = true; + } else if (l == "[theme]") { + reading_library = false; } else { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Unknown section type: '" + l + "'."); ERR_FAIL_V(RES()); } continue; } int eqpos = l.find("="); - if (eqpos==-1) { + if (eqpos == -1) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected '='."); ERR_FAIL_V(RES()); } - - String right=l.substr(eqpos+1,l.length()).strip_edges(); - if (right=="") { + String right = l.substr(eqpos + 1, l.length()).strip_edges(); + if (right == "") { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected value after '='."); ERR_FAIL_V(RES()); } @@ -790,15 +743,14 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin value = Color::html(right); } else if (right.begins_with("@")) { //reference - String reference = right.substr(1,right.length()); + String reference = right.substr(1, right.length()); if (!library.has(reference)) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid reference to '"+reference+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid reference to '" + reference + "'."); ERR_FAIL_V(RES()); - } - value=library[reference]; + value = library[reference]; } else if (right.begins_with("default")) { //use default //do none @@ -806,135 +758,128 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin //attempt to parse a constructor int popenpos = right.find("("); - if (popenpos==-1) { + if (popenpos == -1) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid constructor syntax: " + right); ERR_FAIL_V(RES()); } int pclosepos = right.find_last(")"); - if (pclosepos==-1) { - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right); + if (pclosepos == -1) { + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid constructor parameter syntax: " + right); ERR_FAIL_V(RES()); - } - String type = right.substr(0,popenpos); - String param = right.substr(popenpos+1,pclosepos-popenpos-1); - + String type = right.substr(0, popenpos); + String param = right.substr(popenpos + 1, pclosepos - popenpos - 1); - - if (type=="icon") { + if (type == "icon") { String path; if (param.is_abs_path()) - path=param; + path = param; else - path=base_path+"/"+param; + path = base_path + "/" + param; Ref<Texture> texture = ResourceLoader::load(path); if (!texture.is_valid()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Couldn't find icon at path: " + path); ERR_FAIL_V(RES()); } - value=texture; + value = texture; - } else if (type=="sbox") { + } else if (type == "sbox") { String path; if (param.is_abs_path()) - path=param; + path = param; else - path=base_path+"/"+param; + path = base_path + "/" + param; Ref<StyleBox> stylebox = ResourceLoader::load(path); if (!stylebox.is_valid()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find stylebox at path: "+path); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Couldn't find stylebox at path: " + path); ERR_FAIL_V(RES()); } - value=stylebox; + value = stylebox; - } else if (type=="sboxt") { + } else if (type == "sboxt") { Vector<String> params = param.split(","); - if (params.size()!=5 && params.size()!=9) { + if (params.size() != 5 && params.size() != 9) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxt(): '"+right+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid param count for sboxt(): '" + right + "'."); ERR_FAIL_V(RES()); - } - String path=params[0]; + String path = params[0]; if (!param.is_abs_path()) - path=base_path+"/"+path; + path = base_path + "/" + path; Ref<Texture> tex = ResourceLoader::load(path); if (tex.is_null()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Could not open texture for sboxt at path: '"+params[0]+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Could not open texture for sboxt at path: '" + params[0] + "'."); ERR_FAIL_V(RES()); - } - Ref<StyleBoxTexture> sbtex( memnew(StyleBoxTexture) ); + Ref<StyleBoxTexture> sbtex(memnew(StyleBoxTexture)); sbtex->set_texture(tex); - for(int i=0;i<4;i++) { - if (!params[i+1].is_valid_integer()) { + for (int i = 0; i < 4; i++) { + if (!params[i + 1].is_valid_integer()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+1) +", expected integer constant, got: '"+params[i+1]+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid expand margin parameter for sboxt #" + itos(i + 1) + ", expected integer constant, got: '" + params[i + 1] + "'."); ERR_FAIL_V(RES()); } - int margin = params[i+1].to_int(); - sbtex->set_expand_margin_size(Margin(i),margin); + int margin = params[i + 1].to_int(); + sbtex->set_expand_margin_size(Margin(i), margin); } - if (params.size()==9) { + if (params.size() == 9) { - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - if (!params[i+5].is_valid_integer()) { + if (!params[i + 5].is_valid_integer()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+5) +", expected integer constant, got: '"+params[i+5]+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid expand margin parameter for sboxt #" + itos(i + 5) + ", expected integer constant, got: '" + params[i + 5] + "'."); ERR_FAIL_V(RES()); } - int margin = params[i+5].to_int(); - sbtex->set_margin_size(Margin(i),margin); + int margin = params[i + 5].to_int(); + sbtex->set_margin_size(Margin(i), margin); } } value = sbtex; - } else if (type=="sboxf") { + } else if (type == "sboxf") { Vector<String> params = param.split(","); - if (params.size()<2) { + if (params.size() < 2) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxf(): '"+right+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid param count for sboxf(): '" + right + "'."); ERR_FAIL_V(RES()); - } - Ref<StyleBoxFlat> sbflat( memnew(StyleBoxFlat) ); + Ref<StyleBoxFlat> sbflat(memnew(StyleBoxFlat)); if (!params[0].is_valid_integer()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size)."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected integer numeric constant for parameter 0 (border size)."); ERR_FAIL_V(RES()); - } sbflat->set_border_size(params[0].to_int()); @@ -942,19 +887,17 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin if (!params[0].is_valid_integer()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size)."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected integer numeric constant for parameter 0 (border size)."); ERR_FAIL_V(RES()); - } + int left = MIN(params.size() - 1, 3); - int left = MIN( params.size()-1, 3 ); + int ccodes = 0; - int ccodes=0; + for (int i = 0; i < left; i++) { - for(int i=0;i<left;i++) { - - if (params[i+1].is_valid_html_color()) + if (params[i + 1].is_valid_html_color()) ccodes++; else break; @@ -964,173 +907,164 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin Color bright; Color dark; - if (ccodes<1) { + if (ccodes < 1) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Expected at least 1, 2 or 3 html color codes."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected at least 1, 2 or 3 html color codes."); ERR_FAIL_V(RES()); - } else if (ccodes==1) { + } else if (ccodes == 1) { - normal=Color::html(params[1]); - bright=Color::html(params[1]); - dark=Color::html(params[1]); - } else if (ccodes==2) { + normal = Color::html(params[1]); + bright = Color::html(params[1]); + dark = Color::html(params[1]); + } else if (ccodes == 2) { - normal=Color::html(params[1]); - bright=Color::html(params[2]); - dark=Color::html(params[2]); + normal = Color::html(params[1]); + bright = Color::html(params[2]); + dark = Color::html(params[2]); } else { - normal=Color::html(params[1]); - bright=Color::html(params[2]); - dark=Color::html(params[3]); + normal = Color::html(params[1]); + bright = Color::html(params[2]); + dark = Color::html(params[3]); } sbflat->set_dark_color(dark); sbflat->set_light_color(bright); sbflat->set_bg_color(normal); - if (params.size()==ccodes+5) { + if (params.size() == ccodes + 5) { //margins - for(int i=0;i<4;i++) { + for (int i = 0; i < 4; i++) { - if (!params[i+ccodes+1].is_valid_integer()) { + if (!params[i + ccodes + 1].is_valid_integer()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxf #"+itos(i+ccodes+1) +", expected integer constant, got: '"+params[i+ccodes+1]+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid expand margin parameter for sboxf #" + itos(i + ccodes + 1) + ", expected integer constant, got: '" + params[i + ccodes + 1] + "'."); ERR_FAIL_V(RES()); } //int margin = params[i+ccodes+1].to_int(); //sbflat->set_margin_size(Margin(i),margin); } - } else if (params.size()!=ccodes+1) { + } else if (params.size() != ccodes + 1) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid amount of margin parameters for sboxt."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid amount of margin parameters for sboxt."); ERR_FAIL_V(RES()); - } - - value=sbflat; + value = sbflat; } else { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid constructor type: '" + type + "'."); ERR_FAIL_V(RES()); - } - } - //parse left and do something with it - String left= l.substr(0,eqpos); + String left = l.substr(0, eqpos); if (reading_library) { - left=left.strip_edges(); + left = left.strip_edges(); if (!left.is_valid_identifier()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": <LibraryItem> is not a valid identifier."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": <LibraryItem> is not a valid identifier."); ERR_FAIL_V(RES()); } if (library.has(left)) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Already in library: '"+left+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Already in library: '" + left + "'."); ERR_FAIL_V(RES()); } - library[left]=value; + library[left] = value; } else { int pointpos = left.find("."); - if (pointpos==-1) { + if (pointpos == -1) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Expected 'control.item=..' assign syntax."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected 'control.item=..' assign syntax."); ERR_FAIL_V(RES()); } - String control=left.substr(0,pointpos).strip_edges(); + String control = left.substr(0, pointpos).strip_edges(); if (!control.is_valid_identifier()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": <Control> is not a valid identifier."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": <Control> is not a valid identifier."); ERR_FAIL_V(RES()); } - String item=left.substr(pointpos+1,left.size()).strip_edges(); + String item = left.substr(pointpos + 1, left.size()).strip_edges(); if (!item.is_valid_identifier()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": <Item> is not a valid identifier."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": <Item> is not a valid identifier."); ERR_FAIL_V(RES()); } - if (value.get_type()==Variant::NIL) { + if (value.get_type() == Variant::NIL) { //try to use exiting - if (Theme::get_default()->has_stylebox(item,control)) - value=Theme::get_default()->get_stylebox(item,control); - else if (Theme::get_default()->has_font(item,control)) - value=Theme::get_default()->get_font(item,control); - else if (Theme::get_default()->has_icon(item,control)) - value=Theme::get_default()->get_icon(item,control); - else if (Theme::get_default()->has_color(item,control)) - value=Theme::get_default()->get_color(item,control); - else if (Theme::get_default()->has_constant(item,control)) - value=Theme::get_default()->get_constant(item,control); + if (Theme::get_default()->has_stylebox(item, control)) + value = Theme::get_default()->get_stylebox(item, control); + else if (Theme::get_default()->has_font(item, control)) + value = Theme::get_default()->get_font(item, control); + else if (Theme::get_default()->has_icon(item, control)) + value = Theme::get_default()->get_icon(item, control); + else if (Theme::get_default()->has_color(item, control)) + value = Theme::get_default()->get_color(item, control); + else if (Theme::get_default()->has_constant(item, control)) + value = Theme::get_default()->get_constant(item, control); else { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Default not present for: '"+control+"."+item+"'."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Default not present for: '" + control + "." + item + "'."); ERR_FAIL_V(RES()); } - } - if (value.get_type()==Variant::OBJECT) { + if (value.get_type() == Variant::OBJECT) { Ref<Resource> res = value; if (!res.is_valid()) { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource (NULL)."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid resource (NULL)."); ERR_FAIL_V(RES()); } if (res->cast_to<StyleBox>()) { - theme->set_stylebox(item,control,res); + theme->set_stylebox(item, control, res); } else if (res->cast_to<Font>()) { - theme->set_font(item,control,res); + theme->set_font(item, control, res); } else if (res->cast_to<Font>()) { - theme->set_font(item,control,res); + theme->set_font(item, control, res); } else if (res->cast_to<Texture>()) { - theme->set_icon(item,control,res); + theme->set_icon(item, control, res); } else { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource type."); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid resource type."); ERR_FAIL_V(RES()); } - } else if (value.get_type()==Variant::COLOR) { + } else if (value.get_type() == Variant::COLOR) { - theme->set_color(item,control,value); + theme->set_color(item, control, value); - } else if (value.get_type()==Variant::INT) { + } else if (value.get_type() == Variant::INT) { - theme->set_constant(item,control,value); + theme->set_constant(item, control, value); } else { memdelete(f); - ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't even determine what this setting is! what did you do!?"); + ERR_EXPLAIN(p_path + ":" + itos(line) + ": Couldn't even determine what this setting is! what did you do!?"); ERR_FAIL_V(RES()); } - } - - } f->close(); memdelete(f); if (r_error) - *r_error=OK; + *r_error = OK; return theme; } @@ -1140,14 +1074,14 @@ void ResourceFormatLoaderTheme::get_recognized_extensions(List<String> *p_extens p_extensions->push_back("theme"); } -bool ResourceFormatLoaderTheme::handles_type(const String& p_type) const { +bool ResourceFormatLoaderTheme::handles_type(const String &p_type) const { - return p_type=="Theme"; + return p_type == "Theme"; } String ResourceFormatLoaderTheme::get_resource_type(const String &p_path) const { - if (p_path.get_extension().to_lower()=="theme") + if (p_path.get_extension().to_lower() == "theme") return "Theme"; return ""; } diff --git a/scene/resources/theme.h b/scene/resources/theme.h index e9d890cf97..4de6fd78ca 100644 --- a/scene/resources/theme.h +++ b/scene/resources/theme.h @@ -29,42 +29,41 @@ #ifndef THEME_H #define THEME_H +#include "io/resource_loader.h" #include "resource.h" #include "scene/resources/font.h" +#include "scene/resources/shader.h" #include "scene/resources/style_box.h" #include "scene/resources/texture.h" -#include "scene/resources/shader.h" -#include "io/resource_loader.h" /** @author Juan Linietsky <reduzio@gmail.com> */ class Theme : public Resource { - GDCLASS( Theme, Resource ); + GDCLASS(Theme, Resource); RES_BASE_EXTENSION("thm"); static Ref<Theme> default_theme; - //keep a reference count to font, so each time the font changes, we emit theme changed too - Map< Ref<Font>, int> font_refcount; + Map<Ref<Font>, int> font_refcount; void _ref_font(Ref<Font> p_sc); - void _unref_font( Ref<Font> p_sc); + void _unref_font(Ref<Font> p_sc); void _emit_theme_changed(); + HashMap<StringName, HashMap<StringName, Ref<Texture>, StringNameHasher>, StringNameHasher> icon_map; + HashMap<StringName, HashMap<StringName, Ref<StyleBox>, StringNameHasher>, StringNameHasher> style_map; + HashMap<StringName, HashMap<StringName, Ref<Font>, StringNameHasher>, StringNameHasher> font_map; + HashMap<StringName, HashMap<StringName, Ref<Shader>, StringNameHasher>, StringNameHasher> shader_map; + HashMap<StringName, HashMap<StringName, Color, StringNameHasher>, StringNameHasher> color_map; + HashMap<StringName, HashMap<StringName, int, StringNameHasher>, StringNameHasher> constant_map; - HashMap<StringName,HashMap<StringName,Ref<Texture>,StringNameHasher >, StringNameHasher > icon_map; - HashMap<StringName,HashMap<StringName,Ref<StyleBox>,StringNameHasher >,StringNameHasher > style_map; - HashMap<StringName,HashMap<StringName,Ref<Font>,StringNameHasher >,StringNameHasher > font_map; - HashMap<StringName,HashMap<StringName,Ref<Shader>,StringNameHasher >, StringNameHasher > shader_map; - HashMap<StringName,HashMap<StringName,Color,StringNameHasher >,StringNameHasher > color_map; - HashMap<StringName,HashMap<StringName,int,StringNameHasher>,StringNameHasher > constant_map; protected: - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; static Ref<Texture> default_icon; static Ref<StyleBox> default_style; @@ -72,84 +71,134 @@ protected: Ref<Font> default_theme_font; - PoolVector<String> _get_icon_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_icon_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } - PoolVector<String> _get_stylebox_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_stylebox_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } - PoolVector<String> _get_stylebox_types(void) const { PoolVector<String> ilret; List<StringName> il; get_stylebox_types(&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } - PoolVector<String> _get_font_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_font_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } - PoolVector<String> _get_color_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_color_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } - PoolVector<String> _get_constant_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_constant_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } - PoolVector<String> _get_type_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_type_list(&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; } + PoolVector<String> _get_icon_list(const String &p_type) const { + PoolVector<String> ilret; + List<StringName> il; + get_icon_list(p_type, &il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } + PoolVector<String> _get_stylebox_list(const String &p_type) const { + PoolVector<String> ilret; + List<StringName> il; + get_stylebox_list(p_type, &il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } + PoolVector<String> _get_stylebox_types(void) const { + PoolVector<String> ilret; + List<StringName> il; + get_stylebox_types(&il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } + PoolVector<String> _get_font_list(const String &p_type) const { + PoolVector<String> ilret; + List<StringName> il; + get_font_list(p_type, &il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } + PoolVector<String> _get_color_list(const String &p_type) const { + PoolVector<String> ilret; + List<StringName> il; + get_color_list(p_type, &il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } + PoolVector<String> _get_constant_list(const String &p_type) const { + PoolVector<String> ilret; + List<StringName> il; + get_constant_list(p_type, &il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } + PoolVector<String> _get_type_list(const String &p_type) const { + PoolVector<String> ilret; + List<StringName> il; + get_type_list(&il); + for (List<StringName>::Element *E = il.front(); E; E = E->next()) { + ilret.push_back(E->get()); + } + return ilret; + } static void _bind_methods(); -public: +public: static Ref<Theme> get_default(); - static void set_default(const Ref<Theme>& p_default); + static void set_default(const Ref<Theme> &p_default); - static void set_default_icon( const Ref<Texture>& p_icon ); - static void set_default_style( const Ref<StyleBox>& p_default_style); - static void set_default_font( const Ref<Font>& p_default_font ); + static void set_default_icon(const Ref<Texture> &p_icon); + static void set_default_style(const Ref<StyleBox> &p_default_style); + static void set_default_font(const Ref<Font> &p_default_font); - void set_default_theme_font( const Ref<Font>& p_default_font ); + void set_default_theme_font(const Ref<Font> &p_default_font); Ref<Font> get_default_theme_font() const; - void set_icon(const StringName& p_name,const StringName& p_type,const Ref<Texture>& p_icon); - Ref<Texture> get_icon(const StringName& p_name,const StringName& p_type) const; - bool has_icon(const StringName& p_name,const StringName& p_type) const; - void clear_icon(const StringName& p_name,const StringName& p_type); + void set_icon(const StringName &p_name, const StringName &p_type, const Ref<Texture> &p_icon); + Ref<Texture> get_icon(const StringName &p_name, const StringName &p_type) const; + bool has_icon(const StringName &p_name, const StringName &p_type) const; + void clear_icon(const StringName &p_name, const StringName &p_type); void get_icon_list(StringName p_type, List<StringName> *p_list) const; - void set_shader(const StringName& p_name,const StringName& p_type,const Ref<Shader>& p_shader); - Ref<Shader> get_shader(const StringName& p_name,const StringName& p_type) const; - bool has_shader(const StringName& p_name,const StringName& p_type) const; - void clear_shader(const StringName& p_name,const StringName& p_type); - void get_shader_list(const StringName& p_name, List<StringName> *p_list) const; + void set_shader(const StringName &p_name, const StringName &p_type, const Ref<Shader> &p_shader); + Ref<Shader> get_shader(const StringName &p_name, const StringName &p_type) const; + bool has_shader(const StringName &p_name, const StringName &p_type) const; + void clear_shader(const StringName &p_name, const StringName &p_type); + void get_shader_list(const StringName &p_name, List<StringName> *p_list) const; - void set_stylebox(const StringName& p_name,const StringName& p_type,const Ref<StyleBox>& p_style); - Ref<StyleBox> get_stylebox(const StringName& p_name,const StringName& p_type) const; - bool has_stylebox(const StringName& p_name,const StringName& p_type) const; - void clear_stylebox(const StringName& p_name,const StringName& p_type); + void set_stylebox(const StringName &p_name, const StringName &p_type, const Ref<StyleBox> &p_style); + Ref<StyleBox> get_stylebox(const StringName &p_name, const StringName &p_type) const; + bool has_stylebox(const StringName &p_name, const StringName &p_type) const; + void clear_stylebox(const StringName &p_name, const StringName &p_type); void get_stylebox_list(StringName p_type, List<StringName> *p_list) const; void get_stylebox_types(List<StringName> *p_list) const; - void set_font(const StringName& p_name,const StringName& p_type,const Ref<Font>& p_font); - Ref<Font> get_font(const StringName& p_name,const StringName& p_type) const; - bool has_font(const StringName& p_name,const StringName& p_type) const; - void clear_font(const StringName& p_name,const StringName& p_type); + void set_font(const StringName &p_name, const StringName &p_type, const Ref<Font> &p_font); + Ref<Font> get_font(const StringName &p_name, const StringName &p_type) const; + bool has_font(const StringName &p_name, const StringName &p_type) const; + void clear_font(const StringName &p_name, const StringName &p_type); void get_font_list(StringName p_type, List<StringName> *p_list) const; - void set_color(const StringName& p_name,const StringName& p_type,const Color& p_color); - Color get_color(const StringName& p_name,const StringName& p_type) const; - bool has_color(const StringName& p_name,const StringName& p_type) const; - void clear_color(const StringName& p_name,const StringName& p_type); + void set_color(const StringName &p_name, const StringName &p_type, const Color &p_color); + Color get_color(const StringName &p_name, const StringName &p_type) const; + bool has_color(const StringName &p_name, const StringName &p_type) const; + void clear_color(const StringName &p_name, const StringName &p_type); void get_color_list(StringName p_type, List<StringName> *p_list) const; - void set_constant(const StringName& p_name,const StringName& p_type,int p_constant); - int get_constant(const StringName& p_name,const StringName& p_type) const; - bool has_constant(const StringName& p_name,const StringName& p_type) const; - void clear_constant(const StringName& p_name,const StringName& p_type); + void set_constant(const StringName &p_name, const StringName &p_type, int p_constant); + int get_constant(const StringName &p_name, const StringName &p_type) const; + bool has_constant(const StringName &p_name, const StringName &p_type) const; + void clear_constant(const StringName &p_name, const StringName &p_type); void get_constant_list(StringName p_type, List<StringName> *p_list) const; void get_type_list(List<StringName> *p_list) const; - void copy_default_theme(); Theme(); ~Theme(); - }; - class ResourceFormatLoaderTheme : public ResourceFormatLoader { public: - virtual RES load(const String &p_path,const String& p_original_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; - 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; - }; - - #endif diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp index e12d8057d8..3e128379ae 100644 --- a/scene/resources/tile_set.cpp +++ b/scene/resources/tile_set.cpp @@ -28,341 +28,318 @@ /*************************************************************************/ #include "tile_set.h" -bool TileSet::_set(const StringName& p_name, const Variant& p_value) { +bool TileSet::_set(const StringName &p_name, const Variant &p_value) { String n = p_name; int slash = n.find("/"); - if (slash==-1) + if (slash == -1) return false; - int id = String::to_int(n.c_str(),slash); + int id = String::to_int(n.c_str(), slash); if (!tile_map.has(id)) create_tile(id); - String what = n.substr(slash+1,n.length()); - - if (what=="name") - tile_set_name(id,p_value); - else if (what=="texture") - tile_set_texture(id,p_value); - else if (what=="tex_offset") - tile_set_texture_offset(id,p_value); - else if (what=="material") - tile_set_material(id,p_value); - else if (what=="modulate") - tile_set_modulate(id,p_value); - else if (what=="shape_offset") - tile_set_shape_offset(id,p_value); - else if (what=="region") - tile_set_region(id,p_value); - else if (what=="shape") - tile_set_shape(id,p_value); - else if (what=="shapes") - _tile_set_shapes(id,p_value); - else if (what=="occluder") - tile_set_light_occluder(id,p_value); - else if (what=="occluder_offset") - tile_set_occluder_offset(id,p_value); - else if (what=="navigation") - tile_set_navigation_polygon(id,p_value); - else if (what=="navigation_offset") - tile_set_navigation_polygon_offset(id,p_value); + String what = n.substr(slash + 1, n.length()); + + if (what == "name") + tile_set_name(id, p_value); + else if (what == "texture") + tile_set_texture(id, p_value); + else if (what == "tex_offset") + tile_set_texture_offset(id, p_value); + else if (what == "material") + tile_set_material(id, p_value); + else if (what == "modulate") + tile_set_modulate(id, p_value); + else if (what == "shape_offset") + tile_set_shape_offset(id, p_value); + else if (what == "region") + tile_set_region(id, p_value); + else if (what == "shape") + tile_set_shape(id, p_value); + else if (what == "shapes") + _tile_set_shapes(id, p_value); + else if (what == "occluder") + tile_set_light_occluder(id, p_value); + else if (what == "occluder_offset") + tile_set_occluder_offset(id, p_value); + else if (what == "navigation") + tile_set_navigation_polygon(id, p_value); + else if (what == "navigation_offset") + tile_set_navigation_polygon_offset(id, p_value); else return false; return true; - } -bool TileSet::_get(const StringName& p_name,Variant &r_ret) const{ +bool TileSet::_get(const StringName &p_name, Variant &r_ret) const { String n = p_name; int slash = n.find("/"); - if (slash==-1) + if (slash == -1) return false; - int id = String::to_int(n.c_str(),slash); - - ERR_FAIL_COND_V(!tile_map.has(id),false); - - String what = n.substr(slash+1,n.length()); - - if (what=="name") - r_ret=tile_get_name(id); - else if (what=="texture") - r_ret=tile_get_texture(id); - else if (what=="tex_offset") - r_ret=tile_get_texture_offset(id); - else if (what=="material") - r_ret=tile_get_material(id); - else if (what=="modulate") - r_ret=tile_get_modulate(id); - else if (what=="shape_offset") - r_ret=tile_get_shape_offset(id); - else if (what=="region") - r_ret=tile_get_region(id); - else if (what=="shape") - r_ret=tile_get_shape(id); - else if (what=="shapes") - r_ret=_tile_get_shapes(id); - else if (what=="occluder") - r_ret=tile_get_light_occluder(id); - else if (what=="occluder_offset") - r_ret=tile_get_occluder_offset(id); - else if (what=="navigation") - r_ret=tile_get_navigation_polygon(id); - else if (what=="navigation_offset") - r_ret=tile_get_navigation_polygon_offset(id); + int id = String::to_int(n.c_str(), slash); + + ERR_FAIL_COND_V(!tile_map.has(id), false); + + String what = n.substr(slash + 1, n.length()); + + if (what == "name") + r_ret = tile_get_name(id); + else if (what == "texture") + r_ret = tile_get_texture(id); + else if (what == "tex_offset") + r_ret = tile_get_texture_offset(id); + else if (what == "material") + r_ret = tile_get_material(id); + else if (what == "modulate") + r_ret = tile_get_modulate(id); + else if (what == "shape_offset") + r_ret = tile_get_shape_offset(id); + else if (what == "region") + r_ret = tile_get_region(id); + else if (what == "shape") + r_ret = tile_get_shape(id); + else if (what == "shapes") + r_ret = _tile_get_shapes(id); + else if (what == "occluder") + r_ret = tile_get_light_occluder(id); + else if (what == "occluder_offset") + r_ret = tile_get_occluder_offset(id); + else if (what == "navigation") + r_ret = tile_get_navigation_polygon(id); + else if (what == "navigation_offset") + r_ret = tile_get_navigation_polygon_offset(id); else return false; return true; - } -void TileSet::_get_property_list( List<PropertyInfo> *p_list) const{ +void TileSet::_get_property_list(List<PropertyInfo> *p_list) const { - for(Map<int,Data>::Element *E=tile_map.front();E;E=E->next()) { + for (Map<int, Data>::Element *E = tile_map.front(); E; E = E->next()) { int id = E->key(); - String pre = itos(id)+"/"; - p_list->push_back(PropertyInfo(Variant::STRING,pre+"name")); - p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture")); - p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"tex_offset")); - p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"material",PROPERTY_HINT_RESOURCE_TYPE,"CanvasItemMaterial")); - p_list->push_back(PropertyInfo(Variant::COLOR,pre+"modulate")); - p_list->push_back(PropertyInfo(Variant::RECT2,pre+"region")); - p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"occluder_offset")); - p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"occluder",PROPERTY_HINT_RESOURCE_TYPE,"OccluderPolygon2D")); - p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"navigation_offset")); - p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"navigation",PROPERTY_HINT_RESOURCE_TYPE,"NavigationPolygon")); - p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"shape_offset")); - p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D",PROPERTY_USAGE_EDITOR)); - p_list->push_back(PropertyInfo(Variant::ARRAY,pre+"shapes",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); + String pre = itos(id) + "/"; + p_list->push_back(PropertyInfo(Variant::STRING, pre + "name")); + p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "tex_offset")); + p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial")); + p_list->push_back(PropertyInfo(Variant::COLOR, pre + "modulate")); + p_list->push_back(PropertyInfo(Variant::RECT2, pre + "region")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "occluder_offset")); + p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "occluder", PROPERTY_HINT_RESOURCE_TYPE, "OccluderPolygon2D")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "navigation_offset")); + p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "navigation", PROPERTY_HINT_RESOURCE_TYPE, "NavigationPolygon")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "shape_offset")); + p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D", PROPERTY_USAGE_EDITOR)); + p_list->push_back(PropertyInfo(Variant::ARRAY, pre + "shapes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } } void TileSet::create_tile(int p_id) { - ERR_FAIL_COND( tile_map.has(p_id) ); - tile_map[p_id]=Data(); + ERR_FAIL_COND(tile_map.has(p_id)); + tile_map[p_id] = Data(); _change_notify(""); emit_changed(); - } -void TileSet::tile_set_texture(int p_id,const Ref<Texture> &p_texture) { +void TileSet::tile_set_texture(int p_id, const Ref<Texture> &p_texture) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].texture=p_texture; + tile_map[p_id].texture = p_texture; emit_changed(); - } Ref<Texture> TileSet::tile_get_texture(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<Texture>()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<Texture>()); return tile_map[p_id].texture; - } - -void TileSet::tile_set_material(int p_id,const Ref<CanvasItemMaterial> &p_material) { +void TileSet::tile_set_material(int p_id, const Ref<CanvasItemMaterial> &p_material) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].material=p_material; + tile_map[p_id].material = p_material; emit_changed(); - } -Ref<CanvasItemMaterial> TileSet::tile_get_material(int p_id) const{ +Ref<CanvasItemMaterial> TileSet::tile_get_material(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<CanvasItemMaterial>()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<CanvasItemMaterial>()); return tile_map[p_id].material; } - -void TileSet::tile_set_modulate(int p_id,const Color &p_modulate) { +void TileSet::tile_set_modulate(int p_id, const Color &p_modulate) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].modulate=p_modulate; + tile_map[p_id].modulate = p_modulate; emit_changed(); - } -Color TileSet::tile_get_modulate(int p_id) const{ +Color TileSet::tile_get_modulate(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Color(1,1,1)); + ERR_FAIL_COND_V(!tile_map.has(p_id), Color(1, 1, 1)); return tile_map[p_id].modulate; } -void TileSet::tile_set_texture_offset(int p_id,const Vector2 &p_offset) { +void TileSet::tile_set_texture_offset(int p_id, const Vector2 &p_offset) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].offset=p_offset; + tile_map[p_id].offset = p_offset; emit_changed(); } Vector2 TileSet::tile_get_texture_offset(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2()); return tile_map[p_id].offset; - } -void TileSet::tile_set_shape_offset(int p_id,const Vector2 &p_offset) { +void TileSet::tile_set_shape_offset(int p_id, const Vector2 &p_offset) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].shape_offset=p_offset; + tile_map[p_id].shape_offset = p_offset; emit_changed(); } Vector2 TileSet::tile_get_shape_offset(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2()); return tile_map[p_id].shape_offset; - } -void TileSet::tile_set_region(int p_id,const Rect2 &p_region) { +void TileSet::tile_set_region(int p_id, const Rect2 &p_region) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].region=p_region; + tile_map[p_id].region = p_region; emit_changed(); } Rect2 TileSet::tile_get_region(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Rect2()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Rect2()); return tile_map[p_id].region; - } - -void TileSet::tile_set_name(int p_id,const String &p_name) { +void TileSet::tile_set_name(int p_id, const String &p_name) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].name=p_name; + tile_map[p_id].name = p_name; emit_changed(); } String TileSet::tile_get_name(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),String()); + ERR_FAIL_COND_V(!tile_map.has(p_id), String()); return tile_map[p_id].name; - } -void TileSet::tile_set_shape(int p_id,const Ref<Shape2D> &p_shape) { +void TileSet::tile_set_shape(int p_id, const Ref<Shape2D> &p_shape) { ERR_FAIL_COND(!tile_map.has(p_id)); tile_map[p_id].shapes.resize(1); - tile_map[p_id].shapes[0]=p_shape; + tile_map[p_id].shapes[0] = p_shape; emit_changed(); - } Ref<Shape2D> TileSet::tile_get_shape(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<Shape2D>()); - if (tile_map[p_id].shapes.size()>0) + ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<Shape2D>()); + if (tile_map[p_id].shapes.size() > 0) return tile_map[p_id].shapes[0]; return Ref<Shape2D>(); - } -void TileSet::tile_set_light_occluder(int p_id,const Ref<OccluderPolygon2D> &p_light_occluder) { +void TileSet::tile_set_light_occluder(int p_id, const Ref<OccluderPolygon2D> &p_light_occluder) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].occluder=p_light_occluder; - + tile_map[p_id].occluder = p_light_occluder; } -Ref<OccluderPolygon2D> TileSet::tile_get_light_occluder(int p_id) const{ +Ref<OccluderPolygon2D> TileSet::tile_get_light_occluder(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<OccluderPolygon2D>()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<OccluderPolygon2D>()); return tile_map[p_id].occluder; - } -void TileSet::tile_set_navigation_polygon_offset(int p_id,const Vector2& p_offset) { +void TileSet::tile_set_navigation_polygon_offset(int p_id, const Vector2 &p_offset) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].navigation_polygon_offset=p_offset; - + tile_map[p_id].navigation_polygon_offset = p_offset; } -Vector2 TileSet::tile_get_navigation_polygon_offset(int p_id) const{ - ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2()); +Vector2 TileSet::tile_get_navigation_polygon_offset(int p_id) const { + ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2()); return tile_map[p_id].navigation_polygon_offset; } -void TileSet::tile_set_navigation_polygon(int p_id,const Ref<NavigationPolygon> &p_navigation_polygon) { +void TileSet::tile_set_navigation_polygon(int p_id, const Ref<NavigationPolygon> &p_navigation_polygon) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].navigation_polygon=p_navigation_polygon; - + tile_map[p_id].navigation_polygon = p_navigation_polygon; } Ref<NavigationPolygon> TileSet::tile_get_navigation_polygon(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<NavigationPolygon>()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<NavigationPolygon>()); return tile_map[p_id].navigation_polygon; - } -void TileSet::tile_set_occluder_offset(int p_id,const Vector2& p_offset) { +void TileSet::tile_set_occluder_offset(int p_id, const Vector2 &p_offset) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].occluder_offset=p_offset; - + tile_map[p_id].occluder_offset = p_offset; } -Vector2 TileSet::tile_get_occluder_offset(int p_id) const{ - ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2()); +Vector2 TileSet::tile_get_occluder_offset(int p_id) const { + ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2()); return tile_map[p_id].occluder_offset; } -void TileSet::tile_set_shapes(int p_id,const Vector<Ref<Shape2D> > &p_shapes) { +void TileSet::tile_set_shapes(int p_id, const Vector<Ref<Shape2D> > &p_shapes) { ERR_FAIL_COND(!tile_map.has(p_id)); - tile_map[p_id].shapes=p_shapes; + tile_map[p_id].shapes = p_shapes; emit_changed(); - } Vector<Ref<Shape2D> > TileSet::tile_get_shapes(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Vector<Ref<Shape2D> >()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Vector<Ref<Shape2D> >()); return tile_map[p_id].shapes; } -void TileSet::_tile_set_shapes(int p_id,const Array& p_shapes) { +void TileSet::_tile_set_shapes(int p_id, const Array &p_shapes) { ERR_FAIL_COND(!tile_map.has(p_id)); Vector<Ref<Shape2D> > shapes; - for(int i=0;i<p_shapes.size();i++) { + for (int i = 0; i < p_shapes.size(); i++) { Ref<Shape2D> s = p_shapes[i]; if (s.is_valid()) shapes.push_back(s); } - tile_set_shapes(p_id,shapes); + tile_set_shapes(p_id, shapes); } -Array TileSet::_tile_get_shapes(int p_id) const{ +Array TileSet::_tile_get_shapes(int p_id) const { - ERR_FAIL_COND_V(!tile_map.has(p_id),Array()); + ERR_FAIL_COND_V(!tile_map.has(p_id), Array()); Array arr; - Vector<Ref<Shape2D> >shp = tile_map[p_id].shapes; - for(int i=0;i<shp.size();i++) + Vector<Ref<Shape2D> > shp = tile_map[p_id].shapes; + for (int i = 0; i < shp.size(); i++) arr.push_back(shp[i]); return arr; } -Array TileSet::_get_tiles_ids() const{ +Array TileSet::_get_tiles_ids() const { Array arr; @@ -375,11 +352,10 @@ Array TileSet::_get_tiles_ids() const{ void TileSet::get_tile_list(List<int> *p_tiles) const { - for(Map<int,Data>::Element *E=tile_map.front();E;E=E->next()) { + for (Map<int, Data>::Element *E = tile_map.front(); E; E = E->next()) { p_tiles->push_back(E->key()); } - } bool TileSet::has_tile(int p_id) const { @@ -397,20 +373,17 @@ void TileSet::remove_tile(int p_id) { int TileSet::get_last_unused_tile_id() const { - if (tile_map.size()) - return tile_map.back()->key()+1; + return tile_map.back()->key() + 1; else return 0; - } -int TileSet::find_tile_by_name(const String& p_name) const { +int TileSet::find_tile_by_name(const String &p_name) const { + for (Map<int, Data>::Element *E = tile_map.front(); E; E = E->next()) { - for(Map<int,Data>::Element *E=tile_map.front();E;E=E->next()) { - - if (p_name==E->get().name) + if (p_name == E->get().name) return E->key(); } return -1; @@ -425,42 +398,38 @@ void TileSet::clear() { void TileSet::_bind_methods() { - - ClassDB::bind_method(D_METHOD("create_tile","id"),&TileSet::create_tile); - ClassDB::bind_method(D_METHOD("tile_set_name","id","name"),&TileSet::tile_set_name); - ClassDB::bind_method(D_METHOD("tile_get_name","id"),&TileSet::tile_get_name); - ClassDB::bind_method(D_METHOD("tile_set_texture","id","texture:Texture"),&TileSet::tile_set_texture); - ClassDB::bind_method(D_METHOD("tile_get_texture:Texture","id"),&TileSet::tile_get_texture); - ClassDB::bind_method(D_METHOD("tile_set_material","id","material:CanvasItemMaterial"),&TileSet::tile_set_material); - ClassDB::bind_method(D_METHOD("tile_get_material:CanvasItemMaterial","id"),&TileSet::tile_get_material); - ClassDB::bind_method(D_METHOD("tile_set_texture_offset","id","texture_offset"),&TileSet::tile_set_texture_offset); - ClassDB::bind_method(D_METHOD("tile_get_texture_offset","id"),&TileSet::tile_get_texture_offset); - ClassDB::bind_method(D_METHOD("tile_set_shape_offset","id","shape_offset"),&TileSet::tile_set_shape_offset); - ClassDB::bind_method(D_METHOD("tile_get_shape_offset","id"),&TileSet::tile_get_shape_offset); - ClassDB::bind_method(D_METHOD("tile_set_region","id","region"),&TileSet::tile_set_region); - ClassDB::bind_method(D_METHOD("tile_get_region","id"),&TileSet::tile_get_region); - ClassDB::bind_method(D_METHOD("tile_set_shape","id","shape:Shape2D"),&TileSet::tile_set_shape); - ClassDB::bind_method(D_METHOD("tile_get_shape:Shape2D","id"),&TileSet::tile_get_shape); - ClassDB::bind_method(D_METHOD("tile_set_shapes","id","shapes"),&TileSet::_tile_set_shapes); - ClassDB::bind_method(D_METHOD("tile_get_shapes","id"),&TileSet::_tile_get_shapes); - ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon","id","navigation_polygon:NavigationPolygon"),&TileSet::tile_set_navigation_polygon); - ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon:NavigationPolygon","id"),&TileSet::tile_get_navigation_polygon); - ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon_offset","id","navigation_polygon_offset"),&TileSet::tile_set_navigation_polygon_offset); - ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon_offset","id"),&TileSet::tile_get_navigation_polygon_offset); - ClassDB::bind_method(D_METHOD("tile_set_light_occluder","id","light_occluder:OccluderPolygon2D"),&TileSet::tile_set_light_occluder); - ClassDB::bind_method(D_METHOD("tile_get_light_occluder:OccluderPolygon2D","id"),&TileSet::tile_get_light_occluder); - ClassDB::bind_method(D_METHOD("tile_set_occluder_offset","id","occluder_offset"),&TileSet::tile_set_occluder_offset); - ClassDB::bind_method(D_METHOD("tile_get_occluder_offset","id"),&TileSet::tile_get_occluder_offset); - - ClassDB::bind_method(D_METHOD("remove_tile","id"),&TileSet::remove_tile); - ClassDB::bind_method(D_METHOD("clear"),&TileSet::clear); - ClassDB::bind_method(D_METHOD("get_last_unused_tile_id"),&TileSet::get_last_unused_tile_id); - ClassDB::bind_method(D_METHOD("find_tile_by_name","name"),&TileSet::find_tile_by_name); + ClassDB::bind_method(D_METHOD("create_tile", "id"), &TileSet::create_tile); + ClassDB::bind_method(D_METHOD("tile_set_name", "id", "name"), &TileSet::tile_set_name); + ClassDB::bind_method(D_METHOD("tile_get_name", "id"), &TileSet::tile_get_name); + ClassDB::bind_method(D_METHOD("tile_set_texture", "id", "texture:Texture"), &TileSet::tile_set_texture); + ClassDB::bind_method(D_METHOD("tile_get_texture:Texture", "id"), &TileSet::tile_get_texture); + ClassDB::bind_method(D_METHOD("tile_set_material", "id", "material:CanvasItemMaterial"), &TileSet::tile_set_material); + ClassDB::bind_method(D_METHOD("tile_get_material:CanvasItemMaterial", "id"), &TileSet::tile_get_material); + ClassDB::bind_method(D_METHOD("tile_set_texture_offset", "id", "texture_offset"), &TileSet::tile_set_texture_offset); + ClassDB::bind_method(D_METHOD("tile_get_texture_offset", "id"), &TileSet::tile_get_texture_offset); + ClassDB::bind_method(D_METHOD("tile_set_shape_offset", "id", "shape_offset"), &TileSet::tile_set_shape_offset); + ClassDB::bind_method(D_METHOD("tile_get_shape_offset", "id"), &TileSet::tile_get_shape_offset); + ClassDB::bind_method(D_METHOD("tile_set_region", "id", "region"), &TileSet::tile_set_region); + ClassDB::bind_method(D_METHOD("tile_get_region", "id"), &TileSet::tile_get_region); + ClassDB::bind_method(D_METHOD("tile_set_shape", "id", "shape:Shape2D"), &TileSet::tile_set_shape); + ClassDB::bind_method(D_METHOD("tile_get_shape:Shape2D", "id"), &TileSet::tile_get_shape); + ClassDB::bind_method(D_METHOD("tile_set_shapes", "id", "shapes"), &TileSet::_tile_set_shapes); + ClassDB::bind_method(D_METHOD("tile_get_shapes", "id"), &TileSet::_tile_get_shapes); + ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon", "id", "navigation_polygon:NavigationPolygon"), &TileSet::tile_set_navigation_polygon); + ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon:NavigationPolygon", "id"), &TileSet::tile_get_navigation_polygon); + ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon_offset", "id", "navigation_polygon_offset"), &TileSet::tile_set_navigation_polygon_offset); + ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon_offset", "id"), &TileSet::tile_get_navigation_polygon_offset); + ClassDB::bind_method(D_METHOD("tile_set_light_occluder", "id", "light_occluder:OccluderPolygon2D"), &TileSet::tile_set_light_occluder); + ClassDB::bind_method(D_METHOD("tile_get_light_occluder:OccluderPolygon2D", "id"), &TileSet::tile_get_light_occluder); + ClassDB::bind_method(D_METHOD("tile_set_occluder_offset", "id", "occluder_offset"), &TileSet::tile_set_occluder_offset); + ClassDB::bind_method(D_METHOD("tile_get_occluder_offset", "id"), &TileSet::tile_get_occluder_offset); + + ClassDB::bind_method(D_METHOD("remove_tile", "id"), &TileSet::remove_tile); + ClassDB::bind_method(D_METHOD("clear"), &TileSet::clear); + ClassDB::bind_method(D_METHOD("get_last_unused_tile_id"), &TileSet::get_last_unused_tile_id); + ClassDB::bind_method(D_METHOD("find_tile_by_name", "name"), &TileSet::find_tile_by_name); ClassDB::bind_method(D_METHOD("get_tiles_ids", "name"), &TileSet::_get_tiles_ids); - } - TileSet::TileSet() { - } diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h index b80889fc6f..53f68d00a5 100644 --- a/scene/resources/tile_set.h +++ b/scene/resources/tile_set.h @@ -30,14 +30,14 @@ #define TILE_SET_H #include "resource.h" -#include "scene/resources/shape_2d.h" -#include "scene/resources/texture.h" #include "scene/2d/light_occluder_2d.h" #include "scene/2d/navigation_polygon.h" +#include "scene/resources/shape_2d.h" +#include "scene/resources/texture.h" class TileSet : public Resource { - GDCLASS( TileSet, Resource ); + GDCLASS(TileSet, Resource); struct Data { @@ -55,72 +55,69 @@ class TileSet : public Resource { Color modulate; // Default modulate for back-compat - explicit Data() : modulate(1,1,1) {} + explicit Data() + : modulate(1, 1, 1) {} }; - Map<int,Data> tile_map; - + Map<int, Data> tile_map; protected: - - bool _set(const StringName& p_name, const Variant& p_value); - bool _get(const StringName& p_name,Variant &r_ret) const; - void _get_property_list( List<PropertyInfo> *p_list) const; - void _tile_set_shapes(int p_id,const Array& p_shapes); + bool _set(const StringName &p_name, const Variant &p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + void _get_property_list(List<PropertyInfo> *p_list) const; + void _tile_set_shapes(int p_id, const Array &p_shapes); Array _tile_get_shapes(int p_id) const; Array _get_tiles_ids() const; static void _bind_methods(); -public: - - +public: void create_tile(int p_id); - void tile_set_name(int p_id,const String &p_name); + void tile_set_name(int p_id, const String &p_name); String tile_get_name(int p_id) const; void tile_set_texture(int p_id, const Ref<Texture> &p_texture); Ref<Texture> tile_get_texture(int p_id) const; - void tile_set_texture_offset(int p_id,const Vector2 &p_offset); + void tile_set_texture_offset(int p_id, const Vector2 &p_offset); Vector2 tile_get_texture_offset(int p_id) const; - void tile_set_shape_offset(int p_id,const Vector2 &p_offset); + void tile_set_shape_offset(int p_id, const Vector2 &p_offset); Vector2 tile_get_shape_offset(int p_id) const; - void tile_set_region(int p_id,const Rect2 &p_region); + void tile_set_region(int p_id, const Rect2 &p_region); Rect2 tile_get_region(int p_id) const; - void tile_set_shape(int p_id,const Ref<Shape2D> &p_shape); + void tile_set_shape(int p_id, const Ref<Shape2D> &p_shape); Ref<Shape2D> tile_get_shape(int p_id) const; - void tile_set_material(int p_id,const Ref<CanvasItemMaterial> &p_material); + void tile_set_material(int p_id, const Ref<CanvasItemMaterial> &p_material); Ref<CanvasItemMaterial> tile_get_material(int p_id) const; - void tile_set_modulate(int p_id,const Color &p_color); + void tile_set_modulate(int p_id, const Color &p_color); Color tile_get_modulate(int p_id) const; - void tile_set_occluder_offset(int p_id,const Vector2& p_offset); + void tile_set_occluder_offset(int p_id, const Vector2 &p_offset); Vector2 tile_get_occluder_offset(int p_id) const; - void tile_set_light_occluder(int p_id,const Ref<OccluderPolygon2D> &p_light_occluder); + void tile_set_light_occluder(int p_id, const Ref<OccluderPolygon2D> &p_light_occluder); Ref<OccluderPolygon2D> tile_get_light_occluder(int p_id) const; - void tile_set_navigation_polygon_offset(int p_id,const Vector2& p_offset); + void tile_set_navigation_polygon_offset(int p_id, const Vector2 &p_offset); Vector2 tile_get_navigation_polygon_offset(int p_id) const; - void tile_set_navigation_polygon(int p_id,const Ref<NavigationPolygon> &p_navigation_polygon); + void tile_set_navigation_polygon(int p_id, const Ref<NavigationPolygon> &p_navigation_polygon); Ref<NavigationPolygon> tile_get_navigation_polygon(int p_id) const; - void tile_set_shapes(int p_id,const Vector<Ref<Shape2D> > &p_shapes); + void tile_set_shapes(int p_id, const Vector<Ref<Shape2D> > &p_shapes); Vector<Ref<Shape2D> > tile_get_shapes(int p_id) const; void remove_tile(int p_id); bool has_tile(int p_id) const; - int find_tile_by_name(const String& p_name) const; + int find_tile_by_name(const String &p_name) const; void get_tile_list(List<int> *p_tiles) const; void clear(); diff --git a/scene/resources/video_stream.cpp b/scene/resources/video_stream.cpp index 84186616d7..47c40e4e6b 100644 --- a/scene/resources/video_stream.cpp +++ b/scene/resources/video_stream.cpp @@ -28,12 +28,10 @@ /*************************************************************************/ #include "video_stream.h" -void VideoStreamPlayback::_bind_methods() { +void VideoStreamPlayback::_bind_methods(){ }; - -VideoStreamPlayback::VideoStreamPlayback() { +VideoStreamPlayback::VideoStreamPlayback(){ }; - diff --git a/scene/resources/video_stream.h b/scene/resources/video_stream.h index bcd25c0336..7c1bd94c8b 100644 --- a/scene/resources/video_stream.h +++ b/scene/resources/video_stream.h @@ -32,62 +32,56 @@ #include "audio_stream_resampled.h" #include "scene/resources/texture.h" - class VideoStreamPlayback : public Resource { - GDCLASS(VideoStreamPlayback,Resource); + GDCLASS(VideoStreamPlayback, Resource); protected: static void _bind_methods(); public: + typedef int (*AudioMixCallback)(void *p_udata, const int16_t *p_data, int p_frames); - typedef int (*AudioMixCallback)(void* p_udata,const int16_t *p_data,int p_frames); - - virtual void stop()=0; - virtual void play()=0; + virtual void stop() = 0; + virtual void play() = 0; - virtual bool is_playing() const=0; + virtual bool is_playing() const = 0; - virtual void set_paused(bool p_paused)=0; - virtual bool is_paused(bool p_paused) const=0; + virtual void set_paused(bool p_paused) = 0; + virtual bool is_paused(bool p_paused) const = 0; - virtual void set_loop(bool p_enable)=0; - virtual bool has_loop() const=0; + virtual void set_loop(bool p_enable) = 0; + virtual bool has_loop() const = 0; - virtual float get_length() const=0; + virtual float get_length() const = 0; - virtual float get_pos() const=0; - virtual void seek_pos(float p_time)=0; + virtual float get_pos() const = 0; + virtual void seek_pos(float p_time) = 0; - virtual void set_audio_track(int p_idx) =0; + virtual void set_audio_track(int p_idx) = 0; //virtual int mix(int16_t* p_bufer,int p_frames)=0; - virtual Ref<Texture> get_texture()=0; - virtual void update(float p_delta)=0; + virtual Ref<Texture> get_texture() = 0; + virtual void update(float p_delta) = 0; - virtual void set_mix_callback(AudioMixCallback p_callback,void *p_userdata)=0; - virtual int get_channels() const=0; - virtual int get_mix_rate() const=0; + virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) = 0; + virtual int get_channels() const = 0; + virtual int get_mix_rate() const = 0; VideoStreamPlayback(); }; - class VideoStream : public Resource { - GDCLASS( VideoStream, Resource ); - OBJ_SAVE_TYPE( VideoStream ); //children are all saved as AudioStream, so they can be exchanged + GDCLASS(VideoStream, Resource); + OBJ_SAVE_TYPE(VideoStream); //children are all saved as AudioStream, so they can be exchanged public: - - virtual void set_audio_track(int p_track)=0; - virtual Ref<VideoStreamPlayback> instance_playback()=0; + virtual void set_audio_track(int p_track) = 0; + virtual Ref<VideoStreamPlayback> instance_playback() = 0; VideoStream() {} }; - #endif - diff --git a/scene/resources/world.cpp b/scene/resources/world.cpp index f9233d950c..dc62c2ab3e 100644 --- a/scene/resources/world.cpp +++ b/scene/resources/world.cpp @@ -27,76 +27,73 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "world.h" +#include "camera_matrix.h" +#include "octree.h" #include "scene/3d/camera.h" -#include "scene/3d/visibility_notifier.h" #include "scene/3d/spatial_indexer.h" +#include "scene/3d/visibility_notifier.h" #include "scene/scene_string_names.h" -#include "octree.h" -#include "camera_matrix.h" struct SpatialIndexer { - Octree<VisibilityNotifier> octree; struct NotifierData { Rect3 aabb; OctreeElementID id; - }; - Map<VisibilityNotifier*,NotifierData> notifiers; + Map<VisibilityNotifier *, NotifierData> notifiers; struct CameraData { - Map<VisibilityNotifier*,uint64_t> notifiers; + Map<VisibilityNotifier *, uint64_t> notifiers; }; - Map<Camera*,CameraData> cameras; + Map<Camera *, CameraData> cameras; enum { - VISIBILITY_CULL_MAX=32768 + VISIBILITY_CULL_MAX = 32768 }; - Vector<VisibilityNotifier*> cull; + Vector<VisibilityNotifier *> cull; bool changed; uint64_t pass; uint64_t last_frame; - void _notifier_add(VisibilityNotifier* p_notifier,const Rect3& p_rect) { + void _notifier_add(VisibilityNotifier *p_notifier, const Rect3 &p_rect) { ERR_FAIL_COND(notifiers.has(p_notifier)); - notifiers[p_notifier].aabb=p_rect; - notifiers[p_notifier].id = octree.create(p_notifier,p_rect); - changed=true; - + notifiers[p_notifier].aabb = p_rect; + notifiers[p_notifier].id = octree.create(p_notifier, p_rect); + changed = true; } - void _notifier_update(VisibilityNotifier* p_notifier,const Rect3& p_rect) { + void _notifier_update(VisibilityNotifier *p_notifier, const Rect3 &p_rect) { - Map<VisibilityNotifier*,NotifierData>::Element *E=notifiers.find(p_notifier); + Map<VisibilityNotifier *, NotifierData>::Element *E = notifiers.find(p_notifier); ERR_FAIL_COND(!E); - if (E->get().aabb==p_rect) + if (E->get().aabb == p_rect) return; - E->get().aabb=p_rect; - octree.move(E->get().id,E->get().aabb); - changed=true; + E->get().aabb = p_rect; + octree.move(E->get().id, E->get().aabb); + changed = true; } - void _notifier_remove(VisibilityNotifier* p_notifier) { + void _notifier_remove(VisibilityNotifier *p_notifier) { - Map<VisibilityNotifier*,NotifierData>::Element *E=notifiers.find(p_notifier); + Map<VisibilityNotifier *, NotifierData>::Element *E = notifiers.find(p_notifier); ERR_FAIL_COND(!E); octree.erase(E->get().id); notifiers.erase(p_notifier); - List<Camera*> removed; - for (Map<Camera*,CameraData>::Element*F=cameras.front();F;F=F->next()) { + List<Camera *> removed; + for (Map<Camera *, CameraData>::Element *F = cameras.front(); F; F = F->next()) { - Map<VisibilityNotifier*,uint64_t>::Element*G=F->get().notifiers.find(p_notifier); + Map<VisibilityNotifier *, uint64_t>::Element *G = F->get().notifiers.find(p_notifier); if (G) { F->get().notifiers.erase(G); @@ -104,170 +101,154 @@ struct SpatialIndexer { } } - while(!removed.empty()) { + while (!removed.empty()) { p_notifier->_exit_camera(removed.front()->get()); removed.pop_front(); } - - changed=true; + changed = true; } - void _add_camera(Camera* p_camera) { + void _add_camera(Camera *p_camera) { ERR_FAIL_COND(cameras.has(p_camera)); CameraData vd; - cameras[p_camera]=vd; - changed=true; - + cameras[p_camera] = vd; + changed = true; } - void _update_camera(Camera* p_camera) { + void _update_camera(Camera *p_camera) { - Map<Camera*,CameraData>::Element *E= cameras.find(p_camera); + Map<Camera *, CameraData>::Element *E = cameras.find(p_camera); ERR_FAIL_COND(!E); - changed=true; + changed = true; } - void _remove_camera(Camera* p_camera) { + void _remove_camera(Camera *p_camera) { ERR_FAIL_COND(!cameras.has(p_camera)); - List<VisibilityNotifier*> removed; - for(Map<VisibilityNotifier*,uint64_t>::Element *E=cameras[p_camera].notifiers.front();E;E=E->next()) { + List<VisibilityNotifier *> removed; + for (Map<VisibilityNotifier *, uint64_t>::Element *E = cameras[p_camera].notifiers.front(); E; E = E->next()) { removed.push_back(E->key()); } - while(!removed.empty()) { + while (!removed.empty()) { removed.front()->get()->_exit_camera(p_camera); removed.pop_front(); } cameras.erase(p_camera); - } void _update(uint64_t p_frame) { - if (p_frame==last_frame) + if (p_frame == last_frame) return; - last_frame=p_frame; + last_frame = p_frame; if (!changed) return; - - - for (Map<Camera*,CameraData>::Element *E=cameras.front();E;E=E->next()) { + for (Map<Camera *, CameraData>::Element *E = cameras.front(); E; E = E->next()) { pass++; - Camera *c=E->key(); + Camera *c = E->key(); Vector<Plane> planes = c->get_frustum(); - int culled = octree.cull_convex(planes,cull.ptr(),cull.size()); - + int culled = octree.cull_convex(planes, cull.ptr(), cull.size()); - VisibilityNotifier**ptr=cull.ptr(); + VisibilityNotifier **ptr = cull.ptr(); - List<VisibilityNotifier*> added; - List<VisibilityNotifier*> removed; + List<VisibilityNotifier *> added; + List<VisibilityNotifier *> removed; - for(int i=0;i<culled;i++) { + for (int i = 0; i < culled; i++) { //notifiers in frustum - Map<VisibilityNotifier*,uint64_t>::Element *H=E->get().notifiers.find(ptr[i]); + Map<VisibilityNotifier *, uint64_t>::Element *H = E->get().notifiers.find(ptr[i]); if (!H) { - E->get().notifiers.insert(ptr[i],pass); + E->get().notifiers.insert(ptr[i], pass); added.push_back(ptr[i]); } else { - H->get()=pass; + H->get() = pass; } - - } - for (Map<VisibilityNotifier*,uint64_t>::Element *F=E->get().notifiers.front();F;F=F->next()) { + for (Map<VisibilityNotifier *, uint64_t>::Element *F = E->get().notifiers.front(); F; F = F->next()) { - if (F->get()!=pass) + if (F->get() != pass) removed.push_back(F->key()); } - while(!added.empty()) { + while (!added.empty()) { added.front()->get()->_enter_camera(E->key()); added.pop_front(); } - while(!removed.empty()) { + while (!removed.empty()) { E->get().notifiers.erase(removed.front()->get()); removed.front()->get()->_exit_camera(E->key()); removed.pop_front(); } } - changed=false; + changed = false; } - SpatialIndexer() { - pass=0; - last_frame=0; - changed=false; + pass = 0; + last_frame = 0; + changed = false; cull.resize(VISIBILITY_CULL_MAX); } - }; - - -void World::_register_camera(Camera* p_camera) { +void World::_register_camera(Camera *p_camera) { #ifndef _3D_DISABLED indexer->_add_camera(p_camera); #endif } -void World::_update_camera(Camera* p_camera){ +void World::_update_camera(Camera *p_camera) { #ifndef _3D_DISABLED indexer->_update_camera(p_camera); #endif } -void World::_remove_camera(Camera* p_camera){ +void World::_remove_camera(Camera *p_camera) { #ifndef _3D_DISABLED indexer->_remove_camera(p_camera); #endif } - - - -void World::_register_notifier(VisibilityNotifier* p_notifier,const Rect3& p_rect){ +void World::_register_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect) { #ifndef _3D_DISABLED - indexer->_notifier_add(p_notifier,p_rect); + indexer->_notifier_add(p_notifier, p_rect); #endif } -void World::_update_notifier(VisibilityNotifier* p_notifier,const Rect3& p_rect){ +void World::_update_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect) { #ifndef _3D_DISABLED - indexer->_notifier_update(p_notifier,p_rect); + indexer->_notifier_update(p_notifier, p_rect); #endif } -void World::_remove_notifier(VisibilityNotifier* p_notifier){ +void World::_remove_notifier(VisibilityNotifier *p_notifier) { #ifndef _3D_DISABLED indexer->_notifier_remove(p_notifier); #endif } - void World::_update(uint64_t p_frame) { #ifndef _3D_DISABLED @@ -275,26 +256,22 @@ void World::_update(uint64_t p_frame) { #endif } - - - - RID World::get_space() const { return space; } -RID World::get_scenario() const{ +RID World::get_scenario() const { return scenario; } -void World::set_environment(const Ref<Environment>& p_environment) { +void World::set_environment(const Ref<Environment> &p_environment) { - environment=p_environment; + environment = p_environment; if (environment.is_valid()) - VS::get_singleton()->scenario_set_environment(scenario,environment->get_rid()); + VS::get_singleton()->scenario_set_environment(scenario, environment->get_rid()); else - VS::get_singleton()->scenario_set_environment(scenario,RID()); + VS::get_singleton()->scenario_set_environment(scenario, RID()); } Ref<Environment> World::get_environment() const { @@ -302,7 +279,6 @@ Ref<Environment> World::get_environment() const { return environment; } - PhysicsDirectSpaceState *World::get_direct_space_state() { return PhysicsServer::get_singleton()->space_get_direct_state(space); @@ -310,31 +286,29 @@ PhysicsDirectSpaceState *World::get_direct_space_state() { void World::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_space"),&World::get_space); - ClassDB::bind_method(D_METHOD("get_scenario"),&World::get_scenario); - ClassDB::bind_method(D_METHOD("set_environment","env:Environment"),&World::set_environment); - ClassDB::bind_method(D_METHOD("get_environment:Environment"),&World::get_environment); - ClassDB::bind_method(D_METHOD("get_direct_space_state:PhysicsDirectSpaceState"),&World::get_direct_space_state); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"environment",PROPERTY_HINT_RESOURCE_TYPE,"Environment"),"set_environment","get_environment"); - + ClassDB::bind_method(D_METHOD("get_space"), &World::get_space); + ClassDB::bind_method(D_METHOD("get_scenario"), &World::get_scenario); + ClassDB::bind_method(D_METHOD("set_environment", "env:Environment"), &World::set_environment); + ClassDB::bind_method(D_METHOD("get_environment:Environment"), &World::get_environment); + ClassDB::bind_method(D_METHOD("get_direct_space_state:PhysicsDirectSpaceState"), &World::get_direct_space_state); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment", PROPERTY_HINT_RESOURCE_TYPE, "Environment"), "set_environment", "get_environment"); } - World::World() { space = PhysicsServer::get_singleton()->space_create(); scenario = VisualServer::get_singleton()->scenario_create(); - PhysicsServer::get_singleton()->space_set_active(space,true); - PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_GRAVITY,GLOBAL_DEF("physics/3d/default_gravity",9.8)); - PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_GRAVITY_VECTOR,GLOBAL_DEF("physics/3d/default_gravity_vector",Vector3(0,-1,0))); - PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_LINEAR_DAMP,GLOBAL_DEF("physics/3d/default_linear_damp",0.1)); - PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_ANGULAR_DAMP,GLOBAL_DEF("physics/3d/default_angular_damp",0.1)); + PhysicsServer::get_singleton()->space_set_active(space, true); + PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_GRAVITY, GLOBAL_DEF("physics/3d/default_gravity", 9.8)); + PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF("physics/3d/default_gravity_vector", Vector3(0, -1, 0))); + PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/3d/default_linear_damp", 0.1)); + PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/3d/default_angular_damp", 0.1)); #ifdef _3D_DISABLED indexer = NULL; #else - indexer = memnew( SpatialIndexer ); + indexer = memnew(SpatialIndexer); #endif } @@ -344,8 +318,6 @@ World::~World() { VisualServer::get_singleton()->free(scenario); #ifndef _3D_DISABLED - memdelete( indexer ); + memdelete(indexer); #endif - - } diff --git a/scene/resources/world.h b/scene/resources/world.h index 1ad60f3405..a597633ca1 100644 --- a/scene/resources/world.h +++ b/scene/resources/world.h @@ -30,9 +30,9 @@ #define WORLD_H #include "resource.h" +#include "scene/resources/environment.h" #include "servers/physics_server.h" #include "servers/visual_server.h" -#include "scene/resources/environment.h" class SpatialIndexer; class Camera; @@ -41,42 +41,39 @@ class VisibilityNotifier; class World : public Resource { GDCLASS(World, Resource); RES_BASE_EXTENSION("wrd"); + private: RID space; RID scenario; - SpatialIndexer* indexer; + SpatialIndexer *indexer; Ref<Environment> environment; protected: - static void _bind_methods(); -friend class Camera; -friend class VisibilityNotifier; + friend class Camera; + friend class VisibilityNotifier; - void _register_camera(Camera* p_camera); - void _update_camera(Camera* p_camera); - void _remove_camera(Camera* p_camera); + void _register_camera(Camera *p_camera); + void _update_camera(Camera *p_camera); + void _remove_camera(Camera *p_camera); - void _register_notifier(VisibilityNotifier* p_notifier,const Rect3& p_rect); - void _update_notifier(VisibilityNotifier *p_notifier,const Rect3& p_rect); - void _remove_notifier(VisibilityNotifier* p_notifier); -friend class Viewport; + void _register_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect); + void _update_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect); + void _remove_notifier(VisibilityNotifier *p_notifier); + friend class Viewport; void _update(uint64_t p_frame); - public: - RID get_space() const; RID get_scenario() const; - void set_environment(const Ref<Environment>& p_environment); + void set_environment(const Ref<Environment> &p_environment); Ref<Environment> get_environment() const; PhysicsDirectSpaceState *get_direct_space_state(); World(); ~World(); - }; #endif // WORLD_H diff --git a/scene/resources/world_2d.cpp b/scene/resources/world_2d.cpp index 6b745d5d35..cb346199c9 100644 --- a/scene/resources/world_2d.cpp +++ b/scene/resources/world_2d.cpp @@ -27,18 +27,17 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "world_2d.h" -#include "servers/visual_server.h" #include "servers/physics_2d_server.h" +#include "servers/visual_server.h" //#include "servers/spatial_sound_2d_server.h" #include "global_config.h" +#include "global_config.h" +#include "scene/2d/camera_2d.h" #include "scene/2d/visibility_notifier_2d.h" #include "scene/main/viewport.h" -#include "scene/2d/camera_2d.h" -#include "global_config.h" struct SpatialIndexer2D { - struct CellRef { int ref; @@ -53,12 +52,10 @@ struct SpatialIndexer2D { } _FORCE_INLINE_ CellRef() { - ref=0; + ref = 0; } }; - - struct CellKey { union { @@ -69,61 +66,58 @@ struct SpatialIndexer2D { uint64_t key; }; - bool operator==(const CellKey& p_key) const { return key==p_key.key; } - _FORCE_INLINE_ bool operator<(const CellKey& p_key) const { + bool operator==(const CellKey &p_key) const { return key == p_key.key; } + _FORCE_INLINE_ bool operator<(const CellKey &p_key) const { return key < p_key.key; } - }; struct CellData { - Map<VisibilityNotifier2D*,CellRef> notifiers; + Map<VisibilityNotifier2D *, CellRef> notifiers; }; - - Map<CellKey,CellData> cells; + Map<CellKey, CellData> cells; int cell_size; - Map<VisibilityNotifier2D*,Rect2> notifiers; + Map<VisibilityNotifier2D *, Rect2> notifiers; struct ViewportData { - Map<VisibilityNotifier2D*,uint64_t> notifiers; + Map<VisibilityNotifier2D *, uint64_t> notifiers; Rect2 rect; }; - Map<Viewport*,ViewportData> viewports; + Map<Viewport *, ViewportData> viewports; bool changed; uint64_t pass; - - void _notifier_update_cells(VisibilityNotifier2D *p_notifier,const Rect2& p_rect,bool p_add) { + void _notifier_update_cells(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect, bool p_add) { Point2i begin = p_rect.pos; - begin/=cell_size; - Point2i end = p_rect.pos+p_rect.size; - end/=cell_size; - for(int i=begin.x;i<=end.x;i++) { + begin /= cell_size; + Point2i end = p_rect.pos + p_rect.size; + end /= cell_size; + for (int i = begin.x; i <= end.x; i++) { - for(int j=begin.y;j<=end.y;j++) { + for (int j = begin.y; j <= end.y; j++) { CellKey ck; - ck.x=i; - ck.y=j; - Map<CellKey,CellData>::Element *E=cells.find(ck); + ck.x = i; + ck.y = j; + Map<CellKey, CellData>::Element *E = cells.find(ck); if (p_add) { if (!E) - E=cells.insert(ck,CellData()); + E = cells.insert(ck, CellData()); E->get().notifiers[p_notifier].inc(); } else { ERR_CONTINUE(!E); - if (E->get().notifiers[p_notifier].dec()==0) { + if (E->get().notifiers[p_notifier].dec() == 0) { E->get().notifiers.erase(p_notifier); if (E->get().notifiers.empty()) { @@ -135,38 +129,38 @@ struct SpatialIndexer2D { } } - void _notifier_add(VisibilityNotifier2D* p_notifier,const Rect2& p_rect) { + void _notifier_add(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) { ERR_FAIL_COND(notifiers.has(p_notifier)); - notifiers[p_notifier]=p_rect; - _notifier_update_cells(p_notifier,p_rect,true); - changed=true; + notifiers[p_notifier] = p_rect; + _notifier_update_cells(p_notifier, p_rect, true); + changed = true; } - void _notifier_update(VisibilityNotifier2D* p_notifier,const Rect2& p_rect) { + void _notifier_update(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) { - Map<VisibilityNotifier2D*,Rect2>::Element *E=notifiers.find(p_notifier); + Map<VisibilityNotifier2D *, Rect2>::Element *E = notifiers.find(p_notifier); ERR_FAIL_COND(!E); - if (E->get()==p_rect) + if (E->get() == p_rect) return; - _notifier_update_cells(p_notifier,p_rect,true); - _notifier_update_cells(p_notifier,E->get(),false); - E->get()=p_rect; - changed=true; + _notifier_update_cells(p_notifier, p_rect, true); + _notifier_update_cells(p_notifier, E->get(), false); + E->get() = p_rect; + changed = true; } - void _notifier_remove(VisibilityNotifier2D* p_notifier) { + void _notifier_remove(VisibilityNotifier2D *p_notifier) { - Map<VisibilityNotifier2D*,Rect2>::Element *E=notifiers.find(p_notifier); + Map<VisibilityNotifier2D *, Rect2>::Element *E = notifiers.find(p_notifier); ERR_FAIL_COND(!E); - _notifier_update_cells(p_notifier,E->get(),false); + _notifier_update_cells(p_notifier, E->get(), false); notifiers.erase(p_notifier); - List<Viewport*> removed; - for (Map<Viewport*,ViewportData>::Element*F=viewports.front();F;F=F->next()) { + List<Viewport *> removed; + for (Map<Viewport *, ViewportData>::Element *F = viewports.front(); F; F = F->next()) { - Map<VisibilityNotifier2D*,uint64_t>::Element*G=F->get().notifiers.find(p_notifier); + Map<VisibilityNotifier2D *, uint64_t>::Element *G = F->get().notifiers.find(p_notifier); if (G) { F->get().notifiers.erase(G); @@ -174,44 +168,43 @@ struct SpatialIndexer2D { } } - while(!removed.empty()) { + while (!removed.empty()) { p_notifier->_exit_viewport(removed.front()->get()); removed.pop_front(); } - changed=true; + changed = true; } - void _add_viewport(Viewport* p_viewport,const Rect2& p_rect) { + void _add_viewport(Viewport *p_viewport, const Rect2 &p_rect) { ERR_FAIL_COND(viewports.has(p_viewport)); ViewportData vd; - vd.rect=p_rect; - viewports[p_viewport]=vd; - changed=true; - + vd.rect = p_rect; + viewports[p_viewport] = vd; + changed = true; } - void _update_viewport(Viewport* p_viewport, const Rect2& p_rect) { + void _update_viewport(Viewport *p_viewport, const Rect2 &p_rect) { - Map<Viewport*,ViewportData>::Element *E= viewports.find(p_viewport); + Map<Viewport *, ViewportData>::Element *E = viewports.find(p_viewport); ERR_FAIL_COND(!E); - if (E->get().rect==p_rect) + if (E->get().rect == p_rect) return; - E->get().rect=p_rect; - changed=true; + E->get().rect = p_rect; + changed = true; } - void _remove_viewport(Viewport* p_viewport) { + void _remove_viewport(Viewport *p_viewport) { ERR_FAIL_COND(!viewports.has(p_viewport)); - List<VisibilityNotifier2D*> removed; - for(Map<VisibilityNotifier2D*,uint64_t>::Element *E=viewports[p_viewport].notifiers.front();E;E=E->next()) { + List<VisibilityNotifier2D *> removed; + for (Map<VisibilityNotifier2D *, uint64_t>::Element *E = viewports[p_viewport].notifiers.front(); E; E = E->next()) { removed.push_back(E->key()); } - while(!removed.empty()) { + while (!removed.empty()) { removed.front()->get()->_exit_viewport(p_viewport); removed.pop_front(); } @@ -221,45 +214,44 @@ struct SpatialIndexer2D { void _update() { - if (!changed) return; - for (Map<Viewport*,ViewportData>::Element *E=viewports.front();E;E=E->next()) { + for (Map<Viewport *, ViewportData>::Element *E = viewports.front(); E; E = E->next()) { Point2i begin = E->get().rect.pos; - begin/=cell_size; - Point2i end = E->get().rect.pos+E->get().rect.size; - end/=cell_size; + begin /= cell_size; + Point2i end = E->get().rect.pos + E->get().rect.size; + end /= cell_size; pass++; - List<VisibilityNotifier2D*> added; - List<VisibilityNotifier2D*> removed; + List<VisibilityNotifier2D *> added; + List<VisibilityNotifier2D *> removed; - int visible_cells=(end.x-begin.x)*(end.y-begin.y); + int visible_cells = (end.x - begin.x) * (end.y - begin.y); - if (visible_cells>10000) { + if (visible_cells > 10000) { //well you zoomed out a lot, it's your problem. To avoid freezing in the for loops below, we'll manually check cell by cell - for (Map<CellKey,CellData>::Element *F=cells.front();F;F=F->next()) { + for (Map<CellKey, CellData>::Element *F = cells.front(); F; F = F->next()) { - const CellKey &ck=F->key(); + const CellKey &ck = F->key(); - if (ck.x<begin.x || ck.x>end.x) + if (ck.x < begin.x || ck.x > end.x) continue; - if (ck.y<begin.y || ck.y>end.y) + if (ck.y < begin.y || ck.y > end.y) continue; //notifiers in cell - for (Map<VisibilityNotifier2D*,CellRef>::Element *G=F->get().notifiers.front();G;G=G->next()) { + for (Map<VisibilityNotifier2D *, CellRef>::Element *G = F->get().notifiers.front(); G; G = G->next()) { - Map<VisibilityNotifier2D*,uint64_t>::Element *H=E->get().notifiers.find(G->key()); + Map<VisibilityNotifier2D *, uint64_t>::Element *H = E->get().notifiers.find(G->key()); if (!H) { - H=E->get().notifiers.insert(G->key(),pass); + H = E->get().notifiers.insert(G->key(), pass); added.push_back(G->key()); } else { - H->get()=pass; + H->get() = pass; } } } @@ -267,94 +259,87 @@ struct SpatialIndexer2D { } else { //check cells in grid fashion - for(int i=begin.x;i<=end.x;i++) { + for (int i = begin.x; i <= end.x; i++) { - for(int j=begin.y;j<=end.y;j++) { + for (int j = begin.y; j <= end.y; j++) { CellKey ck; - ck.x=i; - ck.y=j; + ck.x = i; + ck.y = j; - Map<CellKey,CellData>::Element *F=cells.find(ck); + Map<CellKey, CellData>::Element *F = cells.find(ck); if (!F) { continue; } - //notifiers in cell - for (Map<VisibilityNotifier2D*,CellRef>::Element *G=F->get().notifiers.front();G;G=G->next()) { + for (Map<VisibilityNotifier2D *, CellRef>::Element *G = F->get().notifiers.front(); G; G = G->next()) { - Map<VisibilityNotifier2D*,uint64_t>::Element *H=E->get().notifiers.find(G->key()); + Map<VisibilityNotifier2D *, uint64_t>::Element *H = E->get().notifiers.find(G->key()); if (!H) { - H=E->get().notifiers.insert(G->key(),pass); + H = E->get().notifiers.insert(G->key(), pass); added.push_back(G->key()); } else { - H->get()=pass; + H->get() = pass; } } } } } - for (Map<VisibilityNotifier2D*,uint64_t>::Element *F=E->get().notifiers.front();F;F=F->next()) { + for (Map<VisibilityNotifier2D *, uint64_t>::Element *F = E->get().notifiers.front(); F; F = F->next()) { - if (F->get()!=pass) + if (F->get() != pass) removed.push_back(F->key()); } - while(!added.empty()) { + while (!added.empty()) { added.front()->get()->_enter_viewport(E->key()); added.pop_front(); } - while(!removed.empty()) { + while (!removed.empty()) { E->get().notifiers.erase(removed.front()->get()); removed.front()->get()->_exit_viewport(E->key()); removed.pop_front(); } } - changed=false; + changed = false; } - SpatialIndexer2D() { - pass=0; - changed=false; - cell_size=100; //should be configurable with GLOBAL_DEF("") i guess + pass = 0; + changed = false; + cell_size = 100; //should be configurable with GLOBAL_DEF("") i guess } - }; +void World2D::_register_viewport(Viewport *p_viewport, const Rect2 &p_rect) { - -void World2D::_register_viewport(Viewport* p_viewport,const Rect2& p_rect) { - - indexer->_add_viewport(p_viewport,p_rect); + indexer->_add_viewport(p_viewport, p_rect); } -void World2D::_update_viewport(Viewport* p_viewport,const Rect2& p_rect){ - - indexer->_update_viewport(p_viewport,p_rect); +void World2D::_update_viewport(Viewport *p_viewport, const Rect2 &p_rect) { + indexer->_update_viewport(p_viewport, p_rect); } -void World2D::_remove_viewport(Viewport* p_viewport){ +void World2D::_remove_viewport(Viewport *p_viewport) { indexer->_remove_viewport(p_viewport); } -void World2D::_register_notifier(VisibilityNotifier2D* p_notifier, const Rect2 &p_rect){ - - indexer->_notifier_add(p_notifier,p_rect); +void World2D::_register_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) { + indexer->_notifier_add(p_notifier, p_rect); } -void World2D::_update_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect){ +void World2D::_update_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) { - indexer->_notifier_update(p_notifier,p_rect); + indexer->_notifier_update(p_notifier, p_rect); } -void World2D::_remove_notifier(VisibilityNotifier2D* p_notifier){ +void World2D::_remove_notifier(VisibilityNotifier2D *p_notifier) { indexer->_notifier_remove(p_notifier); } @@ -364,7 +349,6 @@ void World2D::_update() { indexer->_update(); } - RID World2D::get_canvas() { return canvas; @@ -382,12 +366,11 @@ RID World2D::get_sound_space() { void World2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("get_canvas"),&World2D::get_canvas); - ClassDB::bind_method(D_METHOD("get_space"),&World2D::get_space); - ClassDB::bind_method(D_METHOD("get_sound_space"),&World2D::get_sound_space); - - ClassDB::bind_method(D_METHOD("get_direct_space_state:Physics2DDirectSpaceState"),&World2D::get_direct_space_state); + ClassDB::bind_method(D_METHOD("get_canvas"), &World2D::get_canvas); + ClassDB::bind_method(D_METHOD("get_space"), &World2D::get_space); + ClassDB::bind_method(D_METHOD("get_sound_space"), &World2D::get_sound_space); + ClassDB::bind_method(D_METHOD("get_direct_space_state:Physics2DDirectSpaceState"), &World2D::get_direct_space_state); } Physics2DDirectSpaceState *World2D::get_direct_space_state() { @@ -395,23 +378,20 @@ Physics2DDirectSpaceState *World2D::get_direct_space_state() { return Physics2DServer::get_singleton()->space_get_direct_state(space); } - World2D::World2D() { canvas = VisualServer::get_singleton()->canvas_create(); space = Physics2DServer::get_singleton()->space_create(); //set space2D to be more friendly with pixels than meters, by adjusting some constants - Physics2DServer::get_singleton()->space_set_active(space,true); - Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY,GLOBAL_DEF("physics/2d/default_gravity",98)); - Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,GLOBAL_DEF("physics/2d/default_gravity_vector",Vector2(0,1))); - Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_LINEAR_DAMP,GLOBAL_DEF("physics/2d/default_linear_damp",0.1)); - Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_ANGULAR_DAMP,GLOBAL_DEF("physics/2d/default_angular_damp",1)); - indexer = memnew( SpatialIndexer2D ); - + Physics2DServer::get_singleton()->space_set_active(space, true); + Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_GRAVITY, GLOBAL_DEF("physics/2d/default_gravity", 98)); + Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF("physics/2d/default_gravity_vector", Vector2(0, 1))); + Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/2d/default_linear_damp", 0.1)); + Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/2d/default_angular_damp", 1)); + indexer = memnew(SpatialIndexer2D); } - World2D::~World2D() { VisualServer::get_singleton()->free(canvas); diff --git a/scene/resources/world_2d.h b/scene/resources/world_2d.h index c02880e9ed..2bb5eb1526 100644 --- a/scene/resources/world_2d.h +++ b/scene/resources/world_2d.h @@ -29,9 +29,9 @@ #ifndef WORLD_2D_H #define WORLD_2D_H +#include "global_config.h" #include "resource.h" #include "servers/physics_2d_server.h" -#include "global_config.h" class SpatialIndexer2D; class VisibilityNotifier2D; @@ -39,32 +39,30 @@ class Viewport; class World2D : public Resource { - GDCLASS( World2D, Resource ); + GDCLASS(World2D, Resource); RID canvas; RID space; RID sound_space; - SpatialIndexer2D* indexer; -protected: + SpatialIndexer2D *indexer; +protected: static void _bind_methods(); -friend class Viewport; -friend class VisibilityNotifier2D; + friend class Viewport; + friend class VisibilityNotifier2D; - void _register_viewport(Viewport* p_viewport,const Rect2& p_rect); - void _update_viewport(Viewport* p_viewport,const Rect2& p_rect); - void _remove_viewport(Viewport* p_viewport); + void _register_viewport(Viewport *p_viewport, const Rect2 &p_rect); + void _update_viewport(Viewport *p_viewport, const Rect2 &p_rect); + void _remove_viewport(Viewport *p_viewport); - void _register_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect); - void _update_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect); - void _remove_notifier(VisibilityNotifier2D* p_notifier); + void _register_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect); + void _update_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect); + void _remove_notifier(VisibilityNotifier2D *p_notifier); void _update(); -public: - - +public: RID get_canvas(); RID get_space(); RID get_sound_space(); |